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/App/src/com/dozuki/ifixit/login/ui/OpenIDActivity.java b/App/src/com/dozuki/ifixit/login/ui/OpenIDActivity.java
index e9b5d97c..063255d6 100644
--- a/App/src/com/dozuki/ifixit/login/ui/OpenIDActivity.java
+++ b/App/src/com/dozuki/ifixit/login/ui/OpenIDActivity.java
@@ -1,112 +1,113 @@
package com.dozuki.ifixit.login.ui;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.dozuki.ifixit.MainApplication;
import com.dozuki.ifixit.R;
import com.dozuki.ifixit.dozuki.model.Site;
import org.holoeverywhere.app.Activity;
public class OpenIDActivity extends Activity {
public static String LOGIN_METHOD = "LOGIN_METHOD";
public static String SINGLE_SIGN_ON = "SINGLE_SIGN_ON";
public static String YAHOO_LOGIN = "yahoo";
public static String GOOGLE_LOGIN = "google";
private WebView mWebView;
private String mBaseUrl;
private Site mSite;
private boolean mSingleSignOn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_id_view);
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
Bundle extras = this.getIntent().getExtras();
mSingleSignOn = extras.getBoolean(SINGLE_SIGN_ON, false);
mSite = ((MainApplication)getApplication()).getSite();
String loginUrl;
if (mSingleSignOn) {
loginUrl = mSite.mSsoUrl;
+ mBaseUrl = loginUrl;
} else {
mBaseUrl = mSite.getOpenIdLoginUrl();
final String method = extras.getString(LOGIN_METHOD);
loginUrl = mBaseUrl + method;
}
mWebView = (WebView)findViewById(R.id.open_id_web_view);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().removeAllCookie();
mWebView.loadUrl(loginUrl);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
// Show loading progress in activity's title bar.
@Override
public void onProgressChanged(WebView view, int progress) {
setProgress(progress * 100);
}
});
mWebView.setWebViewClient(new WebViewClient() {
// When start to load page, show url in activity's title bar
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
setTitle(url);
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
// Ignore page loads if it's on the openID site.
if (!url.contains(mSite.mName) || url.contains(mBaseUrl)) {
return;
}
/**
* We've been bounced back to the original site - get the cookie from cookie jar.
*/
String cookie = CookieManager.getInstance().getCookie(url);
if (cookie == null) {
return;
}
// Cookie is a string like NAME=VALUE [; NAME=VALUE]
String[] pairs = cookie.split(";");
for (int i = 0; i < pairs.length; i++) {
String[] parts = pairs[i].split("=", 2);
// If token is found, return it to the calling activity.
if (parts.length == 2 && parts[0].equalsIgnoreCase("session")) {
Intent result = new Intent();
result.putExtra("session", parts[1]);
setResult(RESULT_OK, result);
finish();
return;
}
}
Log.w("iFixit", "Couldn't find session in Cookie from OpenID login");
Intent result = new Intent();
setResult(RESULT_CANCELED, result);
finish();
}
});
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_id_view);
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
Bundle extras = this.getIntent().getExtras();
mSingleSignOn = extras.getBoolean(SINGLE_SIGN_ON, false);
mSite = ((MainApplication)getApplication()).getSite();
String loginUrl;
if (mSingleSignOn) {
loginUrl = mSite.mSsoUrl;
} else {
mBaseUrl = mSite.getOpenIdLoginUrl();
final String method = extras.getString(LOGIN_METHOD);
loginUrl = mBaseUrl + method;
}
mWebView = (WebView)findViewById(R.id.open_id_web_view);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().removeAllCookie();
mWebView.loadUrl(loginUrl);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
// Show loading progress in activity's title bar.
@Override
public void onProgressChanged(WebView view, int progress) {
setProgress(progress * 100);
}
});
mWebView.setWebViewClient(new WebViewClient() {
// When start to load page, show url in activity's title bar
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
setTitle(url);
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
// Ignore page loads if it's on the openID site.
if (!url.contains(mSite.mName) || url.contains(mBaseUrl)) {
return;
}
/**
* We've been bounced back to the original site - get the cookie from cookie jar.
*/
String cookie = CookieManager.getInstance().getCookie(url);
if (cookie == null) {
return;
}
// Cookie is a string like NAME=VALUE [; NAME=VALUE]
String[] pairs = cookie.split(";");
for (int i = 0; i < pairs.length; i++) {
String[] parts = pairs[i].split("=", 2);
// If token is found, return it to the calling activity.
if (parts.length == 2 && parts[0].equalsIgnoreCase("session")) {
Intent result = new Intent();
result.putExtra("session", parts[1]);
setResult(RESULT_OK, result);
finish();
return;
}
}
Log.w("iFixit", "Couldn't find session in Cookie from OpenID login");
Intent result = new Intent();
setResult(RESULT_CANCELED, result);
finish();
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_id_view);
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
Bundle extras = this.getIntent().getExtras();
mSingleSignOn = extras.getBoolean(SINGLE_SIGN_ON, false);
mSite = ((MainApplication)getApplication()).getSite();
String loginUrl;
if (mSingleSignOn) {
loginUrl = mSite.mSsoUrl;
mBaseUrl = loginUrl;
} else {
mBaseUrl = mSite.getOpenIdLoginUrl();
final String method = extras.getString(LOGIN_METHOD);
loginUrl = mBaseUrl + method;
}
mWebView = (WebView)findViewById(R.id.open_id_web_view);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().removeAllCookie();
mWebView.loadUrl(loginUrl);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
// Show loading progress in activity's title bar.
@Override
public void onProgressChanged(WebView view, int progress) {
setProgress(progress * 100);
}
});
mWebView.setWebViewClient(new WebViewClient() {
// When start to load page, show url in activity's title bar
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
setTitle(url);
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
// Ignore page loads if it's on the openID site.
if (!url.contains(mSite.mName) || url.contains(mBaseUrl)) {
return;
}
/**
* We've been bounced back to the original site - get the cookie from cookie jar.
*/
String cookie = CookieManager.getInstance().getCookie(url);
if (cookie == null) {
return;
}
// Cookie is a string like NAME=VALUE [; NAME=VALUE]
String[] pairs = cookie.split(";");
for (int i = 0; i < pairs.length; i++) {
String[] parts = pairs[i].split("=", 2);
// If token is found, return it to the calling activity.
if (parts.length == 2 && parts[0].equalsIgnoreCase("session")) {
Intent result = new Intent();
result.putExtra("session", parts[1]);
setResult(RESULT_OK, result);
finish();
return;
}
}
Log.w("iFixit", "Couldn't find session in Cookie from OpenID login");
Intent result = new Intent();
setResult(RESULT_CANCELED, result);
finish();
}
});
}
|
diff --git a/src/main/java/edu/rit/asksg/domain/Twilio.java b/src/main/java/edu/rit/asksg/domain/Twilio.java
index 9f9e25c..86a394e 100755
--- a/src/main/java/edu/rit/asksg/domain/Twilio.java
+++ b/src/main/java/edu/rit/asksg/domain/Twilio.java
@@ -1,108 +1,109 @@
package edu.rit.asksg.domain;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.SmsFactory;
import com.twilio.sdk.resource.instance.Sms;
import edu.rit.asksg.dataio.ContentProvider;
import edu.rit.asksg.domain.config.ProviderConfig;
import edu.rit.asksg.domain.config.TwilioConfig;
import edu.rit.asksg.service.ConversationService;
import flexjson.JSON;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.entity.RooJpaEntity;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.tostring.RooToString;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RooJavaBean
@RooToString
@RooJpaEntity
@RooJson
public class Twilio extends Service implements ContentProvider {
@Autowired
private transient ConversationService conversationService;
private transient static final Logger logger = LoggerFactory.getLogger(Twilio.class);
@JSON(include = false)
@Override
public List<Conversation> getNewContent() {
logger.debug("Twilio does not support fetching new content.");
return new ArrayList<Conversation>();
}
@JSON(include = false)
@Override
public List<Conversation> getContentSince(LocalDateTime datetime) {
return new ArrayList<Conversation>();
}
@Override
public boolean postContent(Message message) {
final TwilioConfig config = (TwilioConfig) this.getConfig();
TwilioRestClient twc = new TwilioRestClient(config.getUsername(), config.getAuthenticationToken());
Map<String, String> vars = new HashMap<String, String>();
vars.put("Body", message.getContent());
vars.put("From", config.getPhoneNumber());
// This is the fix recommended by Ryan because the UI can't be relied on to send a 'to' >_>
String number = ((Message[])message.getConversation().getMessages().toArray())[0].getAuthor();
+ logger.debug("Twilio: sending message to number: " + number);
vars.put("To", number);
SmsFactory smsFactory = twc.getAccount().getSmsFactory();
try {
Sms sms = smsFactory.create(vars);
//TODO: Twilio can use a callback to POST information to if sending fails
} catch (TwilioRestException e) {
//logger.error("Failed to send outgoing message to " + message.getAuthor(), e);
- e.printStackTrace();
+ logger.error(e.getLocalizedMessage(), e);
return false;
}
return true;
}
@Override
public boolean authenticate() {
return false;
}
@Override
public boolean isAuthenticated() {
return false;
}
public void handleMessage(String smsSid, String accountSid, String from, String to, String body) {
Message msg = new Message();
msg.setContent(body);
msg.setAuthor(from);
msg.setCreated(LocalDateTime.now());
msg.setModified(LocalDateTime.now());
Conversation conv = new Conversation(msg);
msg.setConversation(conv);
conv.setService(this);
conv.setExternalId(smsSid);
conversationService.saveConversation(conv);
}
@JSON(include = false)
public ConversationService getConversationService() {
return conversationService;
}
public void setConversationService(ConversationService conversationService) {
this.conversationService = conversationService;
}
}
| false | true | public boolean postContent(Message message) {
final TwilioConfig config = (TwilioConfig) this.getConfig();
TwilioRestClient twc = new TwilioRestClient(config.getUsername(), config.getAuthenticationToken());
Map<String, String> vars = new HashMap<String, String>();
vars.put("Body", message.getContent());
vars.put("From", config.getPhoneNumber());
// This is the fix recommended by Ryan because the UI can't be relied on to send a 'to' >_>
String number = ((Message[])message.getConversation().getMessages().toArray())[0].getAuthor();
vars.put("To", number);
SmsFactory smsFactory = twc.getAccount().getSmsFactory();
try {
Sms sms = smsFactory.create(vars);
//TODO: Twilio can use a callback to POST information to if sending fails
} catch (TwilioRestException e) {
//logger.error("Failed to send outgoing message to " + message.getAuthor(), e);
e.printStackTrace();
return false;
}
return true;
}
| public boolean postContent(Message message) {
final TwilioConfig config = (TwilioConfig) this.getConfig();
TwilioRestClient twc = new TwilioRestClient(config.getUsername(), config.getAuthenticationToken());
Map<String, String> vars = new HashMap<String, String>();
vars.put("Body", message.getContent());
vars.put("From", config.getPhoneNumber());
// This is the fix recommended by Ryan because the UI can't be relied on to send a 'to' >_>
String number = ((Message[])message.getConversation().getMessages().toArray())[0].getAuthor();
logger.debug("Twilio: sending message to number: " + number);
vars.put("To", number);
SmsFactory smsFactory = twc.getAccount().getSmsFactory();
try {
Sms sms = smsFactory.create(vars);
//TODO: Twilio can use a callback to POST information to if sending fails
} catch (TwilioRestException e) {
//logger.error("Failed to send outgoing message to " + message.getAuthor(), e);
logger.error(e.getLocalizedMessage(), e);
return false;
}
return true;
}
|
diff --git a/src/main/java/com/cosm/client/utils/ObjectUtil.java b/src/main/java/com/cosm/client/utils/ObjectUtil.java
index 151e78c..ed8695c 100644
--- a/src/main/java/com/cosm/client/utils/ObjectUtil.java
+++ b/src/main/java/com/cosm/client/utils/ObjectUtil.java
@@ -1,74 +1,78 @@
package com.cosm.client.utils;
import java.util.Collection;
import com.cosm.client.model.ConnectedObject;
/**
* Utility class to supplement Object
*
* @author s0pau
*
*/
public class ObjectUtil
{
/**
* @param one
* @param two
* @return if both collection are deeply equal - i.e. when both collection
* is the same size and all objects in the collecion is equal by the
* equal() method.
*/
public static <T extends ConnectedObject> boolean deepEquals(Collection<T> one, Collection<T> two)
{
if (!CollectionUtil.deepEquals(one, two))
{
return false;
+ } else if (one == null)
+ {
+ // if deep equal is true and one of them is null, they are both null
+ return true;
}
int matchedCounts = 0;
int i = 1;
int quitEarlyThreshold = (int) Math.round(one.size() / 2 + 0.5);
for (T obj1 : one)
{
if (i >= quitEarlyThreshold && matchedCounts < quitEarlyThreshold)
{
// optimisation - quit early over half of the collection objects
// does not match
return false;
}
for (T obj2 : two)
{
if (obj1.memberEquals((ConnectedObject) two))
{
matchedCounts++;
}
}
i++;
}
return matchedCounts == one.size();
}
/**
* @param one
* @param two
* @return true if both objects are null or both equals(); false otherwise
*/
public static <T extends Object> boolean nullCheckEquals(T one, T two)
{
if (one == null)
{
if (two == null)
{
return true;
}
} else if (one.equals(two))
{
return true;
}
return false;
}
}
| true | true | public static <T extends ConnectedObject> boolean deepEquals(Collection<T> one, Collection<T> two)
{
if (!CollectionUtil.deepEquals(one, two))
{
return false;
}
int matchedCounts = 0;
int i = 1;
int quitEarlyThreshold = (int) Math.round(one.size() / 2 + 0.5);
for (T obj1 : one)
{
if (i >= quitEarlyThreshold && matchedCounts < quitEarlyThreshold)
{
// optimisation - quit early over half of the collection objects
// does not match
return false;
}
for (T obj2 : two)
{
if (obj1.memberEquals((ConnectedObject) two))
{
matchedCounts++;
}
}
i++;
}
return matchedCounts == one.size();
}
| public static <T extends ConnectedObject> boolean deepEquals(Collection<T> one, Collection<T> two)
{
if (!CollectionUtil.deepEquals(one, two))
{
return false;
} else if (one == null)
{
// if deep equal is true and one of them is null, they are both null
return true;
}
int matchedCounts = 0;
int i = 1;
int quitEarlyThreshold = (int) Math.round(one.size() / 2 + 0.5);
for (T obj1 : one)
{
if (i >= quitEarlyThreshold && matchedCounts < quitEarlyThreshold)
{
// optimisation - quit early over half of the collection objects
// does not match
return false;
}
for (T obj2 : two)
{
if (obj1.memberEquals((ConnectedObject) two))
{
matchedCounts++;
}
}
i++;
}
return matchedCounts == one.size();
}
|
diff --git a/src/main/java/de/cubeisland/AntiGuest/prevention/PunishedPrevention.java b/src/main/java/de/cubeisland/AntiGuest/prevention/PunishedPrevention.java
index f5b85aa..6717b51 100644
--- a/src/main/java/de/cubeisland/AntiGuest/prevention/PunishedPrevention.java
+++ b/src/main/java/de/cubeisland/AntiGuest/prevention/PunishedPrevention.java
@@ -1,176 +1,177 @@
package de.cubeisland.AntiGuest.prevention;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.map.hash.THashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.map.hash.TObjectLongHashMap;
import gnu.trove.procedure.TObjectObjectProcedure;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
/**
* This class represents a prevention the player gets punished from
*
* @author Phillip Schichtel
*/
public class PunishedPrevention extends Prevention
{
private final static PunishmentProcedure PUNISHMENT_PROCEDURE = new PunishmentProcedure();
private boolean punish;
private TIntObjectMap<THashMap<Punishment, ConfigurationSection>> violationPunishmentMap;
private TObjectIntMap<Player> playerViolationMap;
private TObjectLongMap<Player> punishThrottleTimestamps;
private int highestPunishmentViolation;
public PunishedPrevention(String name, PreventionPlugin plugin)
{
this(name, PERMISSION_BASE + name, plugin);
}
public PunishedPrevention(String name, String permission, PreventionPlugin plugin)
{
super(name, permission, plugin);
this.highestPunishmentViolation = 0;
}
@Override
public void enable()
{
super.enable();
this.punishThrottleTimestamps = new TObjectLongHashMap<Player>();
this.violationPunishmentMap = new TIntObjectHashMap<THashMap<Punishment, ConfigurationSection>>();
this.playerViolationMap = new TObjectIntHashMap<Player>();
Configuration config = getConfig();
this.punish = config.getBoolean("punish", this.punish);
if (this.punish)
{
ConfigurationSection punishmentsSection = config.getConfigurationSection("punishments");
if (punishmentsSection != null)
{
int violation;
THashMap<Punishment, ConfigurationSection> punishments;
ConfigurationSection violationSection;
ConfigurationSection punishmentSection;
PreventionManager pm = PreventionManager.getInstance();
Punishment punishment;
for (String violationString : punishmentsSection.getKeys(false))
{
try
{
violation = Integer.parseInt(violationString);
punishments = this.violationPunishmentMap.get(violation);
violationSection = punishmentsSection.getConfigurationSection(violationString);
if (violationSection != null)
{
for (String punishmentName : violationSection.getKeys(false))
{
punishment = pm.getPunishment(punishmentName);
if (punishment != null)
{
punishmentSection = violationSection.getConfigurationSection(punishmentName);
if (punishmentSection != null)
{
if (punishments == null)
{
punishments = new THashMap<Punishment, ConfigurationSection>();
this.violationPunishmentMap.put(violation, punishments);
+ this.highestPunishmentViolation = Math.max(this.highestPunishmentViolation, violation);
}
punishments.put(punishment, punishmentSection);
}
}
}
}
}
catch (NumberFormatException e)
{}
}
}
}
}
@Override
public void disable()
{
super.disable();
this.playerViolationMap.clear();
this.punishThrottleTimestamps.clear();
this.violationPunishmentMap.clear();
this.playerViolationMap = null;
this.punishThrottleTimestamps = null;
this.violationPunishmentMap = null;
}
@Override
public Configuration getDefaultConfig()
{
Configuration config = super.getDefaultConfig();
config.set("punish", false);
config.set("punishments.3.slap.damage", 4);
config.set("punishments.5.kick.reason", getPlugin().getTranslation().translate("defaultKickReason"));
return config;
}
public void punish(final Player player)
{
if (!this.punish)
{
return;
}
Integer violations = this.playerViolationMap.get(player);
if (violations == null || violations >= this.highestPunishmentViolation)
{
violations = 0;
}
this.playerViolationMap.put(player, ++violations);
THashMap<Punishment, ConfigurationSection> punishments = this.violationPunishmentMap.get(violations);
if (punishments != null)
{
PUNISHMENT_PROCEDURE.player = player;
punishments.forEachEntry(PUNISHMENT_PROCEDURE);
}
}
public void punishThrottled(Player player)
{
if (!this.punish)
{
return;
}
Long next = (long)this.punishThrottleTimestamps.get(player);
if (next == null)
{
next = 0L;
}
final long current = System.currentTimeMillis();
if (next < current)
{
this.punish(player);
this.punishThrottleTimestamps.put(player, current + getThrottleDelay());
}
}
private static final class PunishmentProcedure implements TObjectObjectProcedure<Punishment, ConfigurationSection>
{
public Player player;
public boolean execute(Punishment punishment, ConfigurationSection config)
{
punishment.punish(this.player, config);
return true;
}
}
}
| true | true | public void enable()
{
super.enable();
this.punishThrottleTimestamps = new TObjectLongHashMap<Player>();
this.violationPunishmentMap = new TIntObjectHashMap<THashMap<Punishment, ConfigurationSection>>();
this.playerViolationMap = new TObjectIntHashMap<Player>();
Configuration config = getConfig();
this.punish = config.getBoolean("punish", this.punish);
if (this.punish)
{
ConfigurationSection punishmentsSection = config.getConfigurationSection("punishments");
if (punishmentsSection != null)
{
int violation;
THashMap<Punishment, ConfigurationSection> punishments;
ConfigurationSection violationSection;
ConfigurationSection punishmentSection;
PreventionManager pm = PreventionManager.getInstance();
Punishment punishment;
for (String violationString : punishmentsSection.getKeys(false))
{
try
{
violation = Integer.parseInt(violationString);
punishments = this.violationPunishmentMap.get(violation);
violationSection = punishmentsSection.getConfigurationSection(violationString);
if (violationSection != null)
{
for (String punishmentName : violationSection.getKeys(false))
{
punishment = pm.getPunishment(punishmentName);
if (punishment != null)
{
punishmentSection = violationSection.getConfigurationSection(punishmentName);
if (punishmentSection != null)
{
if (punishments == null)
{
punishments = new THashMap<Punishment, ConfigurationSection>();
this.violationPunishmentMap.put(violation, punishments);
}
punishments.put(punishment, punishmentSection);
}
}
}
}
}
catch (NumberFormatException e)
{}
}
}
}
}
| public void enable()
{
super.enable();
this.punishThrottleTimestamps = new TObjectLongHashMap<Player>();
this.violationPunishmentMap = new TIntObjectHashMap<THashMap<Punishment, ConfigurationSection>>();
this.playerViolationMap = new TObjectIntHashMap<Player>();
Configuration config = getConfig();
this.punish = config.getBoolean("punish", this.punish);
if (this.punish)
{
ConfigurationSection punishmentsSection = config.getConfigurationSection("punishments");
if (punishmentsSection != null)
{
int violation;
THashMap<Punishment, ConfigurationSection> punishments;
ConfigurationSection violationSection;
ConfigurationSection punishmentSection;
PreventionManager pm = PreventionManager.getInstance();
Punishment punishment;
for (String violationString : punishmentsSection.getKeys(false))
{
try
{
violation = Integer.parseInt(violationString);
punishments = this.violationPunishmentMap.get(violation);
violationSection = punishmentsSection.getConfigurationSection(violationString);
if (violationSection != null)
{
for (String punishmentName : violationSection.getKeys(false))
{
punishment = pm.getPunishment(punishmentName);
if (punishment != null)
{
punishmentSection = violationSection.getConfigurationSection(punishmentName);
if (punishmentSection != null)
{
if (punishments == null)
{
punishments = new THashMap<Punishment, ConfigurationSection>();
this.violationPunishmentMap.put(violation, punishments);
this.highestPunishmentViolation = Math.max(this.highestPunishmentViolation, violation);
}
punishments.put(punishment, punishmentSection);
}
}
}
}
}
catch (NumberFormatException e)
{}
}
}
}
}
|
diff --git a/src/com/untamedears/ItemExchange/listeners/ItemExchangeListener.java b/src/com/untamedears/ItemExchange/listeners/ItemExchangeListener.java
index 52f2a82..c8c8534 100644
--- a/src/com/untamedears/ItemExchange/listeners/ItemExchangeListener.java
+++ b/src/com/untamedears/ItemExchange/listeners/ItemExchangeListener.java
@@ -1,151 +1,151 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.untamedears.ItemExchange.listeners;
import static org.bukkit.event.block.Action.LEFT_CLICK_BLOCK;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import com.untamedears.ItemExchange.ItemExchangePlugin;
import com.untamedears.ItemExchange.exceptions.ExchangeRuleParseException;
import com.untamedears.ItemExchange.utility.ExchangeRule;
import com.untamedears.ItemExchange.utility.ItemExchange;
/**
*
* @author Brian Landry
*/
public class ItemExchangeListener implements Listener {
/**
* Constructor
*/
public ItemExchangeListener() {
}
/*
* Responds when a player interacts with a shop
*/
@EventHandler
public void playerInteractionEvent(PlayerInteractEvent e) {
Player player = e.getPlayer();
ItemStack itemStack = e.getItem();
// If a player using an interacting action
if (e.getAction() == LEFT_CLICK_BLOCK) {
// If block is a possible exchange
if (ItemExchangePlugin.ACCEPTABLE_BLOCKS.contains(e.getClickedBlock().getType())) {
// If the block contains exchangeItems
Inventory exchangeInventory = ((InventoryHolder) e.getClickedBlock().getState()).getInventory();
ItemExchange itemExchange = ItemExchange.getItemExchange(exchangeInventory);
if (itemExchange.isValid()) {
itemExchange.playerResponse(player, itemStack, e.getClickedBlock().getLocation());
}
}
}
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (event.isShiftClick()) {
try {
ItemStack currentItem = event.getCurrentItem();
int itemAmount = currentItem.getAmount();
ExchangeRule exchangeRule = ExchangeRule.parseRuleBlock(currentItem);
int amount = exchangeRule.getAmount();
if (event.isLeftClick()) {
exchangeRule.setAmount(amount + 1);
}
else {
if (amount > 1)
exchangeRule.setAmount(amount - 1);
}
ItemStack itemstack = exchangeRule.toItemStack();
itemstack.setAmount(itemAmount);
event.setCurrentItem(itemstack);
event.setCancelled(true);
}
catch (ExchangeRuleParseException e) {
}
}
final Inventory top = event.getView().getTopInventory();
- if(top.getType() == InventoryType.CRAFTING && event.getWhoClicked() instanceof Player) {
+ if(top instanceof CraftingInventory && event.getWhoClicked() instanceof Player) {
final Player player = (Player) event.getWhoClicked();
Bukkit.getScheduler().scheduleSyncDelayedTask(ItemExchangePlugin.instance, new Runnable() {
@SuppressWarnings("deprecation")
public void run() {
CraftingInventory inv = (CraftingInventory) top;
List<ExchangeRule> exchangeRules = new ArrayList<ExchangeRule>();
for(ItemStack item : inv.getMatrix()) {
if(item != null && item.getType() != Material.AIR) {
try {
exchangeRules.add(ExchangeRule.parseRuleBlock(item));
}
catch(ExchangeRuleParseException e) {
try {
exchangeRules.addAll(Arrays.asList(ExchangeRule.parseBulkRuleBlock(item)));
}
catch(ExchangeRuleParseException e2) {
return;
}
}
}
}
if(exchangeRules.size() > 0) {
inv.setResult(ExchangeRule.toBulkItemStack(exchangeRules));
player.updateInventory();
}
}
});
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) {
try {
ExchangeRule[] rules = ExchangeRule.parseBulkRuleBlock(event.getItemDrop().getItemStack());
Item drop = event.getItemDrop();
for(ExchangeRule rule : rules) {
ItemStack item = rule.toItemStack();
Item ruleDrop = drop.getWorld().dropItem(drop.getLocation(), item);
ruleDrop.setVelocity(drop.getVelocity());
}
drop.remove();
}
catch (ExchangeRuleParseException e) {
}
}
}
| true | true | public void onInventoryClick(InventoryClickEvent event) {
if (event.isShiftClick()) {
try {
ItemStack currentItem = event.getCurrentItem();
int itemAmount = currentItem.getAmount();
ExchangeRule exchangeRule = ExchangeRule.parseRuleBlock(currentItem);
int amount = exchangeRule.getAmount();
if (event.isLeftClick()) {
exchangeRule.setAmount(amount + 1);
}
else {
if (amount > 1)
exchangeRule.setAmount(amount - 1);
}
ItemStack itemstack = exchangeRule.toItemStack();
itemstack.setAmount(itemAmount);
event.setCurrentItem(itemstack);
event.setCancelled(true);
}
catch (ExchangeRuleParseException e) {
}
}
final Inventory top = event.getView().getTopInventory();
if(top.getType() == InventoryType.CRAFTING && event.getWhoClicked() instanceof Player) {
final Player player = (Player) event.getWhoClicked();
Bukkit.getScheduler().scheduleSyncDelayedTask(ItemExchangePlugin.instance, new Runnable() {
@SuppressWarnings("deprecation")
public void run() {
CraftingInventory inv = (CraftingInventory) top;
List<ExchangeRule> exchangeRules = new ArrayList<ExchangeRule>();
for(ItemStack item : inv.getMatrix()) {
if(item != null && item.getType() != Material.AIR) {
try {
exchangeRules.add(ExchangeRule.parseRuleBlock(item));
}
catch(ExchangeRuleParseException e) {
try {
exchangeRules.addAll(Arrays.asList(ExchangeRule.parseBulkRuleBlock(item)));
}
catch(ExchangeRuleParseException e2) {
return;
}
}
}
}
if(exchangeRules.size() > 0) {
inv.setResult(ExchangeRule.toBulkItemStack(exchangeRules));
player.updateInventory();
}
}
});
}
}
| public void onInventoryClick(InventoryClickEvent event) {
if (event.isShiftClick()) {
try {
ItemStack currentItem = event.getCurrentItem();
int itemAmount = currentItem.getAmount();
ExchangeRule exchangeRule = ExchangeRule.parseRuleBlock(currentItem);
int amount = exchangeRule.getAmount();
if (event.isLeftClick()) {
exchangeRule.setAmount(amount + 1);
}
else {
if (amount > 1)
exchangeRule.setAmount(amount - 1);
}
ItemStack itemstack = exchangeRule.toItemStack();
itemstack.setAmount(itemAmount);
event.setCurrentItem(itemstack);
event.setCancelled(true);
}
catch (ExchangeRuleParseException e) {
}
}
final Inventory top = event.getView().getTopInventory();
if(top instanceof CraftingInventory && event.getWhoClicked() instanceof Player) {
final Player player = (Player) event.getWhoClicked();
Bukkit.getScheduler().scheduleSyncDelayedTask(ItemExchangePlugin.instance, new Runnable() {
@SuppressWarnings("deprecation")
public void run() {
CraftingInventory inv = (CraftingInventory) top;
List<ExchangeRule> exchangeRules = new ArrayList<ExchangeRule>();
for(ItemStack item : inv.getMatrix()) {
if(item != null && item.getType() != Material.AIR) {
try {
exchangeRules.add(ExchangeRule.parseRuleBlock(item));
}
catch(ExchangeRuleParseException e) {
try {
exchangeRules.addAll(Arrays.asList(ExchangeRule.parseBulkRuleBlock(item)));
}
catch(ExchangeRuleParseException e2) {
return;
}
}
}
}
if(exchangeRules.size() > 0) {
inv.setResult(ExchangeRule.toBulkItemStack(exchangeRules));
player.updateInventory();
}
}
});
}
}
|
diff --git a/projects/common/src/org/jscsi/core/scsi/Status.java b/projects/common/src/org/jscsi/core/scsi/Status.java
index d29a2dfe..3e520388 100644
--- a/projects/common/src/org/jscsi/core/scsi/Status.java
+++ b/projects/common/src/org/jscsi/core/scsi/Status.java
@@ -1,263 +1,263 @@
package org.jscsi.core.scsi;
import java.util.HashMap;
import java.util.Map;
/**
* This enumerations defines all valid statuses, which are defined in the iSCSI
* Standard (RFC 3720) and the SCSI Architecture Model 2 [SAM2].
* <p>
* <table border="1">
* <tr>
* <th>Status Code</th>
* <th>Status</th>
* <th>Task Ended</th>
* <th>Service Response</th>
* </tr>
*
* <tr>
* <td>00h</td>
* <td>{@link #GOOD}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* <tr>
* <td>02h</td>
* <td>{@link #CHECK_CONDITION}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* <tr>
* <td>04h</td>
* <td>{@link #CONDITION_MET}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* <tr>
* <td>08h</td>
* <td>{@link #BUSY}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* <tr>
* <td>10h</td>
* <td>{@link #INTERMEDIATE}</td>
* <td>No</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#LINKED_COMMAND_COMPLETE}</td>
* </tr>
* <tr>
* <td>14h</td>
* <td>{@link #INTERMEDIATE_CONDITION_MET}</td>
* <td>No</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#LINKED_COMMAND_COMPLETE}</td>
* </tr>
* <tr>
* <td>18h</td>
* <td>{@link #RESERVATION_CONFLICT}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* <tr>
* <td>22h</td>
* <td colspan="3">Obsolete</td>
* </tr>
* <tr>
* <td>28h</td>
* <td>{@link #TASK_SET_FULL}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* <tr>
* <td>30h</td>
* <td>{@link #ACA_ACTIVE}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* <tr>
* <td>40h</td>
* <td>{@link #TASK_ABORTED}</td>
* <td>Yes</td>
* <td>{@link org.jscsi.scsi.transport.ServiceResponse#TASK_COMPLETE}</td>
* </tr>
* </table>
* <p>
* All other codes are reserved.
*
* @author Volker Wildi
*/
public enum Status {
/**
* This status indicates that the device server has successfully completed the
* task.
*/
GOOD((byte) 0x00),
/**
* This status indicates that an CA or ACA condition has occurred (see 5.9.1).
* Autosense data may be delivered (see 5.9.4.3)[SAM2].
*/
CHECK_CONDITION((byte) 0x02),
/**
* This status shall be returned whenever the requested operation specified by
* an unlinked command is satisfied (see the PRE-FETCH commands in the SBC
* standard).
*/
CONDITION_MET((byte) 0x04),
/**
* This status indicates that the logical unit is busy. This status shall be
* returned whenever a logical unit is temporarily unable to accept a command.
* The recommended application client recovery action is to issue the command
* again at a later time. If the UA_INTLCK_CTRL field in the Control mode page
* contains 11b (see SPC-3), termination of a command with BUSY status shall
* cause an unit attention condition to be established for the SCSI initiator
* port that sent the command with an additional sense code of PREVIOUS BUSY
* STATUS unless a PREVIOUS BUSY STATUS unit attention condition already
* exists.
*/
BUSY((byte) 0x08),
/**
* This status or INTERMEDIATE-CONDITION MET shall be returned for each
* successfully completed command in a series of linked commands (except the
* last command), unless the command is termi- nated with CHECK CONDITION,
* RESERVATION CONFLICT, TASK SET FULL, or BUSY status. If INTERME- DIATE or
* INTERMEDIATE-CONDITION MET status is not returned, the series of linked
* commands is terminated and the task is ended. This status is the equivalent
* of GOOD status for linked commands.
*/
INTERMEDIATE((byte) 0x10),
/**
* This status is returned whenever the requested operation specified by a
* linked command is satisfied (see the PRE-FETCH commands in the SBC
* standard), unless the command is termi- nated with CHECK CONDITION,
* RESERVATION CONFLICT, TASK SET FULL, or BUSY status. If INTERME- DIATE or
* INTERMEDIATE-CONDITION MET status is not returned, the series of linked
* commands is terminated and the task is ended.
*/
INTERMEDIATE_CONDITION_MET((byte) 0x14),
/**
* This status shall be returned whenever a SCSI initiator port attempts to
* access a logical unit or an element of a logical unit in a way that
* conflicts with an existing reservation. (See the RESERVE, RELEASE,
* PERSISTENT RESERVE OUT and PERSISTENT RESERVE IN commands in SPC-2).
* <p>
* If the UA_INTLCK_CTRL field in the Control mode page contains 11b (see
* SPC-3), termination of a command with RESERVATION CONFLICT status shall
* cause an unit attention condition to be established for the SCSI initiator
* port that sent the command with an additional sense code of PREVIOUS
* RESERVATION CONFLICT STATUS unless a PREVIOUS RESERVATION CONFLICT STATUS
* unit attention condition already exists.
*/
RESERVATION_CONFLICT((byte) 0x18),
/**
* This status shall be implemented if the logical unit supports the creation
* of tagged tasks (see 4.10)[SAM2]. This status shall not be implemented if
* the logical unit does not support the creation of tagged tasks.
* <p>
* When the logical unit has at least one task in the task set for a SCSI
* initiator port and a lack of task set resources prevents accepting a
* received tagged task from that SCSI initiator port into the task set, TASK
* SET FULL shall be returned. When the logical unit has no task in the task
* set for a SCSI initiator port and a lack of task set resources prevents
* accepting a received tagged task from that SCSI initiator port into the
* task set, BUSY should be returned.
* <p>
* When the logical unit has at least one task in the task set and a lack of
* task set resources prevents accepting a received untagged task into the
* task set, BUSY should be returned.
* <p>
* The logical unit should allow at least one command in the task set for each
* supported SCSI initiator port that has identified itself to the SCSI target
* port by a SCSI transport protocol specific procedure or by the successful
* transmission of a command.
* <p>
* If the UA_INTLCK_CTRL field in the Control mode page contains 11b (see
* SPC-3), termination of a command with TASK SET FULL status shall cause an
* unit attention condition to be established for the SCSI initiator port that
* sent the command with an additional sense code of PREVIOUS TASK SET FULL
* STATUS unless a PREVIOUS TASK SET FULL STATUS unit attention condition
* already exists.
*/
TASK_SET_FULL((byte) 0x28),
/**
* This status shall be returned when an ACA exists within a task set and a
* SCSI initiator port issues a command for that task set when at least one of
* the following is true:
* <ol type="a">
* <li>There is a task with the ACA attribute (see 7.5.4)[SAM2] in the task
* set;</li>
* <li>The SCSI initiator port issuing the command did not cause the ACA
* condition; or</li>
* <li>The task created to process the command did not have the ACA attribute
* and the NACA bit was set to one in the CDB CONTROL byte of the faulting
* command (see 5.9.1)[SAM2].</li>
* </ol>
* The SCSI initiator port may reissue the command after the ACA condition has
* been cleared.
*/
ACA_ACTIVE((byte) 0x30),
/**
* This status shall be returned when a task is aborted by another SCSI
* initiator port and the Control mode page TAS bit is set to one (see
* 5.7.3)[SAM2].
*/
TASK_ABORTED((byte) 0x40);
private final byte value;
private static Map<Byte, Status> mapping;
private Status(final byte newValue) {
if (Status.mapping == null) {
Status.mapping = new HashMap<Byte, Status>();
}
Status.mapping.put(newValue, this);
value = newValue;
}
/**
* Returns the value of this enumeration.
*
* @return The value of this enumeration.
*/
public final byte value() {
return value;
}
/**
* Returns the constant defined for the given <code>value</code>.
*
* @param value
* The value to search for.
* @return The constant defined for the given <code>value</code>. Or
* <code>null</code>, if this value is not defined by this
* enumeration.
*/
public static final Status valueOf(final byte value) {
return Status.mapping.get(value);
}
@Override
public String toString()
{
- String output = "<Status:";
+ String output = "<Status: flag: ' ";
switch(Status.valueOf(value))
{
- case GOOD: output += " good"; break;
- case CHECK_CONDITION: output += " check condition"; break;
- case CONDITION_MET: output += " condition met"; break;
- case BUSY: output += " busy"; break;
- case INTERMEDIATE: output += " intermediate"; break;
- case INTERMEDIATE_CONDITION_MET: output += " intermediate condition met"; break;
- case RESERVATION_CONFLICT: output += " reservation conflict"; break;
- case TASK_SET_FULL: output += " task set full"; break;
- case ACA_ACTIVE: output += " aca active"; break;
- case TASK_ABORTED: output += " task aborted"; break;
+ case GOOD: output += "GOOD"; break;
+ case CHECK_CONDITION: output += "CHECK CONDITION"; break;
+ case CONDITION_MET: output += "CONDITION MET"; break;
+ case BUSY: output += "BUSY"; break;
+ case INTERMEDIATE: output += "INTERMEDIATE"; break;
+ case INTERMEDIATE_CONDITION_MET: output += "INTERMEDIATE CONDITION MET"; break;
+ case RESERVATION_CONFLICT: output += "RESERVATION CONFLICT"; break;
+ case TASK_SET_FULL: output += "TASK SET FULL"; break;
+ case ACA_ACTIVE: output += "ACA ACTIVE"; break;
+ case TASK_ABORTED: output += "TASK ABORTED"; break;
}
- return output + ">";
+ return output + "'>";
}
}
| false | true | public String toString()
{
String output = "<Status:";
switch(Status.valueOf(value))
{
case GOOD: output += " good"; break;
case CHECK_CONDITION: output += " check condition"; break;
case CONDITION_MET: output += " condition met"; break;
case BUSY: output += " busy"; break;
case INTERMEDIATE: output += " intermediate"; break;
case INTERMEDIATE_CONDITION_MET: output += " intermediate condition met"; break;
case RESERVATION_CONFLICT: output += " reservation conflict"; break;
case TASK_SET_FULL: output += " task set full"; break;
case ACA_ACTIVE: output += " aca active"; break;
case TASK_ABORTED: output += " task aborted"; break;
}
return output + ">";
}
| public String toString()
{
String output = "<Status: flag: ' ";
switch(Status.valueOf(value))
{
case GOOD: output += "GOOD"; break;
case CHECK_CONDITION: output += "CHECK CONDITION"; break;
case CONDITION_MET: output += "CONDITION MET"; break;
case BUSY: output += "BUSY"; break;
case INTERMEDIATE: output += "INTERMEDIATE"; break;
case INTERMEDIATE_CONDITION_MET: output += "INTERMEDIATE CONDITION MET"; break;
case RESERVATION_CONFLICT: output += "RESERVATION CONFLICT"; break;
case TASK_SET_FULL: output += "TASK SET FULL"; break;
case ACA_ACTIVE: output += "ACA ACTIVE"; break;
case TASK_ABORTED: output += "TASK ABORTED"; break;
}
return output + "'>";
}
|
diff --git a/src/com/herocraftonline/dev/heroes/damage/HeroesDamageListener.java b/src/com/herocraftonline/dev/heroes/damage/HeroesDamageListener.java
index aa18ef19..23b9942f 100644
--- a/src/com/herocraftonline/dev/heroes/damage/HeroesDamageListener.java
+++ b/src/com/herocraftonline/dev/heroes/damage/HeroesDamageListener.java
@@ -1,654 +1,656 @@
package com.herocraftonline.dev.heroes.damage;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.api.HeroAttackDamageCause;
import com.herocraftonline.dev.heroes.api.HeroDamageCause;
import com.herocraftonline.dev.heroes.api.HeroSkillDamageCause;
import com.herocraftonline.dev.heroes.api.SkillDamageEvent;
import com.herocraftonline.dev.heroes.api.SkillUseInfo;
import com.herocraftonline.dev.heroes.api.WeaponDamageEvent;
import com.herocraftonline.dev.heroes.damage.DamageManager.ProjectileType;
import com.herocraftonline.dev.heroes.effects.Effect;
import com.herocraftonline.dev.heroes.effects.EffectManager;
import com.herocraftonline.dev.heroes.effects.EffectType;
import com.herocraftonline.dev.heroes.hero.Hero;
import com.herocraftonline.dev.heroes.party.HeroParty;
import com.herocraftonline.dev.heroes.skill.Skill;
import com.herocraftonline.dev.heroes.skill.SkillType;
import com.herocraftonline.dev.heroes.util.Messaging;
import com.herocraftonline.dev.heroes.util.Util;
public class HeroesDamageListener extends EntityListener {
private Heroes plugin;
private DamageManager damageManager;
private Map<Integer, Integer> healthMap = new HashMap<Integer, Integer>();
private boolean ignoreNextDamageEventBecauseWolvesAreOnCrack = true;
public HeroesDamageListener(Heroes plugin, DamageManager damageManager) {
this.plugin = plugin;
this.damageManager = damageManager;
}
@Override
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
Heroes.debug.startTask("HeroesDamageListener.onEntityRegainHealth");
if (event.isCancelled() || !(event.getEntity() instanceof Player)) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityRegainHealth");
return;
}
double amount = event.getAmount();
Player player = (Player) event.getEntity();
Hero hero = plugin.getHeroManager().getHero(player);
double maxHealth = hero.getMaxHealth();
// Satiated players regenerate % of total HP rather than 1 HP
if (event.getRegainReason() == RegainReason.SATIATED) {
double healPercent = Heroes.properties.foodHealPercent;
amount = maxHealth * healPercent;
}
double newHeroHealth = hero.getHealth() + amount;
if (newHeroHealth > maxHealth)
newHeroHealth = maxHealth;
int newPlayerHealth = (int) (newHeroHealth / maxHealth * 20);
hero.setHealth(newHeroHealth);
//Sanity test
int newAmount = newPlayerHealth - player.getHealth();
if (newAmount < 0)
newAmount = 0;
event.setAmount(newAmount);
Heroes.debug.stopTask("HeroesDamageListener.onEntityRegainHealth");
}
private int onEntityDamageCore(EntityDamageEvent event, Entity attacker, int damage) {
if (attacker instanceof Player) {
Player attackingPlayer = (Player) attacker;
Hero hero = plugin.getHeroManager().getHero(attackingPlayer);
if (!hero.canEquipItem(attackingPlayer.getInventory().getHeldItemSlot()) || hero.hasEffectType(EffectType.STUN)) {
event.setCancelled(true);
return 0;
}
// Get the damage this player should deal for the weapon they are using
damage = getPlayerDamage(attackingPlayer, damage);
} else if (attacker instanceof LivingEntity) {
CreatureType type = Util.getCreatureFromEntity(attacker);
if (type != null) {
if (type == CreatureType.WOLF) {
if (ignoreNextDamageEventBecauseWolvesAreOnCrack) {
ignoreNextDamageEventBecauseWolvesAreOnCrack = false;
return 0;
} else {
ignoreNextDamageEventBecauseWolvesAreOnCrack = true;
}
}
Integer tmpDamage = damageManager.getEntityDamage(type);
if (tmpDamage != null) {
damage = tmpDamage;
}
}
} else if (attacker instanceof Projectile) {
Projectile projectile = (Projectile) attacker;
if (projectile.getShooter() instanceof Player) {
attacker = projectile.getShooter();
// Allow alteration of player damage
damage = getPlayerProjectileDamage((Player) projectile.getShooter(), projectile, damage);
damage = (int) Math.ceil(damage / 3.0 * projectile.getVelocity().length());
} else {
attacker = projectile.getShooter();
CreatureType type = Util.getCreatureFromEntity(projectile.getShooter());
if (type != null) {
Integer tmpDamage = damageManager.getEntityDamage(type);
if (tmpDamage != null) {
damage = tmpDamage;
}
}
}
}
// Call the custom event to allow skills to adjust weapon damage
WeaponDamageEvent weaponDamageEvent = new WeaponDamageEvent(damage, (EntityDamageByEntityEvent) event);
plugin.getServer().getPluginManager().callEvent(weaponDamageEvent);
if (weaponDamageEvent.isCancelled()) {
event.setCancelled(true);
return 0 ;
}
damage = weaponDamageEvent.getDamage();
if (event.getEntity() instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) event.getEntity());
hero.setLastDamageCause(new HeroAttackDamageCause(damage, event.getCause(), attacker));
}
return damage;
}
@Override
public void onEntityDamage(EntityDamageEvent event) {
Heroes.debug.startTask("HeroesDamageListener.onEntityDamage");
// Reasons to immediately ignore damage event
if (event.isCancelled() || Heroes.properties.disabledWorlds.contains(event.getEntity().getWorld().getName())) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
Entity defender = event.getEntity();
Entity attacker = null;
HeroDamageCause lastDamage = null;
int damage = event.getDamage();
//Lets figure out who the attacker is
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (subEvent.getDamager() instanceof Projectile) {
attacker = ((Projectile) subEvent.getDamager()).getShooter();
} else {
attacker = subEvent.getDamager();
}
}
if (defender instanceof Player) {
if (((Player) defender).getGameMode() == GameMode.CREATIVE || ((Player) defender).isDead()) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
lastDamage = plugin.getHeroManager().getHero((Player) defender).getLastDamageCause();
}
if (damageManager.isSpellTarget(defender)) {
damage = onSpellDamage(event, damage, defender);
} else {
DamageCause cause = event.getCause();
switch (cause) {
case SUICIDE:
if (defender instanceof Player) {
Player player = (Player) event.getEntity();
plugin.getHeroManager().getHero(player).setHealth(0D);
event.setDamage(1000); //OVERKILLLLL!!
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
break;
case ENTITY_ATTACK:
case ENTITY_EXPLOSION:
case PROJECTILE:
damage = onEntityDamageCore(event, attacker, damage);
break;
case FALL:
damage = onEntityFall(event.getDamage(), defender);
break;
case SUFFOCATION:
damage = onEntitySuffocate(event.getDamage(), defender);
break;
case DROWNING:
damage = onEntityDrown(event.getDamage(), defender, event);
break;
case STARVATION:
damage = onEntityStarve(event.getDamage(), defender);
break;
case FIRE:
case LAVA:
case FIRE_TICK:
damage = onEntityFlame(event.getDamage(), cause, defender, event);
break;
default:
break;
}
//Check if one of the Method calls cancelled the event due to resistances etc.
if (event.isCancelled()) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
if (defender instanceof Player) {
plugin.getHeroManager().getHero((Player) defender).setLastDamageCause(lastDamage);
}
return;
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
if (player.getNoDamageTicks() > 10 || player.isDead() || player.getHealth() <= 0) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
final Hero hero = plugin.getHeroManager().getHero(player);
//check player inventory to make sure they aren't wearing restricted items
hero.checkInventory();
//Loop through the player's effects and check to see if we need to remove them
if (hero.hasEffectType(EffectType.INVULNERABILITY)) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
for (Effect effect : hero.getEffects()) {
if ((effect.isType(EffectType.ROOT) || effect.isType(EffectType.INVIS)) && !effect.isType(EffectType.UNBREAKABLE)) {
hero.removeEffect(effect);
}
}
// Party damage & PvPable test
if (attacker instanceof Player) {
// If the players aren't within the level range then deny the PvP
int aLevel = plugin.getHeroManager().getHero((Player) attacker).getTieredLevel(false);
if (Math.abs(aLevel - hero.getTieredLevel(false)) > Heroes.properties.pvpLevelRange) {
Messaging.send((Player) attacker, "That player is outside of your level range!");
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
HeroParty party = hero.getParty();
if (party != null && party.isNoPvp()) {
if (party.isPartyMember((Player) attacker)) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
}
}
if (damage == 0) {
event.setDamage(0);
return;
}
switch (event.getCause()) {
case FIRE:
case LAVA:
case BLOCK_EXPLOSION:
case CONTACT:
case ENTITY_EXPLOSION:
case ENTITY_ATTACK:
case PROJECTILE:
hero.setHealth(hero.getHealth() - (damage * calculateArmorReduction(player.getInventory())));
break;
default:
hero.setHealth(hero.getHealth() - damage);
}
event.setDamage(convertHeroesDamage(damage, player));
//If the player would drop to 0 but they still have HP left, don't let them die.
if (hero.getHealth() != 0 && player.getHealth() == 1 && event.getDamage() == 1)
player.setHealth(2);
// Make sure health syncs on the next tick
if (hero.getHealth() == 0)
event.setDamage(200);
else
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
hero.syncHealth();
}
}, 1);
//Update the party display
HeroParty party = hero.getParty();
if (party != null && damage > 0) {
party.update();
}
} else if (defender instanceof LivingEntity) {
// Do Damage calculations based on maximum health and current health
final LivingEntity lEntity = (LivingEntity) defender;
int maxHealth = getMaxHealth(lEntity);
Integer currentHealth = healthMap.get(lEntity.getEntityId());
if (currentHealth == null) {
currentHealth = (int) (lEntity.getHealth() / (double) lEntity.getMaxHealth()) * maxHealth;
}
currentHealth -= damage;
if (currentHealth <= 0) {
healthMap.remove(lEntity.getEntityId());
damage = 100;
} else {
healthMap.put(lEntity.getEntityId(), currentHealth);
damage = convertHeroesDamage(damage, (LivingEntity) defender);
int difference = lEntity.getHealth() - damage;
if (difference <= 0) {
lEntity.setHealth(lEntity.getHealth() + 1 - difference);
}
//Only re-sync if the max health for this
if (maxHealth != lEntity.getMaxHealth()) {
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
+ if (lEntity == null || lEntity.isDead())
+ return;
int maxMCHP = lEntity.getMaxHealth();
double percent = healthMap.get(lEntity.getEntityId()) / (double) getMaxHealth(lEntity);
int newHP = (int) (maxMCHP * percent);
if (newHP == 0)
newHP = 1;
lEntity.setHealth(newHP);
}
}, 1);
}
}
event.setDamage(damage);
}
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
}
private int onSpellDamage(EntityDamageEvent event, int damage, Entity defender) {
SkillUseInfo skillInfo = damageManager.getSpellTargetInfo(defender);
damageManager.removeSpellTarget(defender);
if (event instanceof EntityDamageByEntityEvent) {
if (resistanceCheck(defender, skillInfo.getSkill())) {
if (defender instanceof Player)
skillInfo.getSkill().broadcast(defender.getLocation(), "$1 has resisted $2", ((Player) defender).getDisplayName(), skillInfo.getSkill().getName());
else if (defender instanceof LivingEntity)
skillInfo.getSkill().broadcast(defender.getLocation(), "$1 has resisted $2", Messaging.getLivingEntityName((LivingEntity) defender), skillInfo.getSkill().getName());
event.setCancelled(true);
return 0;
}
SkillDamageEvent spellDamageEvent = new SkillDamageEvent(damage, defender, skillInfo);
plugin.getServer().getPluginManager().callEvent(spellDamageEvent);
if (spellDamageEvent.isCancelled()) {
event.setCancelled(true);
return 0;
}
damage = spellDamageEvent.getDamage();
if (defender instanceof Player) {
plugin.getHeroManager().getHero((Player) defender).setLastDamageCause(new HeroSkillDamageCause(damage, event.getCause(), skillInfo.getHero().getPlayer(), skillInfo.getSkill()));
}
}
return damage;
}
/**
* Returns a percentage adjusted damage value for starvation
*
* @param percent
* @param entity
* @return
*/
private int onEntityStarve(double defaultDamage, Entity entity) {
Double percent = damageManager.getEnvironmentalDamage(DamageCause.STARVATION);
if (percent == null) {
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
hero.setLastDamageCause(new HeroDamageCause((int) defaultDamage, DamageCause.STARVATION));
}
return (int) defaultDamage;
}
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
percent *= hero.getMaxHealth();
hero.setLastDamageCause(new HeroDamageCause((int) (double) percent, DamageCause.STARVATION));
} else if (entity instanceof LivingEntity) {
Integer creatureHealth = damageManager.getEntityHealth(Util.getCreatureFromEntity(entity));
if (creatureHealth != null)
percent *= creatureHealth;
}
return percent < 1 ? 1 : (int) (double) percent;
}
/**
* Returns a percentage adjusted damage value for suffocation
*
* @param percent
* @param entity
* @return
*/
private int onEntitySuffocate(double defaultDamage, Entity entity) {
Double percent = damageManager.getEnvironmentalDamage(DamageCause.SUFFOCATION);
if (percent == null) {
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
hero.setLastDamageCause(new HeroDamageCause((int) defaultDamage, DamageCause.SUFFOCATION));
}
return (int) defaultDamage;
}
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
percent *= hero.getMaxHealth();
hero.setLastDamageCause(new HeroDamageCause((int) (double) percent, DamageCause.SUFFOCATION));
} else if (entity instanceof LivingEntity) {
Integer creatureHealth = damageManager.getEntityHealth(Util.getCreatureFromEntity(entity));
if (creatureHealth != null)
percent *= creatureHealth;
}
return percent < 1 ? 1 : (int) (double) percent;
}
/**
* Returns a percentage adjusted damage value for drowning
*
* @param percent
* @param entity
* @return
*/
private int onEntityDrown(double defaultDamage, Entity entity, EntityDamageEvent event) {
Double percent = damageManager.getEnvironmentalDamage(DamageCause.DROWNING);
if (percent == null) {
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
hero.setLastDamageCause(new HeroDamageCause((int) defaultDamage, DamageCause.DROWNING));
}
return (int) defaultDamage;
}
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
if (hero.hasEffectType(EffectType.WATER_BREATHING)) {
event.setCancelled(true);
return 0;
}
percent *= hero.getMaxHealth();
hero.setLastDamageCause(new HeroDamageCause((int) (double) percent, DamageCause.DROWNING));
} else if (entity instanceof LivingEntity) {
if (plugin.getEffectManager().entityHasEffectType((LivingEntity) entity, EffectType.WATER_BREATHING)) {
event.setCancelled(true);
return 0;
}
Integer creatureHealth = damageManager.getEntityHealth(Util.getCreatureFromEntity(entity));
if (creatureHealth != null)
percent *= creatureHealth;
}
return percent < 1 ? 1 : (int) (double) percent;
}
/**
* Adjusts damage for Fire damage events.
*
* @param damage
* @param cause
* @param entity
* @return
*/
private int onEntityFlame(double defaultDamage, DamageCause cause, Entity entity, EntityDamageEvent event) {
Double damage = damageManager.getEnvironmentalDamage(cause);
if (damage == null) {
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
hero.setLastDamageCause(new HeroDamageCause((int) defaultDamage, cause));
}
return (int) defaultDamage;
}
if (damage == 0)
return 0;
if (entity instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) entity);
if (hero.hasEffectType(EffectType.RESIST_FIRE)) {
event.setCancelled(true);
return 0;
}
if (cause != DamageCause.FIRE_TICK)
damage *= hero.getMaxHealth();
hero.setLastDamageCause(new HeroDamageCause((int) (double) damage, cause));
} else if (entity instanceof LivingEntity) {
if (plugin.getEffectManager().entityHasEffectType((LivingEntity) entity, EffectType.RESIST_FIRE)) {
event.setCancelled(true);
return 0;
}
if (cause != DamageCause.FIRE_TICK) {
Integer creatureHealth = damageManager.getEntityHealth(Util.getCreatureFromEntity(entity));
if (creatureHealth != null)
damage *= creatureHealth;
}
}
return damage < 1 ? 1 : (int) (double) damage;
}
/**
* Adjusts the damage being dealt during a fall
*
* @param damage
* @param entity
* @return
*/
private int onEntityFall(int damage, Entity entity) {
Double damagePercent = damageManager.getEnvironmentalDamage(DamageCause.FALL);
if (damagePercent == null)
return damage;
if (damage == 0)
return 0;
if (entity instanceof Player) {
Hero dHero = plugin.getHeroManager().getHero((Player) entity);
if (dHero.hasEffectType(EffectType.SAFEFALL))
return 0;
damage = (int) (damage * damagePercent * dHero.getMaxHealth());
} else if (entity instanceof LivingEntity) {
if (plugin.getEffectManager().entityHasEffectType((LivingEntity) entity, EffectType.SAFEFALL))
return 0;
Integer creatureHealth = damageManager.getEntityHealth(Util.getCreatureFromEntity(entity));
if (creatureHealth != null)
damage = (int) (damage * damagePercent * creatureHealth);
}
return damage < 1 ? 1 : damage;
}
private double calculateArmorReduction(PlayerInventory inventory) {
double percent = 1;
int armorPoints = 0;
for (ItemStack armor : inventory.getArmorContents()) {
if (armor == null)
continue;
switch (armor.getType()) {
case LEATHER_HELMET:
case LEATHER_BOOTS:
case GOLD_BOOTS:
case CHAINMAIL_BOOTS:
armorPoints += 1;
continue;
case GOLD_HELMET:
case IRON_HELMET:
case CHAINMAIL_HELMET:
case LEATHER_LEGGINGS:
case IRON_BOOTS:
armorPoints += 2;
continue;
case DIAMOND_HELMET:
case LEATHER_CHESTPLATE:
case GOLD_LEGGINGS:
case DIAMOND_BOOTS:
armorPoints += 3;
continue;
case CHAINMAIL_LEGGINGS:
armorPoints += 4;
continue;
case GOLD_CHESTPLATE:
case CHAINMAIL_CHESTPLATE:
case IRON_LEGGINGS:
armorPoints += 5;
continue;
case IRON_CHESTPLATE:
case DIAMOND_LEGGINGS:
armorPoints += 6;
continue;
case DIAMOND_CHESTPLATE:
armorPoints += 8;
continue;
}
}
percent = (25 - armorPoints) / 25D;
return percent;
}
private int getPlayerDamage(Player attacker, int damage) {
ItemStack weapon = attacker.getItemInHand();
Material weaponType = weapon.getType();
Integer tmpDamage = damageManager.getItemDamage(weaponType, attacker);
return tmpDamage == null ? damage : tmpDamage;
}
private int getPlayerProjectileDamage(Player attacker, Projectile projectile, int damage) {
Integer tmpDamage = damageManager.getProjectileDamage(ProjectileType.valueOf(projectile), attacker);
return tmpDamage == null ? damage : tmpDamage;
}
private boolean resistanceCheck(Entity defender, Skill skill) {
if (defender instanceof Player) {
Hero hero = plugin.getHeroManager().getHero((Player) defender);
if (hero.hasEffectType(EffectType.RESIST_FIRE) && skill.isType(SkillType.FIRE))
return true;
else if (hero.hasEffectType(EffectType.RESIST_DARK) && skill.isType(SkillType.DARK))
return true;
else if (hero.hasEffectType(EffectType.RESIST_LIGHT) && skill.isType(SkillType.LIGHT))
return true;
else if (hero.hasEffectType(EffectType.RESIST_LIGHTNING) && skill.isType(SkillType.LIGHTNING))
return true;
else if (hero.hasEffectType(EffectType.RESIST_ICE) && skill.isType(SkillType.ICE))
return true;
} else if (defender instanceof LivingEntity) {
EffectManager em = plugin.getEffectManager();
LivingEntity c = (LivingEntity) defender;
if (em.entityHasEffectType(c, EffectType.RESIST_FIRE) && skill.isType(SkillType.FIRE))
return true;
else if (em.entityHasEffectType(c, EffectType.RESIST_DARK) && skill.isType(SkillType.DARK))
return true;
else if (em.entityHasEffectType(c, EffectType.LIGHT) && skill.isType(SkillType.LIGHT))
return true;
else if (em.entityHasEffectType(c, EffectType.RESIST_LIGHTNING) && skill.isType(SkillType.LIGHTNING))
return true;
else if (em.entityHasEffectType(c, EffectType.RESIST_ICE) && skill.isType(SkillType.ICE))
return true;
}
return false;
}
private int convertHeroesDamage(double d, LivingEntity lEntity) {
int maxHealth = getMaxHealth(lEntity);
int damage = (int) ((lEntity.getMaxHealth() / (double) maxHealth) * d);
if (damage == 0)
damage = 1;
return damage;
}
public int getMaxHealth(LivingEntity lEntity) {
if (lEntity instanceof Player)
return (int) plugin.getHeroManager().getHero((Player) lEntity).getMaxHealth();
else {
Integer maxHP = plugin.getDamageManager().getEntityHealth(Util.getCreatureFromEntity(lEntity));
return maxHP != null ? maxHP : lEntity.getMaxHealth();
}
}
}
| true | true | public void onEntityDamage(EntityDamageEvent event) {
Heroes.debug.startTask("HeroesDamageListener.onEntityDamage");
// Reasons to immediately ignore damage event
if (event.isCancelled() || Heroes.properties.disabledWorlds.contains(event.getEntity().getWorld().getName())) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
Entity defender = event.getEntity();
Entity attacker = null;
HeroDamageCause lastDamage = null;
int damage = event.getDamage();
//Lets figure out who the attacker is
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (subEvent.getDamager() instanceof Projectile) {
attacker = ((Projectile) subEvent.getDamager()).getShooter();
} else {
attacker = subEvent.getDamager();
}
}
if (defender instanceof Player) {
if (((Player) defender).getGameMode() == GameMode.CREATIVE || ((Player) defender).isDead()) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
lastDamage = plugin.getHeroManager().getHero((Player) defender).getLastDamageCause();
}
if (damageManager.isSpellTarget(defender)) {
damage = onSpellDamage(event, damage, defender);
} else {
DamageCause cause = event.getCause();
switch (cause) {
case SUICIDE:
if (defender instanceof Player) {
Player player = (Player) event.getEntity();
plugin.getHeroManager().getHero(player).setHealth(0D);
event.setDamage(1000); //OVERKILLLLL!!
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
break;
case ENTITY_ATTACK:
case ENTITY_EXPLOSION:
case PROJECTILE:
damage = onEntityDamageCore(event, attacker, damage);
break;
case FALL:
damage = onEntityFall(event.getDamage(), defender);
break;
case SUFFOCATION:
damage = onEntitySuffocate(event.getDamage(), defender);
break;
case DROWNING:
damage = onEntityDrown(event.getDamage(), defender, event);
break;
case STARVATION:
damage = onEntityStarve(event.getDamage(), defender);
break;
case FIRE:
case LAVA:
case FIRE_TICK:
damage = onEntityFlame(event.getDamage(), cause, defender, event);
break;
default:
break;
}
//Check if one of the Method calls cancelled the event due to resistances etc.
if (event.isCancelled()) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
if (defender instanceof Player) {
plugin.getHeroManager().getHero((Player) defender).setLastDamageCause(lastDamage);
}
return;
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
if (player.getNoDamageTicks() > 10 || player.isDead() || player.getHealth() <= 0) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
final Hero hero = plugin.getHeroManager().getHero(player);
//check player inventory to make sure they aren't wearing restricted items
hero.checkInventory();
//Loop through the player's effects and check to see if we need to remove them
if (hero.hasEffectType(EffectType.INVULNERABILITY)) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
for (Effect effect : hero.getEffects()) {
if ((effect.isType(EffectType.ROOT) || effect.isType(EffectType.INVIS)) && !effect.isType(EffectType.UNBREAKABLE)) {
hero.removeEffect(effect);
}
}
// Party damage & PvPable test
if (attacker instanceof Player) {
// If the players aren't within the level range then deny the PvP
int aLevel = plugin.getHeroManager().getHero((Player) attacker).getTieredLevel(false);
if (Math.abs(aLevel - hero.getTieredLevel(false)) > Heroes.properties.pvpLevelRange) {
Messaging.send((Player) attacker, "That player is outside of your level range!");
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
HeroParty party = hero.getParty();
if (party != null && party.isNoPvp()) {
if (party.isPartyMember((Player) attacker)) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
}
}
if (damage == 0) {
event.setDamage(0);
return;
}
switch (event.getCause()) {
case FIRE:
case LAVA:
case BLOCK_EXPLOSION:
case CONTACT:
case ENTITY_EXPLOSION:
case ENTITY_ATTACK:
case PROJECTILE:
hero.setHealth(hero.getHealth() - (damage * calculateArmorReduction(player.getInventory())));
break;
default:
hero.setHealth(hero.getHealth() - damage);
}
event.setDamage(convertHeroesDamage(damage, player));
//If the player would drop to 0 but they still have HP left, don't let them die.
if (hero.getHealth() != 0 && player.getHealth() == 1 && event.getDamage() == 1)
player.setHealth(2);
// Make sure health syncs on the next tick
if (hero.getHealth() == 0)
event.setDamage(200);
else
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
hero.syncHealth();
}
}, 1);
//Update the party display
HeroParty party = hero.getParty();
if (party != null && damage > 0) {
party.update();
}
} else if (defender instanceof LivingEntity) {
// Do Damage calculations based on maximum health and current health
final LivingEntity lEntity = (LivingEntity) defender;
int maxHealth = getMaxHealth(lEntity);
Integer currentHealth = healthMap.get(lEntity.getEntityId());
if (currentHealth == null) {
currentHealth = (int) (lEntity.getHealth() / (double) lEntity.getMaxHealth()) * maxHealth;
}
currentHealth -= damage;
if (currentHealth <= 0) {
healthMap.remove(lEntity.getEntityId());
damage = 100;
} else {
healthMap.put(lEntity.getEntityId(), currentHealth);
damage = convertHeroesDamage(damage, (LivingEntity) defender);
int difference = lEntity.getHealth() - damage;
if (difference <= 0) {
lEntity.setHealth(lEntity.getHealth() + 1 - difference);
}
//Only re-sync if the max health for this
if (maxHealth != lEntity.getMaxHealth()) {
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
int maxMCHP = lEntity.getMaxHealth();
double percent = healthMap.get(lEntity.getEntityId()) / (double) getMaxHealth(lEntity);
int newHP = (int) (maxMCHP * percent);
if (newHP == 0)
newHP = 1;
lEntity.setHealth(newHP);
}
}, 1);
}
}
event.setDamage(damage);
}
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
}
| public void onEntityDamage(EntityDamageEvent event) {
Heroes.debug.startTask("HeroesDamageListener.onEntityDamage");
// Reasons to immediately ignore damage event
if (event.isCancelled() || Heroes.properties.disabledWorlds.contains(event.getEntity().getWorld().getName())) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
Entity defender = event.getEntity();
Entity attacker = null;
HeroDamageCause lastDamage = null;
int damage = event.getDamage();
//Lets figure out who the attacker is
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (subEvent.getDamager() instanceof Projectile) {
attacker = ((Projectile) subEvent.getDamager()).getShooter();
} else {
attacker = subEvent.getDamager();
}
}
if (defender instanceof Player) {
if (((Player) defender).getGameMode() == GameMode.CREATIVE || ((Player) defender).isDead()) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
lastDamage = plugin.getHeroManager().getHero((Player) defender).getLastDamageCause();
}
if (damageManager.isSpellTarget(defender)) {
damage = onSpellDamage(event, damage, defender);
} else {
DamageCause cause = event.getCause();
switch (cause) {
case SUICIDE:
if (defender instanceof Player) {
Player player = (Player) event.getEntity();
plugin.getHeroManager().getHero(player).setHealth(0D);
event.setDamage(1000); //OVERKILLLLL!!
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
break;
case ENTITY_ATTACK:
case ENTITY_EXPLOSION:
case PROJECTILE:
damage = onEntityDamageCore(event, attacker, damage);
break;
case FALL:
damage = onEntityFall(event.getDamage(), defender);
break;
case SUFFOCATION:
damage = onEntitySuffocate(event.getDamage(), defender);
break;
case DROWNING:
damage = onEntityDrown(event.getDamage(), defender, event);
break;
case STARVATION:
damage = onEntityStarve(event.getDamage(), defender);
break;
case FIRE:
case LAVA:
case FIRE_TICK:
damage = onEntityFlame(event.getDamage(), cause, defender, event);
break;
default:
break;
}
//Check if one of the Method calls cancelled the event due to resistances etc.
if (event.isCancelled()) {
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
if (defender instanceof Player) {
plugin.getHeroManager().getHero((Player) defender).setLastDamageCause(lastDamage);
}
return;
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
if (player.getNoDamageTicks() > 10 || player.isDead() || player.getHealth() <= 0) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
final Hero hero = plugin.getHeroManager().getHero(player);
//check player inventory to make sure they aren't wearing restricted items
hero.checkInventory();
//Loop through the player's effects and check to see if we need to remove them
if (hero.hasEffectType(EffectType.INVULNERABILITY)) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
for (Effect effect : hero.getEffects()) {
if ((effect.isType(EffectType.ROOT) || effect.isType(EffectType.INVIS)) && !effect.isType(EffectType.UNBREAKABLE)) {
hero.removeEffect(effect);
}
}
// Party damage & PvPable test
if (attacker instanceof Player) {
// If the players aren't within the level range then deny the PvP
int aLevel = plugin.getHeroManager().getHero((Player) attacker).getTieredLevel(false);
if (Math.abs(aLevel - hero.getTieredLevel(false)) > Heroes.properties.pvpLevelRange) {
Messaging.send((Player) attacker, "That player is outside of your level range!");
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
HeroParty party = hero.getParty();
if (party != null && party.isNoPvp()) {
if (party.isPartyMember((Player) attacker)) {
event.setCancelled(true);
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
return;
}
}
}
if (damage == 0) {
event.setDamage(0);
return;
}
switch (event.getCause()) {
case FIRE:
case LAVA:
case BLOCK_EXPLOSION:
case CONTACT:
case ENTITY_EXPLOSION:
case ENTITY_ATTACK:
case PROJECTILE:
hero.setHealth(hero.getHealth() - (damage * calculateArmorReduction(player.getInventory())));
break;
default:
hero.setHealth(hero.getHealth() - damage);
}
event.setDamage(convertHeroesDamage(damage, player));
//If the player would drop to 0 but they still have HP left, don't let them die.
if (hero.getHealth() != 0 && player.getHealth() == 1 && event.getDamage() == 1)
player.setHealth(2);
// Make sure health syncs on the next tick
if (hero.getHealth() == 0)
event.setDamage(200);
else
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
hero.syncHealth();
}
}, 1);
//Update the party display
HeroParty party = hero.getParty();
if (party != null && damage > 0) {
party.update();
}
} else if (defender instanceof LivingEntity) {
// Do Damage calculations based on maximum health and current health
final LivingEntity lEntity = (LivingEntity) defender;
int maxHealth = getMaxHealth(lEntity);
Integer currentHealth = healthMap.get(lEntity.getEntityId());
if (currentHealth == null) {
currentHealth = (int) (lEntity.getHealth() / (double) lEntity.getMaxHealth()) * maxHealth;
}
currentHealth -= damage;
if (currentHealth <= 0) {
healthMap.remove(lEntity.getEntityId());
damage = 100;
} else {
healthMap.put(lEntity.getEntityId(), currentHealth);
damage = convertHeroesDamage(damage, (LivingEntity) defender);
int difference = lEntity.getHealth() - damage;
if (difference <= 0) {
lEntity.setHealth(lEntity.getHealth() + 1 - difference);
}
//Only re-sync if the max health for this
if (maxHealth != lEntity.getMaxHealth()) {
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (lEntity == null || lEntity.isDead())
return;
int maxMCHP = lEntity.getMaxHealth();
double percent = healthMap.get(lEntity.getEntityId()) / (double) getMaxHealth(lEntity);
int newHP = (int) (maxMCHP * percent);
if (newHP == 0)
newHP = 1;
lEntity.setHealth(newHP);
}
}, 1);
}
}
event.setDamage(damage);
}
Heroes.debug.stopTask("HeroesDamageListener.onEntityDamage");
}
|
diff --git a/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/gui/ShipStack.java b/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/gui/ShipStack.java
index 0780f51..d557564 100644
--- a/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/gui/ShipStack.java
+++ b/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/gui/ShipStack.java
@@ -1,121 +1,122 @@
package ch.bfh.bti7301.w2013.battleship.gui;
import static ch.bfh.bti7301.w2013.battleship.gui.BoardView.SIZE;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import ch.bfh.bti7301.w2013.battleship.game.Board.Coordinates;
import ch.bfh.bti7301.w2013.battleship.game.Board.Direction;
import ch.bfh.bti7301.w2013.battleship.game.Game;
import ch.bfh.bti7301.w2013.battleship.game.GameRule;
import ch.bfh.bti7301.w2013.battleship.game.Ship;
public class ShipStack extends HBox {
private final GameRule rule;
private double initX;
private double initY;
private Point2D dragAnchor;
public ShipStack(final Game game, final GameRule rule, final BoardView pbv,
final Button ready) {
super(-16);
this.rule = rule;
// FIXME: this is just for layout debugging
setStyle("-fx-background-color: #ffc;");
setMaxHeight(SIZE);
for (Ship s : getAvailableShips()) {
final ShipView sv = new ShipView(s);
getChildren().add(sv);
sv.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
initX = sv.getTranslateX();
initY = sv.getTranslateY();
dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
}
});
sv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double dragX = me.getSceneX() - dragAnchor.getX();
double dragY = me.getSceneY() - dragAnchor.getY();
// calculate new position of the circle
double newXPosition = initX + dragX;
double newYPosition = initY + dragY;
sv.setTranslateX(newXPosition);
sv.setTranslateY(newYPosition);
}
});
sv.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double shipStartX = me.getSceneX() - me.getX()
- pbv.getLayoutX();
double shipStartY = me.getSceneY() - me.getY()
- pbv.getLayoutY();
if (pbv.contains(shipStartX, shipStartY)) {
// if on board, snap & add to it
Coordinates c = pbv.getCoordinates(shipStartX,
shipStartY);
Ship ship = buildShip(sv.getShipType(), c,
Direction.SOUTH);
try {
- game.getLocalPlayer().getBoard().placeShip(ship);
+ game.getLocalPlayer().getBoard().getBoardSetup()
+ .placeShip(ship);
} catch (RuntimeException e) {
// snap back
// Maybe coloring the ship and leaving it there
// would be better?
sv.setTranslateX(initX);
sv.setTranslateY(initY);
return;
}
getChildren().remove(sv);
if (getChildren().isEmpty()) {
ready.setVisible(true);
setVisible(false);
}
pbv.addShip(ship);
} else {
// snap back
sv.setTranslateX(initX);
sv.setTranslateY(initY);
}
}
});
}
}
private List<Ship> getAvailableShips() {
List<Ship> availableShips = new LinkedList<>();
Coordinates dc = new Coordinates(0, 0);
Direction dd = Direction.SOUTH;
for (Entry<Class<? extends Ship>, Integer> e : rule.getShipList()
.entrySet()) {
Ship ship = buildShip(e.getKey(), dc, dd);
for (int i = 0; i < e.getValue(); i++)
availableShips.add(ship);
}
return availableShips;
}
private Ship buildShip(Class<? extends Ship> type, Coordinates c,
Direction d) {
try {
return type.getConstructor(Coordinates.class, Direction.class)
.newInstance(c, d);
} catch (Exception e) {
throw new RuntimeException(
"Error while creating ships through reflection", e);
}
}
}
| true | true | public ShipStack(final Game game, final GameRule rule, final BoardView pbv,
final Button ready) {
super(-16);
this.rule = rule;
// FIXME: this is just for layout debugging
setStyle("-fx-background-color: #ffc;");
setMaxHeight(SIZE);
for (Ship s : getAvailableShips()) {
final ShipView sv = new ShipView(s);
getChildren().add(sv);
sv.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
initX = sv.getTranslateX();
initY = sv.getTranslateY();
dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
}
});
sv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double dragX = me.getSceneX() - dragAnchor.getX();
double dragY = me.getSceneY() - dragAnchor.getY();
// calculate new position of the circle
double newXPosition = initX + dragX;
double newYPosition = initY + dragY;
sv.setTranslateX(newXPosition);
sv.setTranslateY(newYPosition);
}
});
sv.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double shipStartX = me.getSceneX() - me.getX()
- pbv.getLayoutX();
double shipStartY = me.getSceneY() - me.getY()
- pbv.getLayoutY();
if (pbv.contains(shipStartX, shipStartY)) {
// if on board, snap & add to it
Coordinates c = pbv.getCoordinates(shipStartX,
shipStartY);
Ship ship = buildShip(sv.getShipType(), c,
Direction.SOUTH);
try {
game.getLocalPlayer().getBoard().placeShip(ship);
} catch (RuntimeException e) {
// snap back
// Maybe coloring the ship and leaving it there
// would be better?
sv.setTranslateX(initX);
sv.setTranslateY(initY);
return;
}
getChildren().remove(sv);
if (getChildren().isEmpty()) {
ready.setVisible(true);
setVisible(false);
}
pbv.addShip(ship);
} else {
// snap back
sv.setTranslateX(initX);
sv.setTranslateY(initY);
}
}
});
}
}
| public ShipStack(final Game game, final GameRule rule, final BoardView pbv,
final Button ready) {
super(-16);
this.rule = rule;
// FIXME: this is just for layout debugging
setStyle("-fx-background-color: #ffc;");
setMaxHeight(SIZE);
for (Ship s : getAvailableShips()) {
final ShipView sv = new ShipView(s);
getChildren().add(sv);
sv.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
initX = sv.getTranslateX();
initY = sv.getTranslateY();
dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
}
});
sv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double dragX = me.getSceneX() - dragAnchor.getX();
double dragY = me.getSceneY() - dragAnchor.getY();
// calculate new position of the circle
double newXPosition = initX + dragX;
double newYPosition = initY + dragY;
sv.setTranslateX(newXPosition);
sv.setTranslateY(newYPosition);
}
});
sv.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double shipStartX = me.getSceneX() - me.getX()
- pbv.getLayoutX();
double shipStartY = me.getSceneY() - me.getY()
- pbv.getLayoutY();
if (pbv.contains(shipStartX, shipStartY)) {
// if on board, snap & add to it
Coordinates c = pbv.getCoordinates(shipStartX,
shipStartY);
Ship ship = buildShip(sv.getShipType(), c,
Direction.SOUTH);
try {
game.getLocalPlayer().getBoard().getBoardSetup()
.placeShip(ship);
} catch (RuntimeException e) {
// snap back
// Maybe coloring the ship and leaving it there
// would be better?
sv.setTranslateX(initX);
sv.setTranslateY(initY);
return;
}
getChildren().remove(sv);
if (getChildren().isEmpty()) {
ready.setVisible(true);
setVisible(false);
}
pbv.addShip(ship);
} else {
// snap back
sv.setTranslateX(initX);
sv.setTranslateY(initY);
}
}
});
}
}
|
diff --git a/contrib/Karma.java b/contrib/Karma.java
index b57438c..dc0c9da 100644
--- a/contrib/Karma.java
+++ b/contrib/Karma.java
@@ -1,1336 +1,1336 @@
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jibble.pircbot.Colors;
import uk.co.uwcs.choob.modules.Modules;
import uk.co.uwcs.choob.support.ChoobNoSuchCallException;
import uk.co.uwcs.choob.support.ChoobPermission;
import uk.co.uwcs.choob.support.IRCInterface;
import uk.co.uwcs.choob.support.events.Message;
import uk.co.uwcs.choob.support.events.PrivateEvent;
class KarmaObject
{
public int id;
public String string;
public int up;
public int down;
public int value;
String instName;
public boolean equals(final KarmaObject obj)
{
return this.string.equalsIgnoreCase(obj.string);
}
}
class KarmaReasonObject
{
public int id;
public String string;
public int direction;
public String reason;
}
class KarmaChangeHolder
{
KarmaObject karma;
List<KarmaReasonObject> reasons;
int change;
boolean flood;
String instanceName;
KarmaChangeHolder(final String instanceName)
{
this.reasons = new ArrayList<KarmaReasonObject>();
this.instanceName = instanceName;
}
}
class KarmaReasonEnumerator
{
public KarmaReasonEnumerator()
{
// Unhiding.
}
public KarmaReasonEnumerator(final String enumSource, final int[] idList)
{
this.enumSource = enumSource;
this.idList = "";
for (int i = 0; i < idList.length; i++) {
if (i > 0)
this.idList += ",";
this.idList += idList[i];
}
this.index = (int)Math.floor(Math.random() * idList.length);
this.lastUsed = System.currentTimeMillis();
}
public int getNext()
{
if (intIdList == null)
setupIDListInt();
index++;
if (index >= intIdList.length) {
index = 0;
}
lastUsed = System.currentTimeMillis();
return intIdList[index];
}
private void setupIDListInt()
{
final String[] list = this.idList.split("\\s*,\\s*");
this.intIdList = new int[list.length];
for (int i = 0; i < list.length; i++) {
this.intIdList[i] = Integer.parseInt(list[i]);
}
}
public int getSize()
{
if (intIdList == null)
setupIDListInt();
return intIdList.length;
}
public int id;
public String enumSource;
public String idList;
private int[] intIdList = null;
public int index;
public long lastUsed;
}
class KarmaSortByAbsValue implements Comparator<KarmaObject>
{
public int compare(final KarmaObject o1, final KarmaObject o2) {
if (Math.abs(o1.value) > Math.abs(o2.value)) {
return -1;
}
if (Math.abs(o1.value) < Math.abs(o2.value)) {
return 1;
}
if (o1.up > o2.up) {
return -1;
}
if (o1.up < o2.up) {
return 1;
}
if (o1.down > o2.down) {
return -1;
}
if (o1.down < o2.down) {
return 1;
}
return 0;
}
@Override
public boolean equals(final Object obj) {
return false;
}
}
class KarmaSortByValue implements Comparator<KarmaObject>
{
public int compare(final KarmaObject o1, final KarmaObject o2) {
if (o1.value > o2.value) {
return -1;
}
if (o1.value < o2.value) {
return 1;
}
return 0;
}
@Override
public boolean equals(final Object obj) {
return false;
}
}
public class Karma
{
// Non-null == ignore.
private final static Set<String> exceptions = new HashSet<String>();
private final static Set<String> reasonExceptions = new HashSet<String>();
static
{
exceptions.add("c");
exceptions.add("dc");
exceptions.add("visualj");
exceptions.add("vc");
exceptions.add("tolua");
reasonExceptions.add("for that");
reasonExceptions.add("because of that");
}
static final int FLOOD_RATE = 15 * 60 * 1000;
static final String FLOOD_RATE_STR = "15 minutes";
private static long ENUM_TIMEOUT = 5 * 60 * 1000; // 5 minutes
public String[] info()
{
return new String[] {
"Plugin to keep track of the \"karma\" of stuff.",
"The Choob Team",
"[email protected]",
"$Rev$$Date$"
};
}
private final Modules mods;
private final IRCInterface irc;
public Karma (final Modules mods, final IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
mods.interval.callBack("clean-enums", 60000, 1);
}
// Interval
public void interval(final Object param)
{
if ("clean-enums".equals(param)) {
// Clean up dead enumerators.
final long lastUsedCutoff = System.currentTimeMillis() - ENUM_TIMEOUT;
final List<KarmaReasonEnumerator> deadEnums = mods.odb.retrieve(KarmaReasonEnumerator.class, "WHERE lastUsed < " + lastUsedCutoff);
for (int i = 0; i < deadEnums.size(); i++) {
mods.odb.delete(deadEnums.get(i));
}
mods.interval.callBack(param, 60000, 1);
}
}
private KarmaReasonObject pickRandomKarmaReason(final List<KarmaReasonObject> reasons, String enumSource)
{
if (enumSource == null) {
final int index = (int)Math.floor(Math.random() * reasons.size());
return reasons.get(index);
}
int reasonId = -1;
enumSource = enumSource.toLowerCase();
final List<KarmaReasonEnumerator> enums = mods.odb.retrieve(KarmaReasonEnumerator.class, "WHERE enumSource = '" + mods.odb.escapeString(enumSource) + "'");
KarmaReasonEnumerator krEnum = null;
if (enums.size() >= 1) {
krEnum = enums.get(0);
if (krEnum.getSize() != reasons.size()) {
// Count has changed: invalidated!
mods.odb.delete(krEnum);
krEnum = null;
} else {
// Alright, step to the next one.
reasonId = krEnum.getNext();
mods.odb.update(krEnum);
}
}
if (krEnum == null) {
// No enumerator, create one.
final int[] idList = new int[reasons.size()];
for (int i = 0; i < reasons.size(); i++)
idList[i] = reasons.get(i).id;
krEnum = new KarmaReasonEnumerator(enumSource, idList);
reasonId = krEnum.getNext();
mods.odb.save(krEnum);
}
KarmaReasonObject rvReason = null;
for (int i = 0; i < reasons.size(); i++) {
final KarmaReasonObject reason = reasons.get(i);
if (reason.id == reasonId) {
rvReason = reason;
break;
}
}
return rvReason;
}
private String[] getReasonResult(final List<KarmaReasonObject> reasons, final String enumSource)
{
if (reasons.size() == 0) {
return null;
}
final KarmaReasonObject reason = pickRandomKarmaReason(reasons, enumSource);
return new String[] {
reason.string,
reason.reason,
reason.direction == 1 ? "gained" : (reason.direction == -1 ? "lost" : "unchanged")
};
}
public String[] apiReason()
{
System.err.println("WARNING: Karma.apiReason called with no enumSource. No enumeration supported with this call.");
return apiReasonEnum(null);
}
public String[] apiReason(final int direction)
{
System.err.println("WARNING: Karma.apiReason called with no enumSource. No enumeration supported with this call.");
return apiReasonEnum(null, direction);
}
public String[] apiReason(final String name)
{
System.err.println("WARNING: Karma.apiReason called with no enumSource. No enumeration supported with this call.");
return apiReasonEnum(null, name);
}
public String[] apiReason(final String name, final int direction)
{
System.err.println("WARNING: Karma.apiReason called with no enumSource. No enumeration supported with this call.");
return apiReasonEnum(null, name, direction);
}
public String[] apiReasonEnum(final String enumSource)
{
final List<KarmaReasonObject> results = mods.odb.retrieve(KarmaReasonObject.class, "");
return getReasonResult(results, enumSource);
}
public String[] apiReasonEnum(final String enumSource, final int direction)
{
final List<KarmaReasonObject> results = mods.odb.retrieve(KarmaReasonObject.class, "WHERE direction = " + direction);
return getReasonResult(results, enumSource + ":" + (direction == 1 ? "up" : (direction == -1 ? "down" : "unchanged")));
}
public String[] apiReasonEnum(final String enumSource, final String name)
{
final List<KarmaReasonObject> results = mods.odb.retrieve(KarmaReasonObject.class, "WHERE string = \"" + mods.odb.escapeString(name) + "\"");
return getReasonResult(results, enumSource + "::" + name);
}
public String[] apiReasonEnum(final String enumSource, final String name, final int direction)
{
final List<KarmaReasonObject> results = mods.odb.retrieve(KarmaReasonObject.class, "WHERE string = \"" + mods.odb.escapeString(name) + "\" AND direction = " + direction);
return getReasonResult(results, enumSource + ":" + (direction == 1 ? "up" : (direction == -1 ? "down" : "unchanged")) + ":" + name);
}
public String[] helpCommandReason = {
"Find out why something rocks or sucks.",
"[<Object>]",
"<Object> is the optional thing to ask about."
};
public void commandReason( final Message mes )
{
String name = mods.util.getParamString(mes);
String[] reason;
if (name.equals(""))
{
reason = apiReasonEnum(mes.getContext());
if (reason != null)
name = reason[0];
}
else
{
Matcher ma = karmaItemPattern.matcher(name);
if (ma.find())
{
reason = apiReasonEnum(mes.getContext(), getName(ma));
if (reason != null)
name = reason[0];
}
else
{
if (name.startsWith("\""))
{
irc.sendContextReply(mes, "Unable to match your query to a valid karma string.");
return;
}
// Value wasn't quoted, so try it again, but quoted.
ma = karmaItemPattern.matcher("\"" + name + "\"");
if (!ma.find())
{
irc.sendContextReply(mes, "Unable to match your query to a valid karma string.");
return;
}
reason = apiReasonEnum(mes.getContext(), getName(ma));
if (reason != null)
name = reason[0];
}
}
if (reason != null)
irc.sendContextReply(mes, formatKarmaNameForIRC(name) + " has " + reason[2] + " karma " + reason[1]);
else
irc.sendContextReply(mes, "Nobody has ever told me why " + formatKarmaNameForIRC(name) + " has changed karma. :(");
}
private void nullReason(final Message mes, final int direction)
{
String[] reason;
String name;
reason = apiReasonEnum(mes.getContext(), direction);
if (reason != null)
name = reason[0];
else
{
irc.sendContextReply(mes, "No karma reasons.");
return;
}
irc.sendContextReply(mes, formatKarmaNameForIRC(name) + " has " + (direction == 1 ? "gained" : (direction == -1 ? "lost" : "unchanged")) + " karma " + reason[1]);
}
public String[] helpCommandReasonUp = {
"Find out why something rocks.",
"[<Object>]",
"<Object> is the optional thing to ask about."
};
public void commandReasonUp( final Message mes )
{
String name = mods.util.getParamString(mes);
String[] reason;
if (name.equals(""))
{
reason = apiReasonEnum(mes.getContext(), 1);
if (reason != null)
name = reason[0];
}
else
{
final Matcher ma=karmaItemPattern.matcher(name);
if (ma.find())
{
reason = apiReasonEnum(mes.getContext(), getName(ma), 1);
if (reason !=null)
name = reason[0];
}
else
{
nullReason(mes, 1);
return;
}
}
if (reason != null)
irc.sendContextReply(mes, formatKarmaNameForIRC(name) + " has gained karma " + reason[1]);
else
irc.sendContextReply(mes, "Nobody has ever told me why " + formatKarmaNameForIRC(name) + " has gained karma. :(");
}
public String[] helpCommandReasonDown = {
"Find out why something sucks.",
"[<Object>]",
"<Object> is the optional thing to ask about."
};
public void commandReasonDown( final Message mes )
{
String name = mods.util.getParamString(mes);
String[] reason;
if (name.equals(""))
{
reason = apiReasonEnum(mes.getContext(), -1);
if (reason != null)
name = reason[0];
}
else
{
final Matcher ma=karmaItemPattern.matcher(name);
if (ma.find())
{
reason = apiReasonEnum(mes.getContext(), getName(ma), -1);
if (reason != null)
name = reason[0];
}
else
{
nullReason(mes, -1);
return;
}
}
if (reason != null)
irc.sendContextReply(mes, formatKarmaNameForIRC(name) + " has lost karma " + reason[1]);
else
irc.sendContextReply(mes, "Nobody has ever told me why " + formatKarmaNameForIRC(name) + " has lost karma. :(");
}
public String[] helpTopics = { "Using" };
public String[] helpUsing = {
"To change the karma of something, simply send the message"
+ " 'something--' or 'something++'. You can also specify a reason, by"
+ " sending a line starting with a karma change then giving a reason,"
+ " like: 'ntl-- because they suck' or 'ntl-- for sucking teh c0k'.",
"For strings shorter than 3 chars, or spaced strings or whatever,"
+ " you can use quotes, like this: '\"a\"--' or '\"big bananas\"++'."
+ " You can't yet Set these types of string."
};
// Let's just do a simple filter to pick up karma. This is lightweight and
// picks up anything that /could/ be karma (though not necessarily only
// karma)
// ++, --, +- or -+:
final private static String plusplus_or_minusminus = "([\\+\\-]{2})";
// Quoted string:
final private static String c_style_quoted_string = "(?:"
+ "\""
+ "("
+ "(?:\\\\.|[^\"\\\\])+" // C-style quoting
+ ")"
+ "\""
+ ")";
// Plain string of >=2 chars.
final private static String plain_karma = "("
+ "[a-zA-Z0-9_]{2,}"
+ ")";
// Either a quoted or a valid plain karmaitem.
final private static String karma_item = "(?x:" + c_style_quoted_string + "|" + plain_karma + ")";
final private static Pattern karmaItemPattern = Pattern.compile(karma_item);
// If you change this, change reasonPattern too.
final private static Pattern karmaPattern = Pattern.compile(
"(?x:"
+ "(?: ^ | (?<=[\\s\\(]) )" // Anchor at start of string, whitespace or open bracket.
+ karma_item
+ plusplus_or_minusminus
+ "[\\)\\.,]?" // Allowed to terminate with full stop/close bracket etc.
+ "(?: (?=\\s) | $ )" // Need either whitespace or end-of-string now.
+ ")"
);
// If you change the first part of this, change karmaPattern too.
final private static Pattern karmaPatternWithReason = Pattern.compile(
"(?x:"
+ "^" // Anchor at start of string.
+ karma_item
+ plusplus_or_minusminus
+ "\\s+"
+ "("
// A "natural English" reason
+ "(?i: because | for)\\s" // Must start sensibly
+ ".+" // Rest of reason
+ "|"
// A bracketted reason
+ "\\("
+ ".+?" // Contains any text.
+ "\\)"
+ ")"
+ ".*?" // Keep this trailing part as small as possible.
+ "$" // Anchor at the end of string.
+ ")"
);
public final String filterKarmaRegex = plusplus_or_minusminus + "\\B";
public synchronized void filterKarma(final Message mes)
{
// Ignore lines that look like commands.
if (mes.getFlags().containsKey("command"))
return;
final String message = mes.getMessage();
final String nick = mods.nick.getBestPrimaryNick(mes.getNick());
//System.err.println("LINE : <" + message + ">");
final List<Integer> matchStarts = new ArrayList<Integer>();
final Matcher karmaScan = karmaPattern.matcher(message);
while (karmaScan.find())
matchStarts.add(karmaScan.start());
matchStarts.add(message.length());
final List<List<String>> matches = new ArrayList<List<String>>();
for (int matchIndex = 1; matchIndex < matchStarts.size(); matchIndex++)
{
//System.err.println("");
- final String submessage = message.substring(matchStarts.get(matchIndex - 1), matchStarts.get(matchIndex)).replaceAll("[^\\+\\-\\)\\w]+$", "");
+ final String submessage = message.substring(matchStarts.get(matchIndex - 1), matchStarts.get(matchIndex));
//System.err.println(" SEGMENT : <" + submessage + ">");
Matcher karmaMatch = karmaPatternWithReason.matcher(submessage);
if (!karmaMatch.find())
{
karmaMatch = karmaPattern.matcher(submessage);
karmaMatch.find();
}
//System.err.println(" MATCH : <" + karmaMatch.group() + ">");
//for (int i = 1; i <= karmaMatch.groupCount(); i++)
// System.err.println(" GROUP " + i + ": <" + karmaMatch.group(i) + ">");
List<String> groups = new ArrayList<String>();
for (int i = 0; i <= karmaMatch.groupCount(); i++)
groups.add(karmaMatch.group(i));
matches.add(groups);
}
// List of all karma changes that will be applied and hash of them
// so we can handle duplicates sanely.
final List<KarmaChangeHolder> karmas = new ArrayList<KarmaChangeHolder>();
final Map<String,KarmaChangeHolder> karmaMap = new HashMap<String,KarmaChangeHolder>();
for (final List<String> match : matches)
{
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
// Group 4: reason (optional)
String name = "";
if (match.get(1) != null)
{
name = match.get(1).replaceAll("\\\\(.)", "$1");
}
else
{
name = match.get(2);
if (exceptions.contains(name.toLowerCase()))
continue;
}
KarmaChangeHolder karma;
if (karmaMap.containsKey(name.toLowerCase()))
karma = karmaMap.get(name.toLowerCase());
else
karma = new KarmaChangeHolder(name);
// If it's "me", replace with user's nickname and force to down.
if (karma.instanceName.equals/*NOT IgnoreCase*/("me") || karma.instanceName.equals/*NOT IgnoreCase*/("Me") || karma.instanceName.equalsIgnoreCase(nick))
{
karma.instanceName = nick;
karma.change--;
}
// Up or down?
else if (match.get(3).equals("++"))
{
karma.change++;
}
else if (match.get(3).equals("--"))
{
karma.change--;
}
// Get the reason, if it's not excluded!
if (match.size() > 4 && !reasonExceptions.contains(match.get(4)))
{
KarmaReasonObject reason = new KarmaReasonObject();
reason.reason = match.get(4);
reason.direction = match.get(3).equals("++") ? 1 : (match.get(3).equals("--") ? -1 : 0);
karma.reasons.add(reason);
}
if (!karmaMap.containsKey(name.toLowerCase()))
{
karmas.add(karma);
karmaMap.put(karma.instanceName.toLowerCase(), karma);
}
}
// No karma changes? Boring!
if (karmas.size() == 0)
return;
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
// Right. We have a list of karma to apply, we've checked it's a public
// place and we have no duplicates. Time for the flood checking.
for (final KarmaChangeHolder karma : karmas)
{
try
{
// 15 minute block for each karma item, irespective of who or direction.
final int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + normalise(karma.instanceName), FLOOD_RATE, 2);
if (ret != 0)
{
karma.flood = true;
continue;
}
}
catch (final ChoobNoSuchCallException e)
{ } // ignore
catch (final Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
}
// Apply all the karma changes!
for (final KarmaChangeHolder karma : karmas)
{
// Flooded? Skip it!
if (karma.flood)
continue;
// Fetch the existing karma data for this item.
karma.karma = retrieveKarmaObject(karma.instanceName);
// Do up or down change first.
if (karma.change > 0)
{
karma.karma.up++;
karma.karma.value++;
}
else if (karma.change < 0)
{
karma.karma.down++;
karma.karma.value--;
}
// Save the new karma data.
mods.odb.update(karma.karma);
// Now add the reason(s). Note that there's nothing to retrieve
// here so we can save the local object directly.
for (KarmaReasonObject reason : karma.reasons)
{
reason.string = karma.karma.string;
mods.odb.save(reason);
}
}
// Generate a pretty reply, all actual processing is done now:
if (karmas.size() == 1)
{
final KarmaChangeHolder karma = karmas.get(0);
if (karma.flood)
irc.sendContextReply(mes, "Denied change to " + formatKarmaNameForIRC(karma.instanceName) + "! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
else if (karma.karma.string.equals(nick))
// This doesn't mention if there was a reason.
irc.sendContextReply(mes, "Fool, that's less karma to you! That leaves you with " + karma.karma.value + ".");
else
irc.sendContextReply(mes, (karma.change > 0 ? "Given more karma" : karma.change < 0 ? "Given less karma" : "No change") + " to " + formatKarmaNameForIRC(karma.instanceName) + (karma.reasons.size() == 1 ? " and understood your reason" : (karma.reasons.size() > 1 ? " and understood your reasons" : "")) + ". " + (karma.change == 0 ? "Karma remains at " : "New karma is ") + karma.karma.value + ".");
}
else
{
final StringBuffer output = new StringBuffer("Karma adjustments: ");
for (int i = 0; i < karmas.size(); i++)
{
final KarmaChangeHolder karma = karmas.get(i);
output.append(formatKarmaNameForIRC(karma.instanceName));
if (karma.flood)
{
output.append(" ignored (flood)");
}
else
{
if (karma.change > 0)
output.append(" up");
else if (karma.change < 0)
output.append(" down");
else
output.append(" unchanged");
if (karma.reasons.size() > 1)
output.append(" with reasons");
else if (karma.reasons.size() == 1)
output.append(" with reason");
if (karma.change == 0)
output.append(" (remains " + karma.karma.value + ")");
else
output.append(" (now " + karma.karma.value + ")");
}
if (i < karmas.size() - 1)
output.append(", ");
else if (i == karmas.size() - 2)
output.append(" and ");
}
output.append(".");
irc.sendContextReply(mes, output.toString());
}
}
private String postfix(final int n)
{
if (n % 100 >= 11 && n % 100 <= 13)
return "th";
switch (n % 10)
{
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
}
return "th";
}
private void commandScores(final Message mes, final boolean asc)
{
final List<KarmaObject> karmaObjs = retrieveKarmaObjects("SORT " + (asc ? "ASC" : "DESC") + " INTEGER value LIMIT (5)");
final StringBuffer output = new StringBuffer((asc ? "Low" : "High" ) + " Scores: ");
for (int i=0; i<karmaObjs.size(); i++)
{
output.append(String.valueOf(i+1) + postfix(i+1));
output.append(": ");
output.append(formatKarmaNameForIRC(karmaObjs.get(i).string));
output.append(" (with " + karmaObjs.get(i).value + ")");
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
public String[] helpCommandHighScores = {
"Find out what has the highest karma"
};
public void commandHighScores(final Message mes)
{
commandScores(mes, false);
}
public String[] helpCommandLowScores = {
"Find out what has the lowest karma"
};
public void commandLowScores(final Message mes)
{
commandScores(mes, true);
}
private void saveKarmaObjects(final List<KarmaObject> karmaObjs)
{
for (final KarmaObject karmaObj: karmaObjs)
mods.odb.update(karmaObj);
}
private KarmaObject retrieveKarmaObject(String name)
{
name = normalise(name);
final List<KarmaObject> results = mods.odb.retrieve(KarmaObject.class, "WHERE string = \"" + mods.odb.escapeString(name) + "\"");
if (results.size() == 0)
{
final KarmaObject newObj = new KarmaObject();
newObj.string = name;
mods.odb.save(newObj);
return newObj;
}
return results.get(0);
}
private List<KarmaObject> retrieveKarmaObjects(final String clause)
{
return mods.odb.retrieve(KarmaObject.class, clause);
}
public String[] helpCommandFight = {
"Pit the karma of two objects against each other to find the leetest (or least lame).",
"<Object 1> <Object 2>",
};
public void commandFight (final Message mes)
{
final List<String> params = new ArrayList<String>();
final Matcher ma=karmaItemPattern.matcher(mods.util.getParamString(mes));
while (ma.find())
params.add(getName(ma));
final List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
//Nab the params
if (params.size() == 2)
{
for (int i=0; i<2; i++)
{
final String name = params.get(i);
if (name!=null)
{
final KarmaObject karmaObj = retrieveKarmaObject(name);
karmaObj.instName = name;
karmaObjs.add(karmaObj);
}
}
}
if (karmaObjs.size() == 2)
{
//Check that they aint the same thing!
if (karmaObjs.get(0).equals(karmaObjs.get(1)))
{
irc.sendContextReply(mes, "Fighters must be unique!");
}
else
{
final int result = new KarmaSortByValue().compare(karmaObjs.get(0),karmaObjs.get(1));
if (result == -1)
{
//Winner is Object 0
irc.sendContextReply(mes, formatKarmaNameForIRC(karmaObjs.get(0).instName) + " was victorious over " + formatKarmaNameForIRC(karmaObjs.get(1).instName) + "! (" + karmaObjs.get(0).value + " vs " + karmaObjs.get(1).value + ")");
}
else if (result == 1)
{
//Winner is Object 1
irc.sendContextReply(mes, formatKarmaNameForIRC(karmaObjs.get(1).instName) + " was victorious over " + formatKarmaNameForIRC(karmaObjs.get(0).instName) + "! (" + karmaObjs.get(1).value + " vs " + karmaObjs.get(0).value + ")");
}
else
{
//Should only be a draw
irc.sendContextReply(mes, "The battle between " + formatKarmaNameForIRC(karmaObjs.get(0).instName) + " and " + formatKarmaNameForIRC(karmaObjs.get(1).instName) + " was a draw! (" + karmaObjs.get(0).value + " vs " + karmaObjs.get(1).value + ")");
}
}
}
else
{
//Too many, or perhaps too few, things
irc.sendContextReply(mes, "You must supply exactly two objects to fight!");
}
}
public String[] helpCommandReal = {
"Find out the \"real\" karma of some object or another.",
"<Object> [<Object> ...]",
"<Object> is the name of something to get the karma of."
};
public void commandReal (final Message mes)
{
final List<String> params = new ArrayList<String>();
final Matcher ma=karmaItemPattern.matcher(mods.util.getParamString(mes));
while (ma.find())
params.add(getName(ma));
final List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
if (params.size() > 0)
for (int i=0;i<params.size();i++)
{
final String name = params.get(i);
if (name != null) {
final KarmaObject karmaObj = retrieveKarmaObject(name);
karmaObj.instName = name;
karmaObjs.add(karmaObj);
}
}
if (karmaObjs.size() == 1)
{
final int realkarma = karmaObjs.get(0).up - karmaObjs.get(0).down;
irc.sendContextReply(mes, formatKarmaNameForIRC(karmaObjs.get(0).instName) + " has a \"real\" karma of " + realkarma + " (" + karmaObjs.get(0).up + " up, " + karmaObjs.get(0).down + " down).");
return;
}
final StringBuffer output = new StringBuffer("\"Real\" Karmas: ");
if (karmaObjs.size()!=0)
{
for (int i=0;i<karmaObjs.size();i++)
{
final int realkarma = karmaObjs.get(i).up - karmaObjs.get(i).down;
output.append(formatKarmaNameForIRC(karmaObjs.get(i).instName) + ": " + realkarma);
if (i != karmaObjs.size() -1)
{
if (i == karmaObjs.size() -2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply(mes, output.toString());
} else {
irc.sendContextReply(mes, "Check the \"real\" karma of what?");
}
}
public String[] helpCommandGet = {
"Find out the karma of some object or other.",
"<Object> [<Object> ...]",
"<Object> is the name of something to get the karma of"
};
public String commandGet (final String mes)
{
final List<String> params = new ArrayList<String>();
final Matcher ma = karmaItemPattern.matcher(mes);
while (ma.find())
params.add(getName(ma));
final List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
if (params.size() > 0)
for (int i=0; i<params.size(); i++)
{
final String name = params.get(i);
if (name!=null)
{
final KarmaObject karmaObj = retrieveKarmaObject(name);
karmaObj.instName = name;
karmaObjs.add(karmaObj);
}
}
if (karmaObjs.size() == 1)
return formatKarmaNameForIRC(karmaObjs.get(0).instName) + " has a karma of " + karmaObjs.get(0).value + " (" + karmaObjs.get(0).up + " up, " + karmaObjs.get(0).down + " down).";
final StringBuffer output = new StringBuffer("Karmas: ");
if (karmaObjs.size()!=0)
{
for (int i=0; i<karmaObjs.size(); i++)
{
output.append(formatKarmaNameForIRC(karmaObjs.get(i).instName));
output.append(": " + karmaObjs.get(i).value);
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
return output.toString();
}
return "Check the karma of what?";
}
public String[] helpCommandSet = {
"Set out the karma of some object or other.",
"<Object>=<Value> [<Object>=<Value> ...]",
"<Object> is the name of something to set the karma of",
"<Value> is the value to set the karma to"
};
public synchronized void commandSet( final Message mes )
{
mods.security.checkNickPerm(new ChoobPermission("plugins.karma.set"), mes);
final List<String> params = mods.util.getParams( mes );
final List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
for (int i=1; i<params.size(); i++)
{
final String param = params.get(i);
final String[] items = param.split("=");
if (items.length != 2)
{
irc.sendContextReply(mes, "Bad syntax: Use <Object>=<Value> [<Object>=<Value> ...]");
return;
}
final String name = items[0].trim();
int val;
try
{
val = Integer.parseInt(items[1]);
}
catch (final NumberFormatException e)
{
irc.sendContextReply(mes, "Bad syntax: Karma value " + items[1] + " is not a valid integer.");
return;
}
final KarmaObject karmaObj = retrieveKarmaObject(name);
karmaObj.instName = name;
karmaObj.value = val;
karmaObjs.add(karmaObj);
}
if (karmaObjs.size()==0)
{
irc.sendContextReply(mes, "You need to specify some bobdamn karma to set!");
return;
}
saveKarmaObjects(karmaObjs);
final StringBuffer output = new StringBuffer("Karma adjustment");
output.append(karmaObjs.size() == 1 ? "" : "s");
output.append(": ");
for (int i=0; i<karmaObjs.size(); i++)
{
output.append(formatKarmaNameForIRC(karmaObjs.get(i).instName));
output.append(": now ");
output.append(karmaObjs.get(i).value);
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
final private static String slashed_regex_string = "(?:"
+ "/"
+ "("
+ "(?:\\\\.|[^/\\\\])+" // C-style quoting
+ ")"
+ "/"
+ ")";
class KarmaSearchItem
{
KarmaSearchItem(final String name, final boolean regex)
{
this.name = name;
this.regex = regex;
}
String name;
boolean regex;
}
public String[] helpCommandSearch = {
"Finds existing karma items.",
"<Query> [<Query> ...]",
"<Query> is some text or a regular expression (in /.../) to find"
};
public void commandSearch(final Message mes)
{
final List<KarmaSearchItem> params = new ArrayList<KarmaSearchItem>();
final Matcher ma = Pattern.compile(karma_item + "|" + slashed_regex_string).matcher(mods.util.getParamString(mes));
while (ma.find())
{
final String name = getName(ma);
params.add(
name == null ?
new KarmaSearchItem(normalise(ma.group(3)), true) :
new KarmaSearchItem(normalise(name), false)
);
}
if (params.size() == 0)
irc.sendContextReply(mes, "Please specify at least one valid karma item, or a regex.");
// Only 3 items please!
while (params.size() > 3)
params.remove(params.size() - 1);
for (final KarmaSearchItem item : params)
{
String odbQuery;
final String andNotZero = " AND NOT (up = 0 AND down = 0 AND value = 0)";
if (item.regex) {
// Regexp
odbQuery = "WHERE string RLIKE \"" + mods.odb.escapeForRLike(item.name) + "\"" + andNotZero;
} else {
// Substring
odbQuery = "WHERE string LIKE \"%" + mods.odb.escapeForLike(item.name) + "%\"" + andNotZero;
}
System.out.println(" Query: " + odbQuery);
final List<KarmaObject> odbItems = mods.odb.retrieve(KarmaObject.class, odbQuery);
if (odbItems.size() == 0) {
irc.sendContextReply(mes, "No karma items matched " + (item.regex ? "/" : "\"") + item.name + Colors.NORMAL + (item.regex ? "/" : "\"") + ".");
} else {
Collections.sort(odbItems, new KarmaSortByAbsValue());
String rpl = "Karma items matching " + (item.regex ? "/" : "\"") + item.name + Colors.NORMAL + (item.regex ? "/" : "\"") + ": ";
boolean cutOff = false;
for (int j = 0; j < odbItems.size(); j++) {
final KarmaObject ko = odbItems.get(j);
if (rpl.length() + ko.string.length() > 350) {
cutOff = true;
break;
}
if (j > 0) {
rpl += ", ";
}
rpl += formatKarmaNameForIRC(ko.string) + " (" + ko.value + ")";
}
if (cutOff) {
rpl += ", ...";
} else {
rpl += ".";
}
irc.sendContextReply(mes, rpl);
}
}
//List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
//List<String> names = new ArrayList<String>();
//if (params.size() > 0)
// for (int i=0; i<params.size(); i++)
// {
// }
}
public String[] helpCommandList = {
"Get a list of all karma objects.",
};
public String commandList (final String mes)
{
return "No chance, matey.";
}
public void webList(final PrintWriter out, final String params, final String[] user)
{
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
out.println("<HTML>");
out.println("<HEAD>");
out.println("</HEAD>");
out.println("<BODY>");
// Parse input data.
String karmaSearch = "";
for (final String param : params.split("&")) {
if (param.startsWith("s=")) {
karmaSearch = param.substring(2);
} else if (param.indexOf("=") == -1) {
karmaSearch = normalise(param);
}
}
// Search form!
out.println("<FORM METHOD='GET' STYLE='float: right;'>");
out.println("/<INPUT TYPE='TEXT' NAME='s' SIZE='20'>/i <INPUT TYPE='SUBMIT' VALUE='Search'>");
out.println("</FORM>");
// Fetch results.
List<KarmaObject> karmaObjects = null;
if (karmaSearch != "") {
karmaObjects = retrieveKarmaObjects("WHERE string RLIKE \"" + mods.odb.escapeForRLike(karmaSearch) + "\" AND NOT (up = 0 AND down = 0 AND value = 0) SORT INTEGER value");
out.println("<H1>" + karmaObjects.size() + " karma item" + (karmaObjects.size() == 1 ? "" : "s") + " matching /" + mods.scrape.escapeForHTML(karmaSearch) + "/i</H1>");
} else {
karmaObjects = retrieveKarmaObjects("WHERE 1 SORT INTEGER value");
out.println("<H1>All Karma items</H1>");
}
Collections.sort(karmaObjects, new KarmaSortByAbsValue());
// Show table of karma items.
out.println(" <TABLE>");
out.print(" <TR>");
out.print("<TH>Item</TH>");
out.print("<TH>Value</TH>");
out.print("<TH>Up</TH>");
out.print("<TH>Down</TH>");
out.println("</TR>");
for (final KarmaObject karmaObject: karmaObjects) {
if (karmaObject != null) {
out.println(" <TR>");
out.print("<TD><A HREF='Karma.View?id=" + karmaObject.id + "'>" + mods.scrape.escapeForHTML(karmaObject.string) + "</A></TD>");
out.print("<TD>" + karmaObject.value + "</TD>");
out.print("<TD>" + karmaObject.up + "</TD>");
out.print("<TD>" + karmaObject.down + "</TD>");
out.println("</TR>");
}
}
out.println(" </TABLE>");
out.println("</BODY>");
out.println("</HTML>");
}
public void webView(final PrintWriter out, final String params, final String[] user)
{
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
out.println("<HTML>");
out.println("<HEAD>");
out.println("</HEAD>");
out.println("<BODY>");
// Parse input data.
int karmaId = 0;
for (final String param : params.split("&")) {
if (param.startsWith("id=")) {
karmaId = Integer.parseInt(param.substring(3));
} else if (param.indexOf("=") == -1) {
final List<KarmaObject> temp = mods.odb.retrieve(KarmaObject.class, "WHERE string = \"" + mods.odb.escapeString(param) + "\"");
if (temp.size() == 1) {
karmaId = temp.get(0).id;
}
}
}
// Fetch karma item.
final List<KarmaObject> karmaObjects = mods.odb.retrieve(KarmaObject.class, "WHERE id = " + karmaId);
if (karmaObjects.size() >= 1) {
final KarmaObject karmaObject = karmaObjects.get(0);
out.println("<H1>Karma item \"" + mods.scrape.escapeForHTML(karmaObject.string) + "\"</H1>");
// Show table of data about this item.
out.println(" <TABLE>");
out.println(" <TR><TH ALIGN='LEFT'>Item</TH><TD>" + mods.scrape.escapeForHTML(karmaObject.string) + "</TD></TR>");
out.println(" <TR><TH ALIGN='LEFT'>Value</TH><TD>" + karmaObject.value + "</TD></TR>");
out.println(" <TR><TH ALIGN='LEFT'>Up</TH><TD>" + karmaObject.up + "</TD></TR>");
out.println(" <TR><TH ALIGN='LEFT'>Down</TH><TD>" + karmaObject.down + "</TD></TR>");
out.println(" </TABLE>");
out.println(" <TABLE>");
boolean inUp = false;
boolean inUnchanged = false;
boolean inDown = false;
final List<KarmaReasonObject> reasons = mods.odb.retrieve(KarmaReasonObject.class, "WHERE string = \"" + mods.odb.escapeString(karmaObject.string) + "\" SORT INTEGER direction");
for (final KarmaReasonObject reason : reasons) {
if (!inUp && reason.direction == 1) {
//out.println(" <TR><TH>Reasons for gaining karma</TH></TR>");
inUp = true;
} else if (!inUnchanged && reason.direction == 0) {
//out.println(" <TR><TH>Reasons for unchanged karma</TH></TR>");
inUnchanged = true;
} else if (!inDown && reason.direction == -1) {
//out.println(" <TR><TH>Reasons for losing karma</TH></TR>");
inDown = true;
}
out.println(" <TR><TD>" + mods.scrape.escapeForHTML(karmaObject.string + " has " + (reason.direction > 0 ? "gained" : (reason.direction < 0 ? "lost" : "unchanged")) + " karma " + reason.reason) + "</TD></TR>");
}
out.println(" </TABLE>");
} else {
out.println(" <P>The karma ID " + karmaId + " is not valid.</P>");
}
out.println("</BODY>");
out.println("</HTML>");
}
private String normalise(final String name)
{
return name.replaceAll(" ", "_");
}
private String formatKarmaNameForIRC(final String name)
{
return "\"" + name + Colors.NORMAL + "\"";
}
private String getName (final Matcher ma)
{
if (ma.group(1) != null)
return ma.group(1).replaceAll("\\\\(.)", "$1");
return ma.group(2);
}
}
| true | true | public synchronized void filterKarma(final Message mes)
{
// Ignore lines that look like commands.
if (mes.getFlags().containsKey("command"))
return;
final String message = mes.getMessage();
final String nick = mods.nick.getBestPrimaryNick(mes.getNick());
//System.err.println("LINE : <" + message + ">");
final List<Integer> matchStarts = new ArrayList<Integer>();
final Matcher karmaScan = karmaPattern.matcher(message);
while (karmaScan.find())
matchStarts.add(karmaScan.start());
matchStarts.add(message.length());
final List<List<String>> matches = new ArrayList<List<String>>();
for (int matchIndex = 1; matchIndex < matchStarts.size(); matchIndex++)
{
//System.err.println("");
final String submessage = message.substring(matchStarts.get(matchIndex - 1), matchStarts.get(matchIndex)).replaceAll("[^\\+\\-\\)\\w]+$", "");
//System.err.println(" SEGMENT : <" + submessage + ">");
Matcher karmaMatch = karmaPatternWithReason.matcher(submessage);
if (!karmaMatch.find())
{
karmaMatch = karmaPattern.matcher(submessage);
karmaMatch.find();
}
//System.err.println(" MATCH : <" + karmaMatch.group() + ">");
//for (int i = 1; i <= karmaMatch.groupCount(); i++)
// System.err.println(" GROUP " + i + ": <" + karmaMatch.group(i) + ">");
List<String> groups = new ArrayList<String>();
for (int i = 0; i <= karmaMatch.groupCount(); i++)
groups.add(karmaMatch.group(i));
matches.add(groups);
}
// List of all karma changes that will be applied and hash of them
// so we can handle duplicates sanely.
final List<KarmaChangeHolder> karmas = new ArrayList<KarmaChangeHolder>();
final Map<String,KarmaChangeHolder> karmaMap = new HashMap<String,KarmaChangeHolder>();
for (final List<String> match : matches)
{
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
// Group 4: reason (optional)
String name = "";
if (match.get(1) != null)
{
name = match.get(1).replaceAll("\\\\(.)", "$1");
}
else
{
name = match.get(2);
if (exceptions.contains(name.toLowerCase()))
continue;
}
KarmaChangeHolder karma;
if (karmaMap.containsKey(name.toLowerCase()))
karma = karmaMap.get(name.toLowerCase());
else
karma = new KarmaChangeHolder(name);
// If it's "me", replace with user's nickname and force to down.
if (karma.instanceName.equals/*NOT IgnoreCase*/("me") || karma.instanceName.equals/*NOT IgnoreCase*/("Me") || karma.instanceName.equalsIgnoreCase(nick))
{
karma.instanceName = nick;
karma.change--;
}
// Up or down?
else if (match.get(3).equals("++"))
{
karma.change++;
}
else if (match.get(3).equals("--"))
{
karma.change--;
}
// Get the reason, if it's not excluded!
if (match.size() > 4 && !reasonExceptions.contains(match.get(4)))
{
KarmaReasonObject reason = new KarmaReasonObject();
reason.reason = match.get(4);
reason.direction = match.get(3).equals("++") ? 1 : (match.get(3).equals("--") ? -1 : 0);
karma.reasons.add(reason);
}
if (!karmaMap.containsKey(name.toLowerCase()))
{
karmas.add(karma);
karmaMap.put(karma.instanceName.toLowerCase(), karma);
}
}
// No karma changes? Boring!
if (karmas.size() == 0)
return;
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
// Right. We have a list of karma to apply, we've checked it's a public
// place and we have no duplicates. Time for the flood checking.
for (final KarmaChangeHolder karma : karmas)
{
try
{
// 15 minute block for each karma item, irespective of who or direction.
final int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + normalise(karma.instanceName), FLOOD_RATE, 2);
if (ret != 0)
{
karma.flood = true;
continue;
}
}
catch (final ChoobNoSuchCallException e)
{ } // ignore
catch (final Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
}
// Apply all the karma changes!
for (final KarmaChangeHolder karma : karmas)
{
// Flooded? Skip it!
if (karma.flood)
continue;
// Fetch the existing karma data for this item.
karma.karma = retrieveKarmaObject(karma.instanceName);
// Do up or down change first.
if (karma.change > 0)
{
karma.karma.up++;
karma.karma.value++;
}
else if (karma.change < 0)
{
karma.karma.down++;
karma.karma.value--;
}
// Save the new karma data.
mods.odb.update(karma.karma);
// Now add the reason(s). Note that there's nothing to retrieve
// here so we can save the local object directly.
for (KarmaReasonObject reason : karma.reasons)
{
reason.string = karma.karma.string;
mods.odb.save(reason);
}
}
// Generate a pretty reply, all actual processing is done now:
if (karmas.size() == 1)
{
final KarmaChangeHolder karma = karmas.get(0);
if (karma.flood)
irc.sendContextReply(mes, "Denied change to " + formatKarmaNameForIRC(karma.instanceName) + "! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
else if (karma.karma.string.equals(nick))
// This doesn't mention if there was a reason.
irc.sendContextReply(mes, "Fool, that's less karma to you! That leaves you with " + karma.karma.value + ".");
else
irc.sendContextReply(mes, (karma.change > 0 ? "Given more karma" : karma.change < 0 ? "Given less karma" : "No change") + " to " + formatKarmaNameForIRC(karma.instanceName) + (karma.reasons.size() == 1 ? " and understood your reason" : (karma.reasons.size() > 1 ? " and understood your reasons" : "")) + ". " + (karma.change == 0 ? "Karma remains at " : "New karma is ") + karma.karma.value + ".");
}
else
{
final StringBuffer output = new StringBuffer("Karma adjustments: ");
for (int i = 0; i < karmas.size(); i++)
{
final KarmaChangeHolder karma = karmas.get(i);
output.append(formatKarmaNameForIRC(karma.instanceName));
if (karma.flood)
{
output.append(" ignored (flood)");
}
else
{
if (karma.change > 0)
output.append(" up");
else if (karma.change < 0)
output.append(" down");
else
output.append(" unchanged");
if (karma.reasons.size() > 1)
output.append(" with reasons");
else if (karma.reasons.size() == 1)
output.append(" with reason");
if (karma.change == 0)
output.append(" (remains " + karma.karma.value + ")");
else
output.append(" (now " + karma.karma.value + ")");
}
if (i < karmas.size() - 1)
output.append(", ");
else if (i == karmas.size() - 2)
output.append(" and ");
}
output.append(".");
irc.sendContextReply(mes, output.toString());
}
}
| public synchronized void filterKarma(final Message mes)
{
// Ignore lines that look like commands.
if (mes.getFlags().containsKey("command"))
return;
final String message = mes.getMessage();
final String nick = mods.nick.getBestPrimaryNick(mes.getNick());
//System.err.println("LINE : <" + message + ">");
final List<Integer> matchStarts = new ArrayList<Integer>();
final Matcher karmaScan = karmaPattern.matcher(message);
while (karmaScan.find())
matchStarts.add(karmaScan.start());
matchStarts.add(message.length());
final List<List<String>> matches = new ArrayList<List<String>>();
for (int matchIndex = 1; matchIndex < matchStarts.size(); matchIndex++)
{
//System.err.println("");
final String submessage = message.substring(matchStarts.get(matchIndex - 1), matchStarts.get(matchIndex));
//System.err.println(" SEGMENT : <" + submessage + ">");
Matcher karmaMatch = karmaPatternWithReason.matcher(submessage);
if (!karmaMatch.find())
{
karmaMatch = karmaPattern.matcher(submessage);
karmaMatch.find();
}
//System.err.println(" MATCH : <" + karmaMatch.group() + ">");
//for (int i = 1; i <= karmaMatch.groupCount(); i++)
// System.err.println(" GROUP " + i + ": <" + karmaMatch.group(i) + ">");
List<String> groups = new ArrayList<String>();
for (int i = 0; i <= karmaMatch.groupCount(); i++)
groups.add(karmaMatch.group(i));
matches.add(groups);
}
// List of all karma changes that will be applied and hash of them
// so we can handle duplicates sanely.
final List<KarmaChangeHolder> karmas = new ArrayList<KarmaChangeHolder>();
final Map<String,KarmaChangeHolder> karmaMap = new HashMap<String,KarmaChangeHolder>();
for (final List<String> match : matches)
{
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
// Group 4: reason (optional)
String name = "";
if (match.get(1) != null)
{
name = match.get(1).replaceAll("\\\\(.)", "$1");
}
else
{
name = match.get(2);
if (exceptions.contains(name.toLowerCase()))
continue;
}
KarmaChangeHolder karma;
if (karmaMap.containsKey(name.toLowerCase()))
karma = karmaMap.get(name.toLowerCase());
else
karma = new KarmaChangeHolder(name);
// If it's "me", replace with user's nickname and force to down.
if (karma.instanceName.equals/*NOT IgnoreCase*/("me") || karma.instanceName.equals/*NOT IgnoreCase*/("Me") || karma.instanceName.equalsIgnoreCase(nick))
{
karma.instanceName = nick;
karma.change--;
}
// Up or down?
else if (match.get(3).equals("++"))
{
karma.change++;
}
else if (match.get(3).equals("--"))
{
karma.change--;
}
// Get the reason, if it's not excluded!
if (match.size() > 4 && !reasonExceptions.contains(match.get(4)))
{
KarmaReasonObject reason = new KarmaReasonObject();
reason.reason = match.get(4);
reason.direction = match.get(3).equals("++") ? 1 : (match.get(3).equals("--") ? -1 : 0);
karma.reasons.add(reason);
}
if (!karmaMap.containsKey(name.toLowerCase()))
{
karmas.add(karma);
karmaMap.put(karma.instanceName.toLowerCase(), karma);
}
}
// No karma changes? Boring!
if (karmas.size() == 0)
return;
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
// Right. We have a list of karma to apply, we've checked it's a public
// place and we have no duplicates. Time for the flood checking.
for (final KarmaChangeHolder karma : karmas)
{
try
{
// 15 minute block for each karma item, irespective of who or direction.
final int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + normalise(karma.instanceName), FLOOD_RATE, 2);
if (ret != 0)
{
karma.flood = true;
continue;
}
}
catch (final ChoobNoSuchCallException e)
{ } // ignore
catch (final Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
}
// Apply all the karma changes!
for (final KarmaChangeHolder karma : karmas)
{
// Flooded? Skip it!
if (karma.flood)
continue;
// Fetch the existing karma data for this item.
karma.karma = retrieveKarmaObject(karma.instanceName);
// Do up or down change first.
if (karma.change > 0)
{
karma.karma.up++;
karma.karma.value++;
}
else if (karma.change < 0)
{
karma.karma.down++;
karma.karma.value--;
}
// Save the new karma data.
mods.odb.update(karma.karma);
// Now add the reason(s). Note that there's nothing to retrieve
// here so we can save the local object directly.
for (KarmaReasonObject reason : karma.reasons)
{
reason.string = karma.karma.string;
mods.odb.save(reason);
}
}
// Generate a pretty reply, all actual processing is done now:
if (karmas.size() == 1)
{
final KarmaChangeHolder karma = karmas.get(0);
if (karma.flood)
irc.sendContextReply(mes, "Denied change to " + formatKarmaNameForIRC(karma.instanceName) + "! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
else if (karma.karma.string.equals(nick))
// This doesn't mention if there was a reason.
irc.sendContextReply(mes, "Fool, that's less karma to you! That leaves you with " + karma.karma.value + ".");
else
irc.sendContextReply(mes, (karma.change > 0 ? "Given more karma" : karma.change < 0 ? "Given less karma" : "No change") + " to " + formatKarmaNameForIRC(karma.instanceName) + (karma.reasons.size() == 1 ? " and understood your reason" : (karma.reasons.size() > 1 ? " and understood your reasons" : "")) + ". " + (karma.change == 0 ? "Karma remains at " : "New karma is ") + karma.karma.value + ".");
}
else
{
final StringBuffer output = new StringBuffer("Karma adjustments: ");
for (int i = 0; i < karmas.size(); i++)
{
final KarmaChangeHolder karma = karmas.get(i);
output.append(formatKarmaNameForIRC(karma.instanceName));
if (karma.flood)
{
output.append(" ignored (flood)");
}
else
{
if (karma.change > 0)
output.append(" up");
else if (karma.change < 0)
output.append(" down");
else
output.append(" unchanged");
if (karma.reasons.size() > 1)
output.append(" with reasons");
else if (karma.reasons.size() == 1)
output.append(" with reason");
if (karma.change == 0)
output.append(" (remains " + karma.karma.value + ")");
else
output.append(" (now " + karma.karma.value + ")");
}
if (i < karmas.size() - 1)
output.append(", ");
else if (i == karmas.size() - 2)
output.append(" and ");
}
output.append(".");
irc.sendContextReply(mes, output.toString());
}
}
|
diff --git a/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/menus/MenuFactory.java b/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/menus/MenuFactory.java
index 132b5857..d4bd120a 100644
--- a/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/menus/MenuFactory.java
+++ b/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/menus/MenuFactory.java
@@ -1,240 +1,240 @@
package org.strategoxt.imp.runtime.services.menus;
import static org.spoofax.interpreter.core.Tools.termAt;
import static org.strategoxt.imp.runtime.dynamicloading.TermReader.collectTerms;
import static org.strategoxt.imp.runtime.dynamicloading.TermReader.cons;
import static org.strategoxt.imp.runtime.dynamicloading.TermReader.termContents;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.URIUtil;
import org.eclipse.imp.editor.UniversalEditor;
import org.eclipse.imp.parser.IParseController;
import org.eclipse.jface.resource.ImageDescriptor;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.strategoxt.imp.runtime.EditorState;
import org.strategoxt.imp.runtime.Environment;
import org.strategoxt.imp.runtime.dynamicloading.AbstractServiceFactory;
import org.strategoxt.imp.runtime.dynamicloading.BadDescriptorException;
import org.strategoxt.imp.runtime.dynamicloading.Descriptor;
import org.strategoxt.imp.runtime.parser.SGLRParseController;
import org.strategoxt.imp.runtime.services.StrategoObserver;
import org.strategoxt.imp.runtime.services.menus.contribs.CustomStrategyBuilder;
import org.strategoxt.imp.runtime.services.menus.contribs.DebugModeBuilder;
import org.strategoxt.imp.runtime.services.menus.contribs.IBuilder;
import org.strategoxt.imp.runtime.services.menus.contribs.Menu;
import org.strategoxt.imp.runtime.services.menus.contribs.Separator;
import org.strategoxt.imp.runtime.services.menus.contribs.StrategoBuilder;
/**
* @author Lennart Kats <lennart add lclnet.nl>
* @author Oskar van Rest
*/
public class MenuFactory extends AbstractServiceFactory<IMenuList> {
public MenuFactory() {
super(IMenuList.class, false); // not cached; depends on derived editor relation
}
@Override
public IMenuList create(Descriptor d, SGLRParseController controller) throws BadDescriptorException {
List<Menu> menus = new LinkedList<Menu>();
EditorState derivedFromEditor = getDerivedFromEditor(controller);
if (d.isATermEditor() && derivedFromEditor != null)
addDerivedMenus(derivedFromEditor, menus);
addMenus(d, controller, menus, null);
addCustomStrategyBuilder(d, controller, menus, derivedFromEditor);
if (Environment.allowsDebugging(d)) // Descriptor allows debugging)
{
addDebugModeBuilder(d, controller, menus, derivedFromEditor);
}
return new MenuList(menus);
}
private static void addMenus(Descriptor d, SGLRParseController controller, List<Menu> menus, EditorState derivedFromEditor) throws BadDescriptorException {
// BEGIN: 'Transform' menu backwards compatibility
ArrayList<IStrategoAppl> builders = collectTerms(d.getDocument(), "Builder");
for (IStrategoAppl b : builders) {
String caption = termContents(termAt(b, 0));
List<String> path = createPath(createPath(Collections.<String> emptyList(), MenusServiceConstants.OLD_LABEL), caption);
IBuilder builder = createBuilder(b, path, d, controller, derivedFromEditor);
if (builder != null) {
Menu menu = null;
for (Menu m : menus) {
if (m.getCaption().equals(MenusServiceConstants.OLD_LABEL)) {
menu = m;
}
}
if (menu == null) {
menu = new Menu(MenusServiceConstants.OLD_LABEL);
menus.add(0, menu);
}
menu.addMenuContribution(builder);
}
}
// END: 'Transform' menu backwards compatibility
for (IStrategoAppl m : collectTerms(d.getDocument(), "ToolbarMenu")) {
String caption = termContents(termAt(m, 0)); // caption = label or icon path
Menu menu = new Menu(caption);
if (((IStrategoAppl) termAt(m, 0)).getConstructor().getName().equals("Icon")) {
String iconPath = caption;
String pluginPath = d.getBasePath().toOSString();
File iconFile = new File(pluginPath, iconPath);
if (iconFile.exists()) {
ImageDescriptor imageDescriptor = null;
try {
imageDescriptor = ImageDescriptor.createFromURL(URIUtil.toURL(iconFile.toURI()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
menu.setIcon(imageDescriptor);
}
}
List<String> path = createPath(Collections.<String> emptyList(), caption);
- addMenuContribs(menu, m.getSubterm(2), path, d, controller, derivedFromEditor); // TODO: 2 --> 1
+ addMenuContribs(menu, m.getSubterm(1), path, d, controller, derivedFromEditor);
menus.add(menu);
}
}
private static List<String> createPath(List<String> init, String last) {
List<String> result = new LinkedList<String>(init);
result.add(last);
return result;
}
private static void addMenuContribs(Menu menu, IStrategoTerm menuContribs, List<String> path, Descriptor d, SGLRParseController controller, EditorState derivedFromEditor) throws BadDescriptorException {
for (IStrategoAppl a : collectTerms(menuContribs, "Action", "Separator", "Submenu")) {
String cons = a.getConstructor().getName();
if (cons.equals("Action")) {
String caption = termContents(termAt(a, 0));
IBuilder builder = createBuilder(a, createPath(path, caption), d, controller, derivedFromEditor);
if (builder != null) {
menu.addMenuContribution(builder);
}
} else if (cons.equals("Separator")) {
menu.addMenuContribution(new Separator());
} else if (cons.equals("Submenu")) {
String caption = termContents(termAt(a, 0));
Menu submenu = new Menu(caption);
addMenuContribs(submenu, a.getSubterm(1), createPath(path, caption), d, controller, derivedFromEditor);
menu.addMenuContribution(submenu);
}
}
}
private static IBuilder createBuilder(IStrategoTerm action, List<String> path, Descriptor d, SGLRParseController controller, EditorState derivedFromEditor) throws BadDescriptorException {
StrategoObserver feedback = d.createService(StrategoObserver.class, controller);
String strategy = termContents(termAt(action, 1));
IStrategoList options = termAt(action, 2);
boolean openEditor = false;
boolean realTime = false;
boolean persistent = false;
boolean meta = false;
boolean cursor = false;
boolean source = false;
for (IStrategoTerm option : options.getAllSubterms()) {
String type = cons(option);
if (type.equals("OpenEditor")) {
openEditor = true;
} else if (type.equals("RealTime")) {
realTime = true;
} else if (type.equals("Persistent")) {
persistent = true;
} else if (type.equals("Meta")) {
meta = true;
} else if (type.equals("Cursor")) {
cursor = true;
} else if (type.equals("Source")) {
source = true;
} else {
throw new BadDescriptorException("Unknown builder annotation: " + type);
}
}
if (!meta || d.isDynamicallyLoaded())
return new StrategoBuilder(feedback, path, strategy, openEditor, realTime, cursor, source, persistent, derivedFromEditor);
else
return null;
}
private static void addDerivedMenus(EditorState derivedFromEditor, List<Menu> menus) throws BadDescriptorException {
if (derivedFromEditor != null) {
addMenus(derivedFromEditor.getDescriptor(), derivedFromEditor.getParseController(), menus, derivedFromEditor);
}
}
private static void addCustomStrategyBuilder(Descriptor d, SGLRParseController controller, List<Menu> menus, EditorState derivedFromEditor) throws BadDescriptorException {
if (d.isATermEditor() && derivedFromEditor != null) {
StrategoObserver feedback = derivedFromEditor.getDescriptor().createService(StrategoObserver.class, controller);
addCustomStrategyBuilderHelper(menus, feedback, derivedFromEditor);
} else if (d.isDynamicallyLoaded()) {
StrategoObserver feedback = d.createService(StrategoObserver.class, controller);
addCustomStrategyBuilderHelper(menus, feedback, null);
}
}
private static void addCustomStrategyBuilderHelper(List<Menu> menus, StrategoObserver feedback, EditorState derivedFromEditor) {
for (Menu menu : menus) {
List<String> path = new LinkedList<String>();
path.add(menu.getCaption());
path.add(CustomStrategyBuilder.CAPTION);
menu.addMenuContribution(new Separator());
menu.addMenuContribution(new CustomStrategyBuilder(path, feedback, derivedFromEditor));
}
}
/**
* Adds a Debug Mode Builder, if debug mode is allowed the user can choose to enable stratego
* debugging. If debugging is enabled, a new JVM is started for every strategy invoke resulting
* in major performance drops. The user can also disable Debug mode, without needing to rebuil
* the project.
*/
private static void addDebugModeBuilder(Descriptor d, SGLRParseController controller, List<Menu> menus, EditorState derivedFromEditor) throws BadDescriptorException {
StrategoObserver feedback = d.createService(StrategoObserver.class, controller);
for (Menu menu : menus) {
List<String> path = new LinkedList<String>();
path.add(menu.getCaption());
path.add(DebugModeBuilder.getCaption(feedback));
menu.addMenuContribution(new DebugModeBuilder(feedback, path));
}
}
private static EditorState getDerivedFromEditor(SGLRParseController controller) {
if (controller.getEditor() == null || controller.getEditor().getEditor() == null)
return null;
UniversalEditor editor = controller.getEditor().getEditor();
StrategoBuilderListener listener = StrategoBuilderListener.getListener(editor);
if (listener == null)
return null;
UniversalEditor sourceEditor = listener.getSourceEditor();
if (sourceEditor == null)
return null;
return EditorState.getEditorFor(sourceEditor.getParseController());
}
public static void eagerInit(Descriptor descriptor, IParseController parser, EditorState lastEditor) {
// Refresh toolbar menu commands after rebuilding.
MenusServiceUtil.refreshToolbarMenuCommands();
}
}
| true | true | private static void addMenus(Descriptor d, SGLRParseController controller, List<Menu> menus, EditorState derivedFromEditor) throws BadDescriptorException {
// BEGIN: 'Transform' menu backwards compatibility
ArrayList<IStrategoAppl> builders = collectTerms(d.getDocument(), "Builder");
for (IStrategoAppl b : builders) {
String caption = termContents(termAt(b, 0));
List<String> path = createPath(createPath(Collections.<String> emptyList(), MenusServiceConstants.OLD_LABEL), caption);
IBuilder builder = createBuilder(b, path, d, controller, derivedFromEditor);
if (builder != null) {
Menu menu = null;
for (Menu m : menus) {
if (m.getCaption().equals(MenusServiceConstants.OLD_LABEL)) {
menu = m;
}
}
if (menu == null) {
menu = new Menu(MenusServiceConstants.OLD_LABEL);
menus.add(0, menu);
}
menu.addMenuContribution(builder);
}
}
// END: 'Transform' menu backwards compatibility
for (IStrategoAppl m : collectTerms(d.getDocument(), "ToolbarMenu")) {
String caption = termContents(termAt(m, 0)); // caption = label or icon path
Menu menu = new Menu(caption);
if (((IStrategoAppl) termAt(m, 0)).getConstructor().getName().equals("Icon")) {
String iconPath = caption;
String pluginPath = d.getBasePath().toOSString();
File iconFile = new File(pluginPath, iconPath);
if (iconFile.exists()) {
ImageDescriptor imageDescriptor = null;
try {
imageDescriptor = ImageDescriptor.createFromURL(URIUtil.toURL(iconFile.toURI()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
menu.setIcon(imageDescriptor);
}
}
List<String> path = createPath(Collections.<String> emptyList(), caption);
addMenuContribs(menu, m.getSubterm(2), path, d, controller, derivedFromEditor); // TODO: 2 --> 1
menus.add(menu);
}
}
| private static void addMenus(Descriptor d, SGLRParseController controller, List<Menu> menus, EditorState derivedFromEditor) throws BadDescriptorException {
// BEGIN: 'Transform' menu backwards compatibility
ArrayList<IStrategoAppl> builders = collectTerms(d.getDocument(), "Builder");
for (IStrategoAppl b : builders) {
String caption = termContents(termAt(b, 0));
List<String> path = createPath(createPath(Collections.<String> emptyList(), MenusServiceConstants.OLD_LABEL), caption);
IBuilder builder = createBuilder(b, path, d, controller, derivedFromEditor);
if (builder != null) {
Menu menu = null;
for (Menu m : menus) {
if (m.getCaption().equals(MenusServiceConstants.OLD_LABEL)) {
menu = m;
}
}
if (menu == null) {
menu = new Menu(MenusServiceConstants.OLD_LABEL);
menus.add(0, menu);
}
menu.addMenuContribution(builder);
}
}
// END: 'Transform' menu backwards compatibility
for (IStrategoAppl m : collectTerms(d.getDocument(), "ToolbarMenu")) {
String caption = termContents(termAt(m, 0)); // caption = label or icon path
Menu menu = new Menu(caption);
if (((IStrategoAppl) termAt(m, 0)).getConstructor().getName().equals("Icon")) {
String iconPath = caption;
String pluginPath = d.getBasePath().toOSString();
File iconFile = new File(pluginPath, iconPath);
if (iconFile.exists()) {
ImageDescriptor imageDescriptor = null;
try {
imageDescriptor = ImageDescriptor.createFromURL(URIUtil.toURL(iconFile.toURI()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
menu.setIcon(imageDescriptor);
}
}
List<String> path = createPath(Collections.<String> emptyList(), caption);
addMenuContribs(menu, m.getSubterm(1), path, d, controller, derivedFromEditor);
menus.add(menu);
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/rest/MetricRestService.java b/GAE/src/org/waterforpeople/mapping/app/web/rest/MetricRestService.java
index 0dd140214..329f785ae 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/rest/MetricRestService.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/rest/MetricRestService.java
@@ -1,215 +1,215 @@
/*
* Copyright (C) 2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.app.web.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.waterforpeople.mapping.app.gwt.client.survey.MetricDto;
import org.waterforpeople.mapping.app.util.DtoMarshaller;
import org.waterforpeople.mapping.app.web.rest.dto.MetricPayload;
import org.waterforpeople.mapping.app.web.rest.dto.RestStatusDto;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.metric.dao.MetricDao;
import com.gallatinsystems.metric.dao.SurveyMetricMappingDao;
import com.gallatinsystems.metric.domain.Metric;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.domain.Question;
@Controller
@RequestMapping("/metrics")
public class MetricRestService {
@Inject
private MetricDao metricDao;
@Inject
private QuestionDao questionDao;
@Inject
private SurveyMetricMappingDao surveyMetricMappingDao;
// list all metrics, or the metrics for a single surveyId.
@RequestMapping(method = RequestMethod.GET, value = "")
@ResponseBody
public Map<String, List<MetricDto>> listMetrics(
@RequestParam(value = "surveyId", defaultValue = "") Long surveyId) {
final Map<String, List<MetricDto>> response = new HashMap<String, List<MetricDto>>();
List<MetricDto> results = new ArrayList<MetricDto>();
List<Question> questions = new ArrayList<Question>();
List<Metric> metrics = new ArrayList<Metric>();
if (surveyId != null) {
// get metrics for a specific survey
- questions = questionDao.listQuestionsInOrder(surveyId);
+ questions = questionDao.listQuestionsInOrder(surveyId,null);
if (questions != null && questions.size() > 0) {
for (Question question : questions) {
if (question.getMetricId() != null && question.getMetricId() != 0) {
// we have found a question with a metric,
// get the metric and put it in the dto
Metric m = metricDao.getByKey(question.getMetricId());
if (m != null) {
MetricDto mDto = new MetricDto();
DtoMarshaller.copyToDto(m, mDto);
mDto.setQuestionId(question.getKey().getId());
results.add(mDto);
}
}
}
}
} else {
// get all metrics
metrics = metricDao.list(Constants.ALL_RESULTS);
}
if (metrics != null) {
for (Metric s : metrics) {
MetricDto dto = new MetricDto();
DtoMarshaller.copyToDto(s, dto);
results.add(dto);
}
}
response.put("metrics", results);
return response;
}
// find a single metric by the metricId
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
@ResponseBody
public Map<String, MetricDto> findMetric(@PathVariable("id") Long id) {
final Map<String, MetricDto> response = new HashMap<String, MetricDto>();
Metric s = metricDao.getByKey(id);
MetricDto dto = null;
if (s != null) {
dto = new MetricDto();
DtoMarshaller.copyToDto(s, dto);
}
response.put("metric", dto);
return response;
}
// delete metric by id
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
@ResponseBody
public Map<String, RestStatusDto> deleteMetricById(
@PathVariable("id") Long id) {
final Map<String, RestStatusDto> response = new HashMap<String, RestStatusDto>();
Metric s = metricDao.getByKey(id);
RestStatusDto statusDto = null;
statusDto = new RestStatusDto();
statusDto.setStatus("failed");
// check if metric exists in the datastore
if (s != null) {
// delete metric
metricDao.delete(s);
// delete associated surveyMetricMappings
surveyMetricMappingDao.deleteMetricMappingByMetric(id);
statusDto.setStatus("ok");
}
response.put("meta", statusDto);
return response;
}
// update existing metric
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
@ResponseBody
public Map<String, Object> saveExistingMetric(
@RequestBody MetricPayload payLoad) {
final MetricDto metricDto = payLoad.getMetric();
final Map<String, Object> response = new HashMap<String, Object>();
MetricDto dto = null;
RestStatusDto statusDto = new RestStatusDto();
statusDto.setStatus("failed");
// if the POST data contains a valid metricDto, continue.
// Otherwise,
// server will respond with 400 Bad Request
if (metricDto != null) {
Long keyId = metricDto.getKeyId();
Metric s;
// if the metricDto has a key, try to get the metric.
if (keyId != null) {
s = metricDao.getByKey(keyId);
// if we find the metric, update it's properties
if (s != null) {
// copy the properties, except the createdDateTime property,
// because it is set in the Dao. The surveyId is not part of
// the metric object.
BeanUtils.copyProperties(metricDto, s, new String[] {
"createdDateTime", "surveyId" });
s = metricDao.save(s);
dto = new MetricDto();
DtoMarshaller.copyToDto(s, dto);
statusDto.setStatus("ok");
}
}
}
response.put("meta", statusDto);
response.put("metric", dto);
return response;
}
// create new metric
@RequestMapping(method = RequestMethod.POST, value = "")
@ResponseBody
public Map<String, Object> saveNewMetric(@RequestBody MetricPayload payLoad) {
final MetricDto metricDto = payLoad.getMetric();
final Map<String, Object> response = new HashMap<String, Object>();
MetricDto dto = null;
RestStatusDto statusDto = new RestStatusDto();
statusDto.setStatus("failed");
// if the POST data contains a valid metricDto, continue.
// Otherwise,
// server will respond with 400 Bad Request
if (metricDto != null) {
Metric s = new Metric();
// copy the properties, except the createdDateTime property, because
// it is set in the Dao. the surveyId is not part of the metric
// object
BeanUtils.copyProperties(metricDto, s, new String[] {
"createdDateTime", "surveyId" });
s = metricDao.save(s);
dto = new MetricDto();
DtoMarshaller.copyToDto(s, dto);
statusDto.setStatus("ok");
}
response.put("meta", statusDto);
response.put("metric", dto);
return response;
}
}
| true | true | public Map<String, List<MetricDto>> listMetrics(
@RequestParam(value = "surveyId", defaultValue = "") Long surveyId) {
final Map<String, List<MetricDto>> response = new HashMap<String, List<MetricDto>>();
List<MetricDto> results = new ArrayList<MetricDto>();
List<Question> questions = new ArrayList<Question>();
List<Metric> metrics = new ArrayList<Metric>();
if (surveyId != null) {
// get metrics for a specific survey
questions = questionDao.listQuestionsInOrder(surveyId);
if (questions != null && questions.size() > 0) {
for (Question question : questions) {
if (question.getMetricId() != null && question.getMetricId() != 0) {
// we have found a question with a metric,
// get the metric and put it in the dto
Metric m = metricDao.getByKey(question.getMetricId());
if (m != null) {
MetricDto mDto = new MetricDto();
DtoMarshaller.copyToDto(m, mDto);
mDto.setQuestionId(question.getKey().getId());
results.add(mDto);
}
}
}
}
} else {
// get all metrics
metrics = metricDao.list(Constants.ALL_RESULTS);
}
if (metrics != null) {
for (Metric s : metrics) {
MetricDto dto = new MetricDto();
DtoMarshaller.copyToDto(s, dto);
results.add(dto);
}
}
response.put("metrics", results);
return response;
}
| public Map<String, List<MetricDto>> listMetrics(
@RequestParam(value = "surveyId", defaultValue = "") Long surveyId) {
final Map<String, List<MetricDto>> response = new HashMap<String, List<MetricDto>>();
List<MetricDto> results = new ArrayList<MetricDto>();
List<Question> questions = new ArrayList<Question>();
List<Metric> metrics = new ArrayList<Metric>();
if (surveyId != null) {
// get metrics for a specific survey
questions = questionDao.listQuestionsInOrder(surveyId,null);
if (questions != null && questions.size() > 0) {
for (Question question : questions) {
if (question.getMetricId() != null && question.getMetricId() != 0) {
// we have found a question with a metric,
// get the metric and put it in the dto
Metric m = metricDao.getByKey(question.getMetricId());
if (m != null) {
MetricDto mDto = new MetricDto();
DtoMarshaller.copyToDto(m, mDto);
mDto.setQuestionId(question.getKey().getId());
results.add(mDto);
}
}
}
}
} else {
// get all metrics
metrics = metricDao.list(Constants.ALL_RESULTS);
}
if (metrics != null) {
for (Metric s : metrics) {
MetricDto dto = new MetricDto();
DtoMarshaller.copyToDto(s, dto);
results.add(dto);
}
}
response.put("metrics", results);
return response;
}
|
diff --git a/src/main/ed/js/engine/Convert.java b/src/main/ed/js/engine/Convert.java
index ea56b0353..affa5c7bd 100644
--- a/src/main/ed/js/engine/Convert.java
+++ b/src/main/ed/js/engine/Convert.java
@@ -1,1808 +1,1808 @@
// Convert.java
package ed.js.engine;
import java.io.*;
import java.util.*;
import com.twmacinta.util.*;
import org.mozilla.javascript.*;
import ed.js.*;
import ed.io.*;
import ed.lang.*;
import ed.util.*;
public class Convert implements StackTraceFixer {
static boolean DJS = Boolean.getBoolean( "DEBUG.JS" );
final boolean D;
public static final String DEFAULT_PACKAGE = "ed.js.gen";
public static JSFunction makeAnon( String code ){
return makeAnon( code , false );
}
public static JSFunction makeAnon( String code , boolean forceEval ){
try {
final String nice = code.trim();
final String name = "anon" + Math.random();
if ( nice.startsWith( "function" ) &&
nice.endsWith( "}" ) ){
Convert c = new Convert( name , code , true );
JSFunction func = c.get();
Scope s = Scope.newGlobal().child();
s.setGlobal( true );
func.call( s );
String keyToUse = null;
int numKeys = 0;
for ( String key : s.keySet() ){
if ( key.equals( "arguments" ) )
continue;
keyToUse = key;
numKeys++;
}
if ( numKeys == 1 ){
Object val = s.get( keyToUse );
if ( val instanceof JSFunction ){
JSFunction f = (JSFunction)val;
f.setUsePassedInScope( forceEval );
return f;
}
}
}
Convert c = new Convert( name , nice , forceEval );
return c.get();
}
catch ( IOException ioe ){
throw new RuntimeException( "should be impossible" , ioe );
}
}
public Convert( File sourceFile )
throws IOException {
this( sourceFile.getAbsolutePath() , StreamUtil.readFully( sourceFile , "UTF-8" ) );
}
public Convert( String name , String source )
throws IOException {
this(name, source, false);
}
public Convert( String name , String source, boolean invokedFromEval)
throws IOException {
this( name , source , invokedFromEval , Language.JS );
}
public Convert( String name , String source, boolean invokedFromEval , Language sourceLanguage )
throws IOException {
D = DJS
&& ! name.contains( "src/main/ed/lang" )
&& ! name.contains( "src_main_ed_lang" )
;
_invokedFromEval = invokedFromEval;
_sourceLanguage = sourceLanguage;
_name = name;
_source = source;
_className = cleanName( _name ) + _getNumForClass( _name , _source );
_fullClassName = _package + "." + _className;
CompilerEnvirons ce = new CompilerEnvirons();
Parser p = new Parser( ce , ce.getErrorReporter() );
ScriptOrFnNode theNode = null;
try {
theNode = p.parse( _source , _name , 0 );
}
catch ( org.mozilla.javascript.EvaluatorException ee ){
throw new RuntimeException( "can't compile [" + ee.getMessage() + "]" );
}
_encodedSource = p.getEncodedSource();
init( theNode );
}
public static String cleanName( String name ){
return name.replaceAll( "[^\\w]+" , "_" );
}
private void init( ScriptOrFnNode sn ){
if ( _it != null )
throw new RuntimeException( "too late" );
NodeTransformer nf = new NodeTransformer();
nf.transform( sn );
if ( D ){
Debug.print( sn , 0 );
}
State state = new State();
_setLineNumbers( sn , sn );
_addFunctionNodes( sn , state );
if ( D ) System.out.println( "***************" );
Node n = sn.getFirstChild();
while ( n != null ){
if ( n.getType() != Token.FUNCTION ){
if ( n.getNext() == null ){
if ( n.getType() == Token.EXPR_RESULT ){
_append( "return " , n );
_hasReturn = true;
}
if ( n.getType() == Token.RETURN )
_hasReturn = true;
}
_add( n , sn , state );
_append( "\n" , n );
}
n = n.getNext();
}
if ( ! _hasReturn ) {
_append( "return null;" , sn );
}
else {
int end = _mainJavaCode.length() - 1;
boolean alreadyHaveOne = false;
for ( ; end >= 0; end-- ){
char c = _mainJavaCode.charAt( end );
if ( Character.isWhitespace( c ) )
continue;
if ( c == ';' ){
if ( ! alreadyHaveOne ){
alreadyHaveOne = true;
continue;
}
_mainJavaCode.setLength( end + 1 );
}
break;
}
}
}
private void _add( Node n , State s ){
_add( n , null , s );
}
private void _add( Node n , ScriptOrFnNode sn , State state ){
switch ( n.getType() ){
case Token.TYPEOF:
_append( "JS_typeof( " , n );
_assertOne( n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.TYPEOFNAME:
_append( "JS_typeof( " , n );
if ( state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
_append( " ) " , n );
break;
case Token.REGEXP:
int myId = _regex.size();
ScriptOrFnNode parent = _nodeToSOR.get( n );
int rId = n.getIntProp( Node.REGEXP_PROP , -1 );
_regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) );
_append( " _regex[" + myId + "] " , n );
break;
case Token.ARRAYLIT:
{
_append( "( JSArray.create( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) ) " , n );
}
break;
case Token.OBJECTLIT:
{
_append( "JS_buildLiteralObject( new String[]{ " , n );
boolean first = true;
Node c = n.getFirstChild();
for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){
if ( first )
first = false;
else
_append( " , " , n );
String name = id.toString();
if ( c.getType() == Token.GET )
name = JSObjectBase.getterName( name );
else if ( c.getType() == Token.SET )
name = JSObjectBase.setterName( name );
_append( getStringCode( name ) + ".toString()" , n );
c = c.getNext();
}
_append( " } " , n );
c = n.getFirstChild();
while ( c != null ){
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) " , n );
}
break;
case Token.NEW:
_append( "scope.clearThisNew( " , n );
_addCall( n , state , true );
_append( " ) " , n );
break;
case Token.THIS:
_append( "passedIn.getThis()" , n );
break;
case Token.INC:
case Token.DEC:
_assertOne( n );
Node tempChild = n.getFirstChild();
if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){
if ( ! state.isNumber( tempChild.getString() ) )
throw new RuntimeException( "can't increment local variable : " + tempChild.getString() );
_append( tempChild.getString() + "++ " , n );
}
else {
_append( "JS_inc( " , n );
_createRef( n.getFirstChild() , state );
_append( " , " , n );
_append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n );
_append( " , " , n );
_append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n );
_append( ")" , n );
}
break;
case Token.USE_STACK:
_append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n );
break;
case Token.SETPROP_OP:
case Token.SETELEM_OP:
Node theOp = n.getFirstChild().getNext().getNext();
if ( theOp.getType() == Token.ADD &&
( theOp.getFirstChild().getType() == Token.USE_STACK ||
theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){
_append( "\n" , n );
_append( "JS_setDefferedPlus( (JSObject) " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( theOp.getFirstChild().getType() == Token.USE_STACK ?
theOp.getFirstChild().getNext() :
theOp.getFirstChild() ,
state );
_append( " \n ) \n" , n );
break;
}
_append( "\n { \n" , n );
_append( "JSObject __tempObject = (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
String tempName = "__temp" + (int)(Math.random() * 10000);
state._tempOpNames.push( tempName );
_append( "Object " + tempName + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( ";\n" , n );
_append( " __tempObject.set(" , n );
_append( tempName , n );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); \n" , n );
_append( " } \n" , n );
break;
case Token.SETPROP:
case Token.SETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").set( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) " , n );
break;
case Token.GETPROPNOWARN:
case Token.GETPROP:
case Token.GETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").get( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.SET_REF:
_assertType( n.getFirstChild() , Token.REF_SPECIAL );
_append( "((JSObject)" , n );
_add( n.getFirstChild().getFirstChild() , state );
_append( ").set( \"" , n );
_append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n );
_append( "\" , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.GET_REF:
_assertType( n.getFirstChild() , Token.REF_SPECIAL );
_append( "((JSObject)" , n );
_add( n.getFirstChild().getFirstChild() , state );
_append( ").get( \"" , n );
_append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n );
_append( "\" )" , n );
break;
case Token.EXPR_RESULT:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.CALL:
_addCall( n , state );
break;
case Token.NUMBER:
double d = n.getDouble();
String temp = String.valueOf( d );
if ( temp.endsWith( ".0" ) ||
JSNumericFunctions.couldBeInt( d ) )
temp = String.valueOf( (int)d );
_append( "JSNumber.self( " + temp + ")" , n );
break;
case Token.STRING:
final String theString = n.getString();
_append( getStringCode( theString ) , n );
break;
case Token.TRUE:
_append( " true " , n );
break;
case Token.FALSE:
_append( " false " , n );
break;
case Token.NULL:
_append( " null " , n );
break;
case Token.VAR:
_addVar( n , state );
break;
case Token.GETVAR:
if ( state.useLocalVariable( n.getString() ) ){
_append( n.getString() , n );
break;
}
case Token.NAME:
if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
break;
case Token.SETVAR:
final String foo = n.getFirstChild().getString();
if ( state.useLocalVariable( foo ) ){
if ( ! state.hasSymbol( foo ) )
throw new RuntimeException( "something is wrong" );
if ( ! state.isPrimitive( foo ) )
_append( "JSInternalFunctions.self ( " , n );
_append( foo + " = " , n );
_add( n.getFirstChild().getNext() , state );
if ( ! state.isPrimitive( foo ) )
_append( " )\n" , n );
}
else {
_setVar( foo ,
n.getFirstChild().getNext() ,
state , true );
}
break;
case Token.SETNAME:
_addSet( n , state );
break;
case Token.GET:
_addFunction( n.getFirstChild() , state );
break;
case Token.SET:
_addFunction( n.getFirstChild() , state );
break;
case Token.FUNCTION:
_addFunction( n , state );
break;
case Token.BLOCK:
_addBlock( n , state );
break;
case Token.EXPR_VOID:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.RETURN:
boolean last = n.getNext() == null;
if ( ! last )
_append( "if ( true ) { " , n );
_append( "return " , n );
if ( n.getFirstChild() != null ){
_assertOne( n );
_add( n.getFirstChild() , state );
}
else {
_append( " null " , n );
}
_append( ";" , n );
if ( ! last )
_append( "}" , n );
_append( "\n" , n );
break;
case Token.BITNOT:
_assertOne( n );
_append( "JS_bitnot( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.HOOK:
_append( " JSInternalFunctions.self( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ? ( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) : ( " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) ) " , n );
break;
case Token.POS:
_assertOne( n );
_add( n.getFirstChild() , state );
break;
case Token.ADD:
if ( state.isNumberAndLocal( n.getFirstChild() ) &&
state.isNumberAndLocal( n.getFirstChild().getNext() ) ){
_append( "(" , n );
_add( n.getFirstChild() , state );
_append( " + " , n );
_add( n.getFirstChild().getNext() , state );
_append( ")" , n );
break;
}
case Token.NE:
case Token.MUL:
case Token.DIV:
case Token.SUB:
case Token.EQ:
case Token.SHEQ:
case Token.SHNE:
case Token.GE:
case Token.LE:
case Token.LT:
case Token.GT:
case Token.BITOR:
case Token.BITAND:
case Token.BITXOR:
case Token.URSH:
case Token.RSH:
case Token.LSH:
case Token.MOD:
if ( n.getType() == Token.NE )
_append( " ! " , n );
_append( "JS_" , n );
String fooooo = _2ThingThings.get( n.getType() );
if ( fooooo == null )
throw new RuntimeException( "noting for : " + n );
_append( fooooo , n );
_append( "\n( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )\n " , n );
break;
case Token.IFNE:
_addIFNE( n , state );
break;
case Token.LOOP:
_addLoop( n , state );
break;
case Token.EMPTY:
if ( n.getFirstChild() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "not really empty" );
}
break;
case Token.LABEL:
_append( n.getString() + ":" , n );
break;
case Token.BREAK:
_append( "break " + n.getString() + ";\n" , n );
break;
case Token.CONTINUE:
- _append( "continue " + n.getString() + ";\n" , n );
+ _append( "if ( true ) continue " + n.getString() + ";\n" , n );
break;
case Token.WHILE:
_append( "while( false || JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ){ " , n );
_add( n.getFirstChild().getNext() , state );
_append( " }\n" , n );
break;
case Token.FOR:
_addFor( n , state );
break;
case Token.TARGET:
break;
case Token.NOT:
_assertOne( n );
_append( " JS_not( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.AND:
/*
_append( " ( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " && " , n );
_append( " JS_evalToBool( " , n );
_add( c , state );
_append( " ) " , n );
c = c.getNext();
}
_append( " ) " , n );
break;
*/
case Token.OR:
Node cc = n.getFirstChild();
if ( cc.getNext() == null )
throw new RuntimeException( "what?" );
if ( cc.getNext().getNext() != null )
throw new RuntimeException( "what?" );
String mod = n.getType() == Token.AND ? "and" : "or";
_append( "JSInternalFunctions.self( scope." + mod + "Save( " , n );
_add( cc , state );
_append( " ) ? scope.get" + mod + "Save() : ( " , n );
_add( cc.getNext() , state );
_append( " ) ) " , n );
break;
case Token.LOCAL_BLOCK:
_assertOne( n );
if ( n.getFirstChild().getType() != Token.TRY )
throw new RuntimeException("only know about LOCAL_BLOCK with try" );
_addTry( n.getFirstChild() , state );
break;
case Token.JSR:
case Token.RETURN_RESULT:
// these are handled in block
break;
case Token.THROW:
_append( "if ( true ) _throw( " , n );
_add( n.getFirstChild() , state );
_append( " ); " , n );
break;
case Token.INSTANCEOF:
_append( "JS_instanceof( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
if ( n.getFirstChild().getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
break;
case Token.DELPROP:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " ).removeField( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
break;
case Token.SWITCH:
_addSwitch( n , state );
break;
case Token.COMMA:
_append( "JS_comma( " , n );
boolean first = true;
Node inner = n.getFirstChild();
while ( inner != null ){
if ( first )
first = false;
else
_append( " , " , n );
_append( "\n ( " , n );
_add( inner , state );
_append( " )\n " , n );
inner = inner.getNext();
}
_append( " ) " , n );
break;
case Token.IN:
_append( "((JSObject)" , n );
_add( n.getFirstChild().getNext() , state );
_append( " ).containsKey( " , n );
_add( n.getFirstChild() , state );
_append( ".toString() ) " , n );
break;
case Token.NEG:
_append( "JS_mul( -1 , " , n );
_add( n.getFirstChild() , state );
_append( " )" , n );
break;
case Token.ENTERWITH:
_append( "scope.enterWith( (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " );" , n );
break;
case Token.LEAVEWITH:
_append( "scope.leaveWith();" , n );
break;
case Token.WITH:
_add( n.getFirstChild() , state );
break;
default:
Debug.printTree( n , 0 );
throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() );
}
}
private void _addSwitch( Node n , State state ){
_assertType( n , Token.SWITCH );
String ft = "ft" + (int)(Math.random() * 10000);
String val = "val" + (int)(Math.random() * 10000);
_append( "boolean " + ft + " = false;\n" , n );
_append( "do { \n " , n );
_append( " if ( false ) break; \n" , n );
Node caseArea = n.getFirstChild();
_append( "Object " + val + " = " , n );
_add( caseArea , state );
_append( " ; \n " , n );
n = n.getNext();
_assertType( n , Token.GOTO ); // this is default ?
n = n.getNext().getNext();
caseArea = caseArea.getNext();
while ( caseArea != null ){
_append( "if ( " + ft + " || JS_eq( " + val + " , " , caseArea );
_add( caseArea.getFirstChild() , state );
_append( " ) ){\n " + ft + " = true; \n " , caseArea );
_assertType( n , Token.BLOCK );
_add( n , state );
n = n.getNext().getNext();
_append( " } \n " , caseArea );
caseArea = caseArea.getNext();
}
if ( n != null && n.getType() == Token.BLOCK ){
_add( n , state );
}
_append(" } while ( false );" , n );
}
private void _createRef( Node n , State state ){
if ( n.getType() == Token.NAME || n.getType() == Token.GETVAR ){
if ( state.useLocalVariable( n.getString() ) )
throw new RuntimeException( "can't create a JSRef from a local variable : " + n.getString() );
_append( " new JSRef( scope , null , " , n );
_append( "\"" + n.getString() + "\"" , n );
_append( " ) " , n );
return;
}
if ( n.getType() == Token.GETPROP ||
n.getType() == Token.GETELEM ){
_append( " new JSRef( scope , (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
return;
}
throw new RuntimeException( "can't handle" );
}
private void _addTry( Node n , State state ){
_assertType( n , Token.TRY );
Node mainBlock = n.getFirstChild();
_assertType( mainBlock , Token.BLOCK );
_append( "try { \n " , n );
_add( mainBlock , state );
_append( " \n } \n " , n );
n = mainBlock.getNext();
final int num = (int)(Math.random() * 100000 );
final String javaEName = "javaEEE" + num;
final String javaName = "javaEEEO" + num;
while ( n != null ){
if ( n.getType() == Token.FINALLY ){
_assertType( n.getFirstChild() , Token.BLOCK );
_append( "finally { \n" , n );
_add( n.getFirstChild() , state );
_append( " \n } \n " , n );
n = n.getNext();
continue;
}
if ( n.getType() == Token.LOCAL_BLOCK &&
n.getFirstChild().getType() == Token.CATCH_SCOPE ){
_append( " \n catch ( Throwable " + javaEName + " ){ \n " , n );
_append( " \n Object " + javaName + " = ( " + javaEName + " instanceof JSException ) ? " +
" ((JSException)" + javaEName + ").getObject() : " + javaEName + " ; \n" , n );
_append( "try { scope.pushException( " + javaEName + " ); \n" , n );
Node catchScope = n.getFirstChild();
while ( catchScope != null ){
final Node c = catchScope;
if ( c.getType() != Token.CATCH_SCOPE )
break;
Node b = c.getNext();
_assertType( b , Token.BLOCK );
_assertType( b.getFirstChild() , Token.ENTERWITH );
_assertType( b.getFirstChild().getNext() , Token.WITH );
b = b.getFirstChild().getNext().getFirstChild();
_assertType( b , Token.BLOCK );
String jsName = c.getFirstChild().getString();
_append( " scope.put( \"" + jsName + "\" , " + javaName + " , true ); " , c );
b = b.getFirstChild();
boolean isIF = b.getType() == Token.IFNE;
if ( isIF ){
_append( "\n if ( " + javaEName + " != null && JS_evalToBool( " , b );
_add( b.getFirstChild() , state );
_append( " ) ){ \n " , b );
b = b.getNext().getFirstChild();
}
while ( b != null ){
if ( b.getType() == Token.LEAVEWITH )
break;
_add( b , state );
b = b.getNext();
}
_append( "if ( true ) " + javaEName + " = null ;\n" , b );
if ( isIF ){
_append( "\n } \n " , b );
}
catchScope = catchScope.getNext().getNext();
}
_append( "if ( " + javaEName + " != null ){ if ( " + javaEName + " instanceof RuntimeException ){ throw (RuntimeException)" + javaEName + ";} throw new JSException( " + javaEName + ");}\n" , n );
_append( " } finally { scope.popException(); } " , n );
_append( "\n } \n " , n ); // ends catch
n = n.getNext();
continue;
}
if ( n.getType() == Token.GOTO ||
n.getType() == Token.TARGET ||
n.getType() == Token.JSR ){
n = n.getNext();
continue;
}
if ( n.getType() == Token.RETHROW ){
//_append( "\nthrow " + javaEName + ";\n" , n );
n = n.getNext();
continue;
}
throw new RuntimeException( "what : " + Token.name( n.getType() ) );
}
}
private void _addFor( Node n , State state ){
_assertType( n , Token.FOR );
final int numChildren = countChildren( n );
if ( numChildren == 4 ){
_append( "\n for ( " , n );
if ( n.getFirstChild().getType() == Token.BLOCK ){
Node temp = n.getFirstChild().getFirstChild();
while ( temp != null ){
if ( temp.getType() == Token.EXPR_VOID )
_add( temp.getFirstChild() , state );
else
_add( temp , state );
temp = temp.getNext();
if ( temp != null )
_append( " , " , n );
}
_append( " ; " , n );
}
else {
_add( n.getFirstChild() , state );
_append( " ; " , n );
}
_append( " \n JS_evalToBool( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) ; \n" , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " )\n " , n );
_append( " { \n " , n );
_add( n.getFirstChild().getNext().getNext().getNext() , state );
_append( " } \n " , n );
}
else if ( numChildren == 3 ){
String name = n.getFirstChild().getString();
String tempName = name + "TEMP";
_append( "\n for ( String " , n );
_append( tempName , n );
_append( " : JSInternalFunctions.JS_collForFor( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) ){\n " , n );
if ( state.useLocalVariable( name ) && state.hasSymbol( name ) )
_append( name + " = new JSString( " + tempName + ") ; " , n );
else
_append( "scope.put( \"" + name + "\" , new JSString( " + tempName + " ) , true );\n" , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( "\n}\n" , n );
}
else {
throw new RuntimeException( "wtf?" );
}
}
private void _addLoop( Node n , State state ){
_assertType( n , Token.LOOP );
final Node theLoop = n;
n = n.getFirstChild();
Node nodes[] = null;
if ( ( nodes = _matches( n , _while1 ) ) != null ){
Node main = nodes[1];
Node predicate = nodes[5];
_append( "while ( JS_evalToBool( " , theLoop );
_add( predicate.getFirstChild() , state );
_append( " ) ) " , theLoop );
_add( main , state );
}
else if ( ( nodes = _matches( n , _doWhile1 ) ) != null ){
Node main = nodes[1];
Node predicate = nodes[3];
_assertType( predicate , Token.IFEQ );
_append( "do { \n " , theLoop );
_add( main , state );
_append( " } \n while ( false || JS_evalToBool( " , n );
_add( predicate.getFirstChild() , state );
_append( " ) );\n " , n );
}
else {
throw new RuntimeException( "what?" );
}
}
private void _addIFNE( Node n , State state ){
_assertType( n , Token.IFNE );
final Node.Jump theIf = (Node.Jump)n;
_assertOne( n ); // this is the predicate
Node ifBlock = n.getNext();
_append( "if ( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ){\n" , n );
_add( ifBlock , state );
_append( "}\n" , n );
n = n.getNext().getNext();
if ( n.getType() == Token.TARGET ){
if ( n.getNext() != null )
throw new RuntimeException( "something is wrong" );
return;
}
_assertType( n , Token.GOTO );
_assertType( n.getNext() , Token.TARGET );
if ( theIf.target.hashCode() != n.getNext().hashCode() )
throw new RuntimeException( "hashes don't match" );
n = n.getNext().getNext();
_append( " else if ( true ) { " , n );
_add( n , state );
_append( " } \n" , n );
_assertType( n.getNext() , Token.TARGET );
if ( n.getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
}
private void _addFunctionNodes( final ScriptOrFnNode sn , final State state ){
Set<Integer> baseIds = new HashSet<Integer>();
{
Node temp = sn.getFirstChild();
while ( temp != null ){
if ( temp.getType() == Token.FUNCTION &&
temp.getString() != null ){
int prop = temp.getIntProp( Node.FUNCTION_PROP , -1 );
if ( prop >= 0 ){
baseIds.add( prop );
}
}
temp = temp.getNext();
}
}
for ( int i=0; i<sn.getFunctionCount(); i++ ){
FunctionNode fn = sn.getFunctionNode( i );
_setLineNumbers( fn , fn );
String name = fn.getFunctionName();
String anonName = "tempFunc_" + _id + "_" + i + "_" + _methodId++;
boolean anon = name.length() == 0;
if ( anon )
name = anonName;
if ( D ){
System.out.println( "***************" );
System.out.println( i + " : " + name );
}
String useName = name;
if ( ! anon && ! baseIds.contains( i ) ){
useName = anonName;
state._nonRootFunctions.add( i );
}
state._functionIdToName.put( i , useName );
_setVar( useName , fn , state , anon );
_append( "; \n scope.getFunction( \"" + useName + "\" ).setName( \"" + name + "\" );\n\n" , fn );
}
}
private void _addFunction( Node n , State state ){
if ( ! ( n instanceof FunctionNode ) ){
if ( n.getString() != null && n.getString().length() != 0 ){
int id = n.getIntProp( Node.FUNCTION_PROP , -1 );
if ( state._nonRootFunctions.contains( id ) ){
_append( "scope.set( \"" + n.getString() + "\" , scope.get( \"" + state._functionIdToName.get( id ) + "\" ) );\n" , n );
}
return;
}
_append( getFunc( n , state ) , n );
return;
}
_assertOne( n );
FunctionNode fn = (FunctionNode)n;
FunctionInfo fi = FunctionInfo.create( fn );
state = state.child();
state._fi = fi;
boolean hasArguments = fi.usesArguemnts();
_append( "new JSFunctionCalls" + fn.getParamCount() + "( scope , null ){ \n" , n );
_append( "protected void init(){ super.init(); _sourceLanguage = getFileLanguage(); \n " , n );
_append( "_arguments = new JSArray();\n" , n );
for ( int i=0; i<fn.getParamCount(); i++ ){
final String foo = fn.getParamOrVarName( i );
_append( "_arguments.add( \"" + foo + "\" );\n" , n );
}
_append( "}\n" , n );
String callLine = "public Object call( final Scope passedIn ";
String varSetup = "";
for ( int i=0; i<fn.getParamCount(); i++ ){
final String foo = fn.getParamOrVarName( i );
callLine += " , ";
callLine += " Object " + foo;
if ( ! state.useLocalVariable( foo ) ){
callLine += "INNNNN";
varSetup += " \nscope.put(\"" + foo + "\"," + foo + "INNNNN , true );\n ";
if ( hasArguments )
varSetup += "arguments.add( " + foo + "INNNNN );\n";
}
else {
state.addSymbol( foo );
if ( hasArguments )
varSetup += "arguments.add( " + foo + " );\n";
}
callLine += " ";
}
callLine += " , Object ___extra[] ){\n" ;
_append( callLine + " final Scope scope = usePassedInScope() ? passedIn : new Scope( \"temp scope for: \" + _name , getScope() , passedIn , getFileLanguage() ); " , n );
if ( hasArguments ){
_append( "JSArray arguments = new JSArray();\n" , n );
_append( "scope.put( \"arguments\" , arguments , true );\n" , n );
}
for ( int i=0; i<fn.getParamCount(); i++ ){
final String foo = fn.getParamOrVarName( i );
final String javaName = foo + ( state.useLocalVariable( foo ) ? "" : "INNNNN" );
final Node defArg = fn.getDefault( foo );
if ( defArg == null )
continue;
_append( "if ( null == " + javaName + " ) " , defArg );
_append( javaName + " = " , defArg );
_add( defArg , state );
_append( ";\n" , defArg );
}
_append( varSetup , n );
if ( hasArguments ){
_append( "if ( ___extra != null ) for ( Object TTTT : ___extra ) arguments.add( TTTT );\n" , n );
_append( "{ Integer numArgs = _lastStart.get(); _lastStart.set( null ); while( numArgs != null && arguments.size() > numArgs && arguments.get( arguments.size() -1 ) == null ) arguments.remove( arguments.size() - 1 ); }" , n );
}
for ( int i=fn.getParamCount(); i<fn.getParamAndVarCount(); i++ ){
final String foo = fn.getParamOrVarName( i );
if ( state.useLocalVariable( foo ) ){
state.addSymbol( foo );
if ( state.isNumber( foo ) ){
_append( "double " + foo + " = 0;\n" , n );
}
else
_append( "Object " + foo + " = null;\n" , n );
}
else {
_append( "scope.put( \"" + foo + "\" , null , true );\n" , n );
}
}
_addFunctionNodes( fn , state );
_add( n.getFirstChild() , state );
_append( "}\n" , n );
int myStringId = _strings.size();
_strings.add( getSource( fn ) );
_append( "\t public String toString(){ return _strings[" + myStringId + "].toString(); }" , fn );
_append( "}\n" , n );
}
private void _addBlock( Node n , State state ){
_assertType( n , Token.BLOCK );
if ( n.getFirstChild() == null ){
_append( "{}" , n );
return;
}
// this is weird. look at bracing0.js
boolean bogusBrace = true;
Node c = n.getFirstChild();
while ( c != null ){
if ( c.getType() != Token.EXPR_VOID ){
bogusBrace = false;
break;
}
if ( c.getFirstChild().getNext() != null ){
bogusBrace = false;
break;
}
if ( c.getFirstChild().getType() != Token.SETVAR ){
bogusBrace = false;
break;
}
c = c.getNext();
}
bogusBrace = bogusBrace ||
( n.getFirstChild().getNext() == null &&
n.getFirstChild().getType() == Token.EXPR_VOID &&
n.getFirstChild().getFirstChild() == null );
if ( bogusBrace ){
c = n.getFirstChild();
while ( c != null ){
_add( c , state );
c = c.getNext();
}
return;
}
boolean endReturn =
n.getLastChild() != null &&
n.getLastChild().getType() == Token.RETURN_RESULT;
_append( "{" , n );
String ret = "retName" + (int)((Math.random()*1000));
if ( endReturn )
_append( "\n\nObject " + ret + " = null;\n\n" , n );
Node child = n.getFirstChild();
while ( child != null ){
if ( endReturn && child.getType() == Token.LEAVEWITH )
break;
if ( endReturn && child.getType() == Token.EXPR_RESULT )
_append( ret + " = " , child );
_add( child , state );
if ( child.getType() == Token.IFNE ||
child.getType() == Token.SWITCH )
break;
child = child.getNext();
}
if ( endReturn )
_append( "\n\nif ( true ){ return " + ret + "; }\n\n" , n );
_append( "}" , n );
}
private void _addSet( Node n , State state ){
_assertType( n , Token.SETNAME );
Node name = n.getFirstChild();
_setVar( name.getString() , name.getNext() , state );
}
private void _addVar( Node n , State state ){
_assertType( n , Token.VAR );
_assertOne( n );
Node name = n.getFirstChild();
_assertOne( name );
_setVar( name.getString() , name.getFirstChild() , state );
}
private void _addCall( Node n , State state ){
_addCall( n , state , false );
}
private void _addCall( Node n , State state , boolean isClass ){
Node name = n.getFirstChild();
boolean useThis = name.getType() == Token.GETPROP && ! isClass;
if ( useThis )
_append( "scope.clearThisNormal( " , n );
Boolean inc[] = new Boolean[]{ true };
String f = getFunc( name , state , isClass , inc );
_append( ( inc[0] ? f : "" ) + ".call( scope" + ( isClass ? ".newThis( " + f + " )" : "" ) + " " , n );
Node param = name.getNext();
while ( param != null ){
_append( " , " , param );
_add( param , state );
param = param.getNext();
}
_append( " , new Object[0] ) " , n );
if ( useThis )
_append( " ) " , n );
}
private void _setVar( String name , Node val , State state ){
_setVar( name , val , state , false );
}
private void _setVar( String name , Node val , State state , boolean local ){
if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ){
boolean prim = state.isPrimitive( name );
if ( ! prim )
_append( "JSInternalFunctions.self( " , val );
_append( name + " = " , val );
_add( val , state );
_append( "\n" , val );
if ( ! prim )
_append( ")\n" , val );
return;
}
_append( "scope.put( \"" + name + "\" , " , val);
_add( val , state );
_append( " , " + local + " ) " , val );
}
private int countChildren( Node n ){
int num = 0;
Node c = n.getFirstChild();
while ( c != null ){
num++;
c = c.getNext();
}
return num;
}
public static void _assertOne( Node n ){
if ( n.getFirstChild() == null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "no child" );
}
if ( n.getFirstChild().getNext() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "more than 1 child" );
}
}
public void _assertType( Node n , int type ){
_assertType( n , type , this );
}
public static void _assertType( Node n , int type , Convert c ){
if ( type == n.getType() )
return;
String msg = "wrong type. was : " + Token.name( n.getType() ) + " should be " + Token.name( type );
if ( c != null )
msg += " file : " + c._name + " : " + ( c._nodeToSourceLine.get( n ) + 1 );
throw new RuntimeException( msg );
}
private void _setLineNumbers( final Node startN , final ScriptOrFnNode startSOF ){
final Set<Integer> seen = new HashSet<Integer>();
final List<Pair<Node,ScriptOrFnNode>> overallTODO = new LinkedList<Pair<Node,ScriptOrFnNode>>();
overallTODO.add( new Pair<Node,ScriptOrFnNode>( startN , startSOF ) );
while ( overallTODO.size() > 0 ){
final Pair<Node,ScriptOrFnNode> temp = overallTODO.remove( 0 );
Node n = temp.first;
final ScriptOrFnNode sof = temp.second;
final int line = n.getLineno();
if ( line < 0 )
throw new RuntimeException( "something is wrong" );
List<Node> todo = new LinkedList<Node>();
_nodeToSourceLine.put( n , line );
_nodeToSOR.put( n , sof );
if ( n.getFirstChild() != null )
todo.add( n.getFirstChild() );
if ( n.getNext() != null )
todo.add( n.getNext() );
while ( todo.size() > 0 ){
n = todo.remove(0);
if ( seen.contains( n.hashCode() ) )
continue;
seen.add( n.hashCode() );
if ( n.getLineno() > 0 ){
overallTODO.add( new Pair<Node,ScriptOrFnNode>( n , n instanceof ScriptOrFnNode ? (ScriptOrFnNode)n : sof ) );
continue;
}
_nodeToSourceLine.put( n , line );
_nodeToSOR.put( n , sof );
if ( n.getFirstChild() != null )
todo.add( n.getFirstChild() );
if ( n.getNext() != null )
todo.add( n.getNext() );
}
}
}
private void _append( String s , Node n ){
_mainJavaCode.append( s );
if ( n == null )
return;
int numLines = 0;
int max = s.length();
for ( int i=0; i<max; i++ )
if ( s.charAt( i ) == '\n' )
numLines++;
final int start = _currentLineNumber;
int end = _currentLineNumber + numLines;
for ( int i=start; i<end; i++ ){
List<Node> l = _javaCodeToLines.get( i );
if ( l == null ){
l = new ArrayList<Node>();
_javaCodeToLines.put( i , l );
}
l.add( n );
}
_currentLineNumber = end;
}
private String getFunc( Node n , State state ){
return getFunc( n , state , false , null );
}
private String getFunc( Node n , State state , boolean isClass , Boolean inc[] ){
if ( n.getClass().getName().indexOf( "StringNode" ) < 0 ){
if ( n.getType() == Token.GETPROP && ! isClass ){
_append( "scope.getFunctionAndSetThis( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( ".toString() ) " , n );
return "";
}
int start = _mainJavaCode.length();
_append( "((JSFunction )" , n);
_add( n , state );
_append( ")" , n );
int end = _mainJavaCode.length();
if( isClass ){
if ( inc == null )
throw new RuntimeException( "inc is null and can't be here" );
inc[0] = false;
return "(" + _mainJavaCode.substring( start , end ) + ")";
}
return "";
}
String name = n.getString();
if ( name == null || name.length() == 0 ){
int id = n.getIntProp( Node.FUNCTION_PROP , -1 );
if ( id == -1 )
throw new RuntimeException( "no name or id for this thing" );
name = state._functionIdToName.get( id );
if ( name == null || name.length() == 0 )
throw new RuntimeException( "no name for this id " );
}
if ( state.hasSymbol( name ) )
return "(( JSFunction)" + name + ")";
return "scope.getFunction( \"" + name + "\" )";
}
public String getClassName(){
return _className;
}
public String getClassString(){
StringBuilder buf = new StringBuilder();
buf.append( "package " + _package + ";\n" );
buf.append( "import ed.js.*;\n" );
buf.append( "import ed.js.func.*;\n" );
buf.append( "import ed.js.engine.Scope;\n" );
buf.append( "import ed.js.engine.JSCompiledScript;\n" );
buf.append( "public class " ).append( _className ).append( " extends JSCompiledScript {\n" );
buf.append( "\tpublic Object _call( Scope scope , Object extra[] ) throws Throwable {\n" );
buf.append( "\t\t final Scope passedIn = scope; \n" );
if (_invokedFromEval) {
buf.append("\t\t // not creating new scope for execution as we're being run in the context of an eval\n");
}
else {
buf.append( "\t\t scope = new Scope( \"compiled script for:" + _name.replaceAll( "/tmp/jxp/s?/?0\\.\\d+/" , "" ) + "\" , scope , null , getFileLanguage() ); \n" );
buf.append( "\t\t scope.putAll( getTLScope() );\n" );
}
buf.append( "\t\t JSArray arguments = new JSArray(); scope.put( \"arguments\" , arguments , true );\n " );
buf.append( "\t\t if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" );
_preMainLines = StringUtil.count( buf.toString() , "\n" );
buf.append( _mainJavaCode );
buf.append( "\n\n\t}\n\n" );
buf.append( "\n}\n\n" );
return buf.toString();
}
public JSFunction get(){
if ( _it != null )
return _it;
try {
Class c = CompileUtil.compile( _package , getClassName() , getClassString() , this );
JSCompiledScript it = (JSCompiledScript)c.newInstance();
it._convert = this;
it._regex = new JSRegex[ _regex.size() ];
for ( int i=0; i<_regex.size(); i++ ){
Pair<String,String> p = _regex.get( i );
JSRegex foo = new JSRegex( p.first , p.second );
it._regex[i] = foo;
}
it._strings = new JSString[ _strings.size() ];
for ( int i=0; i<_strings.size(); i++ )
it._strings[i] = new JSString( _strings.get( i ) );
it.setName( _name );
_it = it;
StackTraceHolder.getInstance().set( _fullClassName , this );
StackTraceHolder.getInstance().setPackage( "ed.js" , this );
StackTraceHolder.getInstance().setPackage( "ed.js.func" , this );
StackTraceHolder.getInstance().setPackage( "ed.js.engine" , this );
return _it;
}
catch ( RuntimeException re ){
re.printStackTrace();
fixStack( re );
throw re;
}
catch ( Exception e ){
e.printStackTrace();
fixStack( e );
throw new RuntimeException( e );
}
}
public void fixStack( Throwable e ){
StackTraceHolder.getInstance().fix( e );
}
Node _getNodeFromJavaLine( int line ){
line = ( line - _preMainLines ) - 1;
List<Node> nodes = _javaCodeToLines.get( line );
if ( nodes == null || nodes.size() == 0 ){
return null;
}
return nodes.get(0);
}
public int _mapLineNumber( int line ){
Node n = _getNodeFromJavaLine( line );
if ( n == null )
return -1;
Integer i = _nodeToSourceLine.get( n );
if ( i == null )
return -1;
return i + 1;
}
public void _debugLineNumber( final int line ){
System.out.println( "-----" );
for ( int temp = Math.max( 0 , line - 5 );
temp < line + 5 ;
temp++ )
System.out.println( "\t" + temp + "->" + _mapLineNumber( temp ) + " || " + _getNodeFromJavaLine( temp ) );
System.out.println( "-----" );
}
public StackTraceElement fixSTElement( StackTraceElement element ){
return fixSTElement( element , false );
}
public StackTraceElement fixSTElement( StackTraceElement element , boolean debug ){
if ( ! element.getClassName().startsWith( _fullClassName ) )
return null;
if ( debug ){
System.out.println( element );
_debugLineNumber( element.getLineNumber() );
}
Node n = _getNodeFromJavaLine( element.getLineNumber() );
if ( n == null )
return null;
// the +1 is for the way rhino does stuff
int line = _mapLineNumber( element.getLineNumber() );
ScriptOrFnNode sof = _nodeToSOR.get( n );
String method = "___";
if ( sof instanceof FunctionNode )
method = ((FunctionNode)sof).getFunctionName();
return new StackTraceElement( _name , method , _name , line );
}
public boolean removeSTElement( StackTraceElement element ){
String s = element.toString();
return
s.contains( ".call(JSFunctionCalls" ) ||
s.contains( "ed.js.JSFunctionBase.call(" ) ||
s.contains( "ed.js.engine.JSCompiledScript.call" );
}
String getSource( FunctionNode fn ){
final int start = fn.getEncodedSourceStart();
final int end = fn.getEncodedSourceEnd();
final String encoded = _encodedSource.substring( start , end );
final String realSource = Decompiler.decompile( encoded , 0 , new UintMap() );
return realSource;
}
private String getStringCode( String s ){
int stringId = _strings.size();
_strings.add( s );
return "_strings[" + stringId + "]";
}
public boolean hasReturn(){
return _hasReturn;
}
public int findStringId( String s ){
for ( int i=0; i<_strings.size(); i++ ){
if ( _strings.get(i).equals( s ) ){
return i;
}
}
return -1;
}
//final File _file;
final String _name;
final String _source;
final String _encodedSource;
final String _className;
final String _fullClassName;
final String _package = DEFAULT_PACKAGE;
final boolean _invokedFromEval;
final Language _sourceLanguage;
final int _id = ID++;
// these 3 variables should only be use by _append
private int _currentLineNumber = 0;
final Map<Integer,List<Node>> _javaCodeToLines = new TreeMap<Integer,List<Node>>();
final Map<Node,Integer> _nodeToSourceLine = new HashMap<Node,Integer>();
final Map<Node,ScriptOrFnNode> _nodeToSOR = new HashMap<Node,ScriptOrFnNode>();
final List<Pair<String,String>> _regex = new ArrayList<Pair<String,String>>();
final List<String> _strings = new ArrayList<String>();
int _preMainLines = -1;
private final StringBuilder _mainJavaCode = new StringBuilder();
private boolean _hasReturn = false;
private JSFunction _it;
private int _methodId = 0;
private static int ID = 1;
private final static Map<Integer,String> _2ThingThings = new HashMap<Integer,String>();
static {
_2ThingThings.put( Token.ADD , "add" );
_2ThingThings.put( Token.MUL , "mul" );
_2ThingThings.put( Token.SUB , "sub" );
_2ThingThings.put( Token.DIV , "div" );
_2ThingThings.put( Token.SHEQ , "sheq" );
_2ThingThings.put( Token.SHNE , "shne" );
_2ThingThings.put( Token.EQ , "eq" );
_2ThingThings.put( Token.NE , "eq" );
_2ThingThings.put( Token.GE , "ge" );
_2ThingThings.put( Token.LE , "le" );
_2ThingThings.put( Token.LT , "lt" );
_2ThingThings.put( Token.GT , "gt" );
_2ThingThings.put( Token.BITOR , "bitor" );
_2ThingThings.put( Token.BITAND , "bitand" );
_2ThingThings.put( Token.BITXOR , "bitxor" );
_2ThingThings.put( Token.URSH , "ursh" );
_2ThingThings.put( Token.RSH , "rsh" );
_2ThingThings.put( Token.LSH , "lsh" );
_2ThingThings.put( Token.MOD , "mod" );
}
private static final int _while1[] = new int[]{ Token.GOTO , Token.TARGET , 0 , 0 , Token.TARGET , Token.IFEQ , Token.TARGET };
private static final int _doWhile1[] = new int[]{ Token.TARGET , 0 , Token.TARGET , Token.IFEQ , Token.TARGET };
private static Node[] _matches( Node n , int types[] ){
Node foo[] = new Node[types.length];
for ( int i=0; i<types.length; i++ ){
foo[i] = n;
if ( types[i] > 0 && n.getType() != types[i] )
return null;
n = n.getNext();
}
return n == null ? foo : null;
}
// this is class compile optimization below
static synchronized int _getNumForClass( String name , String source ){
ClassInfo ci = _classes.get( name );
if ( ci == null ){
ci = new ClassInfo();
_classes.put( name , ci );
}
return ci.getNum( source );
}
private static Map<String,ClassInfo> _classes = Collections.synchronizedMap( new HashMap<String,ClassInfo>() );
static class ClassInfo {
synchronized int getNum( String source ){
_myMd5.Init();
_myMd5.Update( source );
final String hash = _myMd5.asHex();
Integer num = _sourceToNumber.get( hash );
if ( num != null )
return num;
num = ++_numSoFar;
_sourceToNumber.put( hash , num );
return num;
}
final MD5 _myMd5 = new MD5();
final Map<String,Integer> _sourceToNumber = new TreeMap<String,Integer>();
int _numSoFar = 0;
}
}
| true | true | private void _add( Node n , ScriptOrFnNode sn , State state ){
switch ( n.getType() ){
case Token.TYPEOF:
_append( "JS_typeof( " , n );
_assertOne( n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.TYPEOFNAME:
_append( "JS_typeof( " , n );
if ( state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
_append( " ) " , n );
break;
case Token.REGEXP:
int myId = _regex.size();
ScriptOrFnNode parent = _nodeToSOR.get( n );
int rId = n.getIntProp( Node.REGEXP_PROP , -1 );
_regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) );
_append( " _regex[" + myId + "] " , n );
break;
case Token.ARRAYLIT:
{
_append( "( JSArray.create( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) ) " , n );
}
break;
case Token.OBJECTLIT:
{
_append( "JS_buildLiteralObject( new String[]{ " , n );
boolean first = true;
Node c = n.getFirstChild();
for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){
if ( first )
first = false;
else
_append( " , " , n );
String name = id.toString();
if ( c.getType() == Token.GET )
name = JSObjectBase.getterName( name );
else if ( c.getType() == Token.SET )
name = JSObjectBase.setterName( name );
_append( getStringCode( name ) + ".toString()" , n );
c = c.getNext();
}
_append( " } " , n );
c = n.getFirstChild();
while ( c != null ){
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) " , n );
}
break;
case Token.NEW:
_append( "scope.clearThisNew( " , n );
_addCall( n , state , true );
_append( " ) " , n );
break;
case Token.THIS:
_append( "passedIn.getThis()" , n );
break;
case Token.INC:
case Token.DEC:
_assertOne( n );
Node tempChild = n.getFirstChild();
if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){
if ( ! state.isNumber( tempChild.getString() ) )
throw new RuntimeException( "can't increment local variable : " + tempChild.getString() );
_append( tempChild.getString() + "++ " , n );
}
else {
_append( "JS_inc( " , n );
_createRef( n.getFirstChild() , state );
_append( " , " , n );
_append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n );
_append( " , " , n );
_append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n );
_append( ")" , n );
}
break;
case Token.USE_STACK:
_append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n );
break;
case Token.SETPROP_OP:
case Token.SETELEM_OP:
Node theOp = n.getFirstChild().getNext().getNext();
if ( theOp.getType() == Token.ADD &&
( theOp.getFirstChild().getType() == Token.USE_STACK ||
theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){
_append( "\n" , n );
_append( "JS_setDefferedPlus( (JSObject) " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( theOp.getFirstChild().getType() == Token.USE_STACK ?
theOp.getFirstChild().getNext() :
theOp.getFirstChild() ,
state );
_append( " \n ) \n" , n );
break;
}
_append( "\n { \n" , n );
_append( "JSObject __tempObject = (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
String tempName = "__temp" + (int)(Math.random() * 10000);
state._tempOpNames.push( tempName );
_append( "Object " + tempName + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( ";\n" , n );
_append( " __tempObject.set(" , n );
_append( tempName , n );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); \n" , n );
_append( " } \n" , n );
break;
case Token.SETPROP:
case Token.SETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").set( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) " , n );
break;
case Token.GETPROPNOWARN:
case Token.GETPROP:
case Token.GETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").get( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.SET_REF:
_assertType( n.getFirstChild() , Token.REF_SPECIAL );
_append( "((JSObject)" , n );
_add( n.getFirstChild().getFirstChild() , state );
_append( ").set( \"" , n );
_append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n );
_append( "\" , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.GET_REF:
_assertType( n.getFirstChild() , Token.REF_SPECIAL );
_append( "((JSObject)" , n );
_add( n.getFirstChild().getFirstChild() , state );
_append( ").get( \"" , n );
_append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n );
_append( "\" )" , n );
break;
case Token.EXPR_RESULT:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.CALL:
_addCall( n , state );
break;
case Token.NUMBER:
double d = n.getDouble();
String temp = String.valueOf( d );
if ( temp.endsWith( ".0" ) ||
JSNumericFunctions.couldBeInt( d ) )
temp = String.valueOf( (int)d );
_append( "JSNumber.self( " + temp + ")" , n );
break;
case Token.STRING:
final String theString = n.getString();
_append( getStringCode( theString ) , n );
break;
case Token.TRUE:
_append( " true " , n );
break;
case Token.FALSE:
_append( " false " , n );
break;
case Token.NULL:
_append( " null " , n );
break;
case Token.VAR:
_addVar( n , state );
break;
case Token.GETVAR:
if ( state.useLocalVariable( n.getString() ) ){
_append( n.getString() , n );
break;
}
case Token.NAME:
if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
break;
case Token.SETVAR:
final String foo = n.getFirstChild().getString();
if ( state.useLocalVariable( foo ) ){
if ( ! state.hasSymbol( foo ) )
throw new RuntimeException( "something is wrong" );
if ( ! state.isPrimitive( foo ) )
_append( "JSInternalFunctions.self ( " , n );
_append( foo + " = " , n );
_add( n.getFirstChild().getNext() , state );
if ( ! state.isPrimitive( foo ) )
_append( " )\n" , n );
}
else {
_setVar( foo ,
n.getFirstChild().getNext() ,
state , true );
}
break;
case Token.SETNAME:
_addSet( n , state );
break;
case Token.GET:
_addFunction( n.getFirstChild() , state );
break;
case Token.SET:
_addFunction( n.getFirstChild() , state );
break;
case Token.FUNCTION:
_addFunction( n , state );
break;
case Token.BLOCK:
_addBlock( n , state );
break;
case Token.EXPR_VOID:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.RETURN:
boolean last = n.getNext() == null;
if ( ! last )
_append( "if ( true ) { " , n );
_append( "return " , n );
if ( n.getFirstChild() != null ){
_assertOne( n );
_add( n.getFirstChild() , state );
}
else {
_append( " null " , n );
}
_append( ";" , n );
if ( ! last )
_append( "}" , n );
_append( "\n" , n );
break;
case Token.BITNOT:
_assertOne( n );
_append( "JS_bitnot( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.HOOK:
_append( " JSInternalFunctions.self( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ? ( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) : ( " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) ) " , n );
break;
case Token.POS:
_assertOne( n );
_add( n.getFirstChild() , state );
break;
case Token.ADD:
if ( state.isNumberAndLocal( n.getFirstChild() ) &&
state.isNumberAndLocal( n.getFirstChild().getNext() ) ){
_append( "(" , n );
_add( n.getFirstChild() , state );
_append( " + " , n );
_add( n.getFirstChild().getNext() , state );
_append( ")" , n );
break;
}
case Token.NE:
case Token.MUL:
case Token.DIV:
case Token.SUB:
case Token.EQ:
case Token.SHEQ:
case Token.SHNE:
case Token.GE:
case Token.LE:
case Token.LT:
case Token.GT:
case Token.BITOR:
case Token.BITAND:
case Token.BITXOR:
case Token.URSH:
case Token.RSH:
case Token.LSH:
case Token.MOD:
if ( n.getType() == Token.NE )
_append( " ! " , n );
_append( "JS_" , n );
String fooooo = _2ThingThings.get( n.getType() );
if ( fooooo == null )
throw new RuntimeException( "noting for : " + n );
_append( fooooo , n );
_append( "\n( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )\n " , n );
break;
case Token.IFNE:
_addIFNE( n , state );
break;
case Token.LOOP:
_addLoop( n , state );
break;
case Token.EMPTY:
if ( n.getFirstChild() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "not really empty" );
}
break;
case Token.LABEL:
_append( n.getString() + ":" , n );
break;
case Token.BREAK:
_append( "break " + n.getString() + ";\n" , n );
break;
case Token.CONTINUE:
_append( "continue " + n.getString() + ";\n" , n );
break;
case Token.WHILE:
_append( "while( false || JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ){ " , n );
_add( n.getFirstChild().getNext() , state );
_append( " }\n" , n );
break;
case Token.FOR:
_addFor( n , state );
break;
case Token.TARGET:
break;
case Token.NOT:
_assertOne( n );
_append( " JS_not( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.AND:
/*
_append( " ( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " && " , n );
_append( " JS_evalToBool( " , n );
_add( c , state );
_append( " ) " , n );
c = c.getNext();
}
_append( " ) " , n );
break;
*/
case Token.OR:
Node cc = n.getFirstChild();
if ( cc.getNext() == null )
throw new RuntimeException( "what?" );
if ( cc.getNext().getNext() != null )
throw new RuntimeException( "what?" );
String mod = n.getType() == Token.AND ? "and" : "or";
_append( "JSInternalFunctions.self( scope." + mod + "Save( " , n );
_add( cc , state );
_append( " ) ? scope.get" + mod + "Save() : ( " , n );
_add( cc.getNext() , state );
_append( " ) ) " , n );
break;
case Token.LOCAL_BLOCK:
_assertOne( n );
if ( n.getFirstChild().getType() != Token.TRY )
throw new RuntimeException("only know about LOCAL_BLOCK with try" );
_addTry( n.getFirstChild() , state );
break;
case Token.JSR:
case Token.RETURN_RESULT:
// these are handled in block
break;
case Token.THROW:
_append( "if ( true ) _throw( " , n );
_add( n.getFirstChild() , state );
_append( " ); " , n );
break;
case Token.INSTANCEOF:
_append( "JS_instanceof( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
if ( n.getFirstChild().getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
break;
case Token.DELPROP:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " ).removeField( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
break;
case Token.SWITCH:
_addSwitch( n , state );
break;
case Token.COMMA:
_append( "JS_comma( " , n );
boolean first = true;
Node inner = n.getFirstChild();
while ( inner != null ){
if ( first )
first = false;
else
_append( " , " , n );
_append( "\n ( " , n );
_add( inner , state );
_append( " )\n " , n );
inner = inner.getNext();
}
_append( " ) " , n );
break;
case Token.IN:
_append( "((JSObject)" , n );
_add( n.getFirstChild().getNext() , state );
_append( " ).containsKey( " , n );
_add( n.getFirstChild() , state );
_append( ".toString() ) " , n );
break;
case Token.NEG:
_append( "JS_mul( -1 , " , n );
_add( n.getFirstChild() , state );
_append( " )" , n );
break;
case Token.ENTERWITH:
_append( "scope.enterWith( (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " );" , n );
break;
case Token.LEAVEWITH:
_append( "scope.leaveWith();" , n );
break;
case Token.WITH:
_add( n.getFirstChild() , state );
break;
default:
Debug.printTree( n , 0 );
throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() );
}
}
| private void _add( Node n , ScriptOrFnNode sn , State state ){
switch ( n.getType() ){
case Token.TYPEOF:
_append( "JS_typeof( " , n );
_assertOne( n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.TYPEOFNAME:
_append( "JS_typeof( " , n );
if ( state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
_append( " ) " , n );
break;
case Token.REGEXP:
int myId = _regex.size();
ScriptOrFnNode parent = _nodeToSOR.get( n );
int rId = n.getIntProp( Node.REGEXP_PROP , -1 );
_regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) );
_append( " _regex[" + myId + "] " , n );
break;
case Token.ARRAYLIT:
{
_append( "( JSArray.create( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) ) " , n );
}
break;
case Token.OBJECTLIT:
{
_append( "JS_buildLiteralObject( new String[]{ " , n );
boolean first = true;
Node c = n.getFirstChild();
for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){
if ( first )
first = false;
else
_append( " , " , n );
String name = id.toString();
if ( c.getType() == Token.GET )
name = JSObjectBase.getterName( name );
else if ( c.getType() == Token.SET )
name = JSObjectBase.setterName( name );
_append( getStringCode( name ) + ".toString()" , n );
c = c.getNext();
}
_append( " } " , n );
c = n.getFirstChild();
while ( c != null ){
_append( " , " , n );
_add( c , state );
c = c.getNext();
}
_append( " ) " , n );
}
break;
case Token.NEW:
_append( "scope.clearThisNew( " , n );
_addCall( n , state , true );
_append( " ) " , n );
break;
case Token.THIS:
_append( "passedIn.getThis()" , n );
break;
case Token.INC:
case Token.DEC:
_assertOne( n );
Node tempChild = n.getFirstChild();
if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){
if ( ! state.isNumber( tempChild.getString() ) )
throw new RuntimeException( "can't increment local variable : " + tempChild.getString() );
_append( tempChild.getString() + "++ " , n );
}
else {
_append( "JS_inc( " , n );
_createRef( n.getFirstChild() , state );
_append( " , " , n );
_append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n );
_append( " , " , n );
_append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n );
_append( ")" , n );
}
break;
case Token.USE_STACK:
_append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n );
break;
case Token.SETPROP_OP:
case Token.SETELEM_OP:
Node theOp = n.getFirstChild().getNext().getNext();
if ( theOp.getType() == Token.ADD &&
( theOp.getFirstChild().getType() == Token.USE_STACK ||
theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){
_append( "\n" , n );
_append( "JS_setDefferedPlus( (JSObject) " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( theOp.getFirstChild().getType() == Token.USE_STACK ?
theOp.getFirstChild().getNext() :
theOp.getFirstChild() ,
state );
_append( " \n ) \n" , n );
break;
}
_append( "\n { \n" , n );
_append( "JSObject __tempObject = (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
String tempName = "__temp" + (int)(Math.random() * 10000);
state._tempOpNames.push( tempName );
_append( "Object " + tempName + " = " , n );
_add( n.getFirstChild().getNext() , state );
_append( ";\n" , n );
_append( " __tempObject.set(" , n );
_append( tempName , n );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ); \n" , n );
_append( " } \n" , n );
break;
case Token.SETPROP:
case Token.SETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").set( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) " , n );
break;
case Token.GETPROPNOWARN:
case Token.GETPROP:
case Token.GETELEM:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( ").get( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.SET_REF:
_assertType( n.getFirstChild() , Token.REF_SPECIAL );
_append( "((JSObject)" , n );
_add( n.getFirstChild().getFirstChild() , state );
_append( ").set( \"" , n );
_append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n );
_append( "\" , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )" , n );
break;
case Token.GET_REF:
_assertType( n.getFirstChild() , Token.REF_SPECIAL );
_append( "((JSObject)" , n );
_add( n.getFirstChild().getFirstChild() , state );
_append( ").get( \"" , n );
_append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n );
_append( "\" )" , n );
break;
case Token.EXPR_RESULT:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.CALL:
_addCall( n , state );
break;
case Token.NUMBER:
double d = n.getDouble();
String temp = String.valueOf( d );
if ( temp.endsWith( ".0" ) ||
JSNumericFunctions.couldBeInt( d ) )
temp = String.valueOf( (int)d );
_append( "JSNumber.self( " + temp + ")" , n );
break;
case Token.STRING:
final String theString = n.getString();
_append( getStringCode( theString ) , n );
break;
case Token.TRUE:
_append( " true " , n );
break;
case Token.FALSE:
_append( " false " , n );
break;
case Token.NULL:
_append( " null " , n );
break;
case Token.VAR:
_addVar( n , state );
break;
case Token.GETVAR:
if ( state.useLocalVariable( n.getString() ) ){
_append( n.getString() , n );
break;
}
case Token.NAME:
if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) )
_append( n.getString() , n );
else
_append( "scope.get( \"" + n.getString() + "\" )" , n );
break;
case Token.SETVAR:
final String foo = n.getFirstChild().getString();
if ( state.useLocalVariable( foo ) ){
if ( ! state.hasSymbol( foo ) )
throw new RuntimeException( "something is wrong" );
if ( ! state.isPrimitive( foo ) )
_append( "JSInternalFunctions.self ( " , n );
_append( foo + " = " , n );
_add( n.getFirstChild().getNext() , state );
if ( ! state.isPrimitive( foo ) )
_append( " )\n" , n );
}
else {
_setVar( foo ,
n.getFirstChild().getNext() ,
state , true );
}
break;
case Token.SETNAME:
_addSet( n , state );
break;
case Token.GET:
_addFunction( n.getFirstChild() , state );
break;
case Token.SET:
_addFunction( n.getFirstChild() , state );
break;
case Token.FUNCTION:
_addFunction( n , state );
break;
case Token.BLOCK:
_addBlock( n , state );
break;
case Token.EXPR_VOID:
_assertOne( n );
_add( n.getFirstChild() , state );
_append( ";\n" , n );
break;
case Token.RETURN:
boolean last = n.getNext() == null;
if ( ! last )
_append( "if ( true ) { " , n );
_append( "return " , n );
if ( n.getFirstChild() != null ){
_assertOne( n );
_add( n.getFirstChild() , state );
}
else {
_append( " null " , n );
}
_append( ";" , n );
if ( ! last )
_append( "}" , n );
_append( "\n" , n );
break;
case Token.BITNOT:
_assertOne( n );
_append( "JS_bitnot( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.HOOK:
_append( " JSInternalFunctions.self( JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ? ( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) : ( " , n );
_add( n.getFirstChild().getNext().getNext() , state );
_append( " ) ) " , n );
break;
case Token.POS:
_assertOne( n );
_add( n.getFirstChild() , state );
break;
case Token.ADD:
if ( state.isNumberAndLocal( n.getFirstChild() ) &&
state.isNumberAndLocal( n.getFirstChild().getNext() ) ){
_append( "(" , n );
_add( n.getFirstChild() , state );
_append( " + " , n );
_add( n.getFirstChild().getNext() , state );
_append( ")" , n );
break;
}
case Token.NE:
case Token.MUL:
case Token.DIV:
case Token.SUB:
case Token.EQ:
case Token.SHEQ:
case Token.SHNE:
case Token.GE:
case Token.LE:
case Token.LT:
case Token.GT:
case Token.BITOR:
case Token.BITAND:
case Token.BITXOR:
case Token.URSH:
case Token.RSH:
case Token.LSH:
case Token.MOD:
if ( n.getType() == Token.NE )
_append( " ! " , n );
_append( "JS_" , n );
String fooooo = _2ThingThings.get( n.getType() );
if ( fooooo == null )
throw new RuntimeException( "noting for : " + n );
_append( fooooo , n );
_append( "\n( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " )\n " , n );
break;
case Token.IFNE:
_addIFNE( n , state );
break;
case Token.LOOP:
_addLoop( n , state );
break;
case Token.EMPTY:
if ( n.getFirstChild() != null ){
Debug.printTree( n , 0 );
throw new RuntimeException( "not really empty" );
}
break;
case Token.LABEL:
_append( n.getString() + ":" , n );
break;
case Token.BREAK:
_append( "break " + n.getString() + ";\n" , n );
break;
case Token.CONTINUE:
_append( "if ( true ) continue " + n.getString() + ";\n" , n );
break;
case Token.WHILE:
_append( "while( false || JS_evalToBool( " , n );
_add( n.getFirstChild() , state );
_append( " ) ){ " , n );
_add( n.getFirstChild().getNext() , state );
_append( " }\n" , n );
break;
case Token.FOR:
_addFor( n , state );
break;
case Token.TARGET:
break;
case Token.NOT:
_assertOne( n );
_append( " JS_not( " , n );
_add( n.getFirstChild() , state );
_append( " ) " , n );
break;
case Token.AND:
/*
_append( " ( " , n );
Node c = n.getFirstChild();
while ( c != null ){
if ( c != n.getFirstChild() )
_append( " && " , n );
_append( " JS_evalToBool( " , n );
_add( c , state );
_append( " ) " , n );
c = c.getNext();
}
_append( " ) " , n );
break;
*/
case Token.OR:
Node cc = n.getFirstChild();
if ( cc.getNext() == null )
throw new RuntimeException( "what?" );
if ( cc.getNext().getNext() != null )
throw new RuntimeException( "what?" );
String mod = n.getType() == Token.AND ? "and" : "or";
_append( "JSInternalFunctions.self( scope." + mod + "Save( " , n );
_add( cc , state );
_append( " ) ? scope.get" + mod + "Save() : ( " , n );
_add( cc.getNext() , state );
_append( " ) ) " , n );
break;
case Token.LOCAL_BLOCK:
_assertOne( n );
if ( n.getFirstChild().getType() != Token.TRY )
throw new RuntimeException("only know about LOCAL_BLOCK with try" );
_addTry( n.getFirstChild() , state );
break;
case Token.JSR:
case Token.RETURN_RESULT:
// these are handled in block
break;
case Token.THROW:
_append( "if ( true ) _throw( " , n );
_add( n.getFirstChild() , state );
_append( " ); " , n );
break;
case Token.INSTANCEOF:
_append( "JS_instanceof( " , n );
_add( n.getFirstChild() , state );
_append( " , " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
if ( n.getFirstChild().getNext().getNext() != null )
throw new RuntimeException( "something is wrong" );
break;
case Token.DELPROP:
_append( "((JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " ).removeField( " , n );
_add( n.getFirstChild().getNext() , state );
_append( " ) " , n );
break;
case Token.SWITCH:
_addSwitch( n , state );
break;
case Token.COMMA:
_append( "JS_comma( " , n );
boolean first = true;
Node inner = n.getFirstChild();
while ( inner != null ){
if ( first )
first = false;
else
_append( " , " , n );
_append( "\n ( " , n );
_add( inner , state );
_append( " )\n " , n );
inner = inner.getNext();
}
_append( " ) " , n );
break;
case Token.IN:
_append( "((JSObject)" , n );
_add( n.getFirstChild().getNext() , state );
_append( " ).containsKey( " , n );
_add( n.getFirstChild() , state );
_append( ".toString() ) " , n );
break;
case Token.NEG:
_append( "JS_mul( -1 , " , n );
_add( n.getFirstChild() , state );
_append( " )" , n );
break;
case Token.ENTERWITH:
_append( "scope.enterWith( (JSObject)" , n );
_add( n.getFirstChild() , state );
_append( " );" , n );
break;
case Token.LEAVEWITH:
_append( "scope.leaveWith();" , n );
break;
case Token.WITH:
_add( n.getFirstChild() , state );
break;
default:
Debug.printTree( n , 0 );
throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() );
}
}
|
diff --git a/block/BlockBlueFire.java b/block/BlockBlueFire.java
index 6fcb7ab..51c5fbd 100644
--- a/block/BlockBlueFire.java
+++ b/block/BlockBlueFire.java
@@ -1,518 +1,518 @@
package deepcraft.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Random;
import deepcraft.core.CommonProxy;
import deepcraft.core.SBlocks;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.WorldProviderEnd;
import net.minecraftforge.common.ForgeDirection;
import static net.minecraftforge.common.ForgeDirection.*;
public class BlockBlueFire extends Block
{
@Override
public String getTextureFile () {
return CommonProxy.BLOCK_PNG;
}
/** The chance this block will encourage nearby blocks to catch on fire */
private int[] chanceToEncourageFire = new int[256];
/**
* This is an array indexed by block ID the larger the number in the array the more likely a block type will catch
* fires
*/
private int[] abilityToCatchFire = new int[256];
public BlockBlueFire(int par1, int par2)
{
super(par1, par2, Material.fire);
this.setTickRandomly(true);
this.disableStats();
this.setCreativeTab(CreativeTabs.tabBlock);
}
/**
* This method is called on a block after all other blocks gets already created. You can use it to reference and
* configure something on the block that needs the others ones.
*/
public void initializeBlock()
{
abilityToCatchFire = Block.blockFlammability;
chanceToEncourageFire = Block.blockFireSpreadSpeed;
this.setBurnRate(Block.planks.blockID, 50, 200);
this.setBurnRate(Block.woodDoubleSlab.blockID, 50, 200);
this.setBurnRate(Block.woodSingleSlab.blockID, 50, 200);
this.setBurnRate(Block.fence.blockID, 50, 200);
this.setBurnRate(Block.stairCompactPlanks.blockID, 50, 200);
this.setBurnRate(Block.stairsWoodBirch.blockID, 50, 200);
this.setBurnRate(Block.stairsWoodSpruce.blockID, 50, 200);
this.setBurnRate(Block.stairsWoodJungle.blockID, 50, 200);
this.setBurnRate(Block.wood.blockID, 50, 50);
this.setBurnRate(Block.leaves.blockID, 300, 600);
this.setBurnRate(Block.bookShelf.blockID, 300, 200);
this.setBurnRate(Block.tnt.blockID, 150, 1000);
this.setBurnRate(Block.tallGrass.blockID, 600, 1000);
this.setBurnRate(Block.cloth.blockID, 300, 600);
this.setBurnRate(Block.vine.blockID, 150, 1000);
}
/**
* Sets the burn rate for a block. The larger abilityToCatchFire the more easily it will catch. The larger
* chanceToEncourageFire the faster it will burn and spread to other blocks. Args: blockID, chanceToEncourageFire,
* abilityToCatchFire
*/
private void setBurnRate(int par1, int par2, int par3)
{
Block.setBurnProperties(par1, par2, par3);
}
/**
* Returns a bounding box from the pool of bounding boxes (this means this box can change after the pool has been
* cleared to be reused)
*/
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4)
{
return null;
}
/**
* Is this block (a) opaque and (b) a full 1m cube? This determines whether or not to render the shared face of two
* adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block.
*/
public boolean isOpaqueCube()
{
return false;
}
/**
* If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc)
*/
public boolean renderAsNormalBlock()
{
return false;
}
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return 3;
}
/**
* Returns the quantity of items to drop on block destruction.
*/
public int quantityDropped(Random par1Random)
{
return 0;
}
/**
* How many world ticks before ticking
*/
public int tickRate()
{
return 30;
}
/**
* Ticks the block if it's been scheduled
*/
public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
if (par1World.getGameRules().getGameRuleBooleanValue("doFireTick"))
{
Block base = Block.blocksList[par1World.getBlockId(par2, par3 - 1, par4)];
- boolean var6 = (base != null && base.isFireSource(par1World, par2, par3 - 1, par4, par1World.getBlockMetadata(par2, par3 - 1, par4), UP));
+ boolean var6 = (base != null && (base.isFireSource(par1World, par2, par3 - 1, par4, par1World.getBlockMetadata(par2, par3 - 1, par4), UP) || par1World.getBlockId(par2, par3 - 1, par4) == SBlocks.netherrackDeep.blockID));
if (!this.canPlaceBlockAt(par1World, par2, par3, par4))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
if (!var6 && par1World.isRaining() && (par1World.canLightningStrikeAt(par2, par3, par4) || par1World.canLightningStrikeAt(par2 - 1, par3, par4) || par1World.canLightningStrikeAt(par2 + 1, par3, par4) || par1World.canLightningStrikeAt(par2, par3, par4 - 1) || par1World.canLightningStrikeAt(par2, par3, par4 + 1)))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
else
{
int var7 = par1World.getBlockMetadata(par2, par3, par4);
if (var7 < 15)
{
par1World.setBlockMetadata(par2, par3, par4, var7 + par5Random.nextInt(3) / 2);
}
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate() + par5Random.nextInt(10));
if (!var6 && !this.canNeighborBurn(par1World, par2, par3, par4))
{
if (!par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) || var7 > 3)
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
}
else if (!var6 && !this.canBlockCatchFire(par1World, par2, par3 - 1, par4, UP) && var7 == 15 && par5Random.nextInt(4) == 0)
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
else
{
boolean var8 = par1World.isBlockHighHumidity(par2, par3, par4);
byte var9 = 0;
if (var8)
{
var9 = -50;
}
this.tryToCatchBlockOnFire(par1World, par2 + 1, par3, par4, 300 + var9, par5Random, var7, WEST );
this.tryToCatchBlockOnFire(par1World, par2 - 1, par3, par4, 300 + var9, par5Random, var7, EAST );
this.tryToCatchBlockOnFire(par1World, par2, par3 - 1, par4, 250 + var9, par5Random, var7, UP );
this.tryToCatchBlockOnFire(par1World, par2, par3 + 1, par4, 250 + var9, par5Random, var7, DOWN );
this.tryToCatchBlockOnFire(par1World, par2, par3, par4 - 1, 300 + var9, par5Random, var7, SOUTH);
this.tryToCatchBlockOnFire(par1World, par2, par3, par4 + 1, 300 + var9, par5Random, var7, NORTH);
for (int var10 = par2 - 1; var10 <= par2 + 1; ++var10)
{
for (int var11 = par4 - 1; var11 <= par4 + 1; ++var11)
{
for (int var12 = par3 - 1; var12 <= par3 + 4; ++var12)
{
if (var10 != par2 || var12 != par3 || var11 != par4)
{
int var13 = 100;
if (var12 > par3 + 1)
{
var13 += (var12 - (par3 + 1)) * 100;
}
int var14 = this.getChanceOfNeighborsEncouragingFire(par1World, var10, var12, var11);
if (var14 > 0)
{
int var15 = (var14 + 40 + par1World.difficultySetting * 7) / (var7 + 30);
if (var8)
{
var15 /= 2;
}
if (var15 > 0 && par5Random.nextInt(var13) <= var15 && (!par1World.isRaining() || !par1World.canLightningStrikeAt(var10, var12, var11)) && !par1World.canLightningStrikeAt(var10 - 1, var12, par4) && !par1World.canLightningStrikeAt(var10 + 1, var12, var11) && !par1World.canLightningStrikeAt(var10, var12, var11 - 1) && !par1World.canLightningStrikeAt(var10, var12, var11 + 1))
{
int var16 = var7 + par5Random.nextInt(5) / 4;
if (var16 > 15)
{
var16 = 15;
}
par1World.setBlockAndMetadataWithNotify(var10, var12, var11, this.blockID, var16);
}
}
}
}
}
}
}
}
}
}
public boolean func_82506_l()
{
return false;
}
@Deprecated
private void tryToCatchBlockOnFire(World par1World, int par2, int par3, int par4, int par5, Random par6Random, int par7)
{
tryToCatchBlockOnFire(par1World, par2, par3, par4, par5, par6Random, par7, UP);
}
private void tryToCatchBlockOnFire(World par1World, int par2, int par3, int par4, int par5, Random par6Random, int par7, ForgeDirection face)
{
int var8 = 0;
Block block = Block.blocksList[par1World.getBlockId(par2, par3, par4)];
if (block != null)
{
var8 = block.getFlammability(par1World, par2, par3, par4, par1World.getBlockMetadata(par2, par3, par4), face);
}
if (par6Random.nextInt(par5) < var8)
{
boolean var9 = par1World.getBlockId(par2, par3, par4) == Block.tnt.blockID;
if (par6Random.nextInt(par7 + 10) < 5 && !par1World.canLightningStrikeAt(par2, par3, par4))
{
int var10 = par7 + par6Random.nextInt(5) / 4;
if (var10 > 15)
{
var10 = 15;
}
par1World.setBlockAndMetadataWithNotify(par2, par3, par4, this.blockID, var10);
}
else
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
if (var9)
{
Block.tnt.onBlockDestroyedByPlayer(par1World, par2, par3, par4, 1);
}
}
}
/**
* Returns true if at least one block next to this one can burn.
*/
private boolean canNeighborBurn(World par1World, int par2, int par3, int par4)
{
return canBlockCatchFire(par1World, par2 + 1, par3, par4, WEST ) ||
canBlockCatchFire(par1World, par2 - 1, par3, par4, EAST ) ||
canBlockCatchFire(par1World, par2, par3 - 1, par4, UP ) ||
canBlockCatchFire(par1World, par2, par3 + 1, par4, DOWN ) ||
canBlockCatchFire(par1World, par2, par3, par4 - 1, SOUTH) ||
canBlockCatchFire(par1World, par2, par3, par4 + 1, NORTH);
}
/**
* Gets the highest chance of a neighbor block encouraging this block to catch fire
*/
private int getChanceOfNeighborsEncouragingFire(World par1World, int par2, int par3, int par4)
{
byte var5 = 0;
if (!par1World.isAirBlock(par2, par3, par4))
{
return 0;
}
else
{
int var6 = this.getChanceToEncourageFire(par1World, par2 + 1, par3, par4, var5, WEST);
var6 = this.getChanceToEncourageFire(par1World, par2 - 1, par3, par4, var6, EAST);
var6 = this.getChanceToEncourageFire(par1World, par2, par3 - 1, par4, var6, UP);
var6 = this.getChanceToEncourageFire(par1World, par2, par3 + 1, par4, var6, DOWN);
var6 = this.getChanceToEncourageFire(par1World, par2, par3, par4 - 1, var6, SOUTH);
var6 = this.getChanceToEncourageFire(par1World, par2, par3, par4 + 1, var6, NORTH);
return var6;
}
}
/**
* Returns if this block is collidable (only used by Fire). Args: x, y, z
*/
public boolean isCollidable()
{
return false;
}
/**
* Checks the specified block coordinate to see if it can catch fire. Args: blockAccess, x, y, z
* Deprecated for a side-sensitive version
*/
@Deprecated
public boolean canBlockCatchFire(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
return canBlockCatchFire(par1IBlockAccess, par2, par3, par4, UP);
}
/**
* Retrieves a specified block's chance to encourage their neighbors to burn and if the number is greater than the
* current number passed in it will return its number instead of the passed in one. Args: world, x, y, z,
* curChanceToEncourageFire
* Deprecated for a side-sensitive version
*/
@Deprecated
public int getChanceToEncourageFire(World par1World, int par2, int par3, int par4, int par5)
{
return getChanceToEncourageFire(par1World, par2, par3, par4, par5, UP);
}
/**
* Checks to see if its valid to put this block at the specified coordinates. Args: world, x, y, z
*/
public boolean canPlaceBlockAt(World par1World, int par2, int par3, int par4)
{
return par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) || this.canNeighborBurn(par1World, par2, par3, par4);
}
/**
* Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are
* their own) Args: x, y, z, neighbor blockID
*/
public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, int par5)
{
if (!par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) && !this.canNeighborBurn(par1World, par2, par3, par4))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
}
/**
* Called whenever the block is added into the world. Args: world, x, y, z
*/
public void onBlockAdded(World par1World, int par2, int par3, int par4)
{
if (par1World.provider.dimensionId > 0 || par1World.getBlockId(par2, par3 - 1, par4) != Block.obsidian.blockID || !Block.portal.tryToCreatePortal(par1World, par2, par3, par4))
{
if (!par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) && !this.canNeighborBurn(par1World, par2, par3, par4))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
else
{
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate() + par1World.rand.nextInt(10));
}
}
}
@SideOnly(Side.CLIENT)
/**
* A randomly called display update to be able to add particles or other items for display
*/
public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
if (par5Random.nextInt(24) == 0)
{
par1World.playSound((double)((float)par2 + 0.5F), (double)((float)par3 + 0.5F), (double)((float)par4 + 0.5F), "fire.fire", 1.0F + par5Random.nextFloat(), par5Random.nextFloat() * 0.7F + 0.3F, false);
}
int var6;
float var7;
float var8;
float var9;
if (!par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) && !SBlocks.fireBlue.canBlockCatchFire(par1World, par2, par3 - 1, par4, UP))
{
if (SBlocks.fireBlue.canBlockCatchFire(par1World, par2 - 1, par3, par4, EAST))
{
for (var6 = 0; var6 < 2; ++var6)
{
var7 = (float)par2 + par5Random.nextFloat() * 0.1F;
var8 = (float)par3 + par5Random.nextFloat();
var9 = (float)par4 + par5Random.nextFloat();
par1World.spawnParticle("largesmoke", (double)var7, (double)var8, (double)var9, 0.0D, 0.0D, 0.0D);
}
}
if (SBlocks.fireBlue.canBlockCatchFire(par1World, par2 + 1, par3, par4, WEST))
{
for (var6 = 0; var6 < 2; ++var6)
{
var7 = (float)(par2 + 1) - par5Random.nextFloat() * 0.1F;
var8 = (float)par3 + par5Random.nextFloat();
var9 = (float)par4 + par5Random.nextFloat();
par1World.spawnParticle("largesmoke", (double)var7, (double)var8, (double)var9, 0.0D, 0.0D, 0.0D);
}
}
if (SBlocks.fireBlue.canBlockCatchFire(par1World, par2, par3, par4 - 1, SOUTH))
{
for (var6 = 0; var6 < 2; ++var6)
{
var7 = (float)par2 + par5Random.nextFloat();
var8 = (float)par3 + par5Random.nextFloat();
var9 = (float)par4 + par5Random.nextFloat() * 0.1F;
par1World.spawnParticle("largesmoke", (double)var7, (double)var8, (double)var9, 0.0D, 0.0D, 0.0D);
}
}
if (SBlocks.fireBlue.canBlockCatchFire(par1World, par2, par3, par4 + 1, NORTH))
{
for (var6 = 0; var6 < 2; ++var6)
{
var7 = (float)par2 + par5Random.nextFloat();
var8 = (float)par3 + par5Random.nextFloat();
var9 = (float)(par4 + 1) - par5Random.nextFloat() * 0.1F;
par1World.spawnParticle("largesmoke", (double)var7, (double)var8, (double)var9, 0.0D, 0.0D, 0.0D);
}
}
if (SBlocks.fireBlue.canBlockCatchFire(par1World, par2, par3 + 1, par4, DOWN))
{
for (var6 = 0; var6 < 2; ++var6)
{
var7 = (float)par2 + par5Random.nextFloat();
var8 = (float)(par3 + 1) - par5Random.nextFloat() * 0.1F;
var9 = (float)par4 + par5Random.nextFloat();
par1World.spawnParticle("largesmoke", (double)var7, (double)var8, (double)var9, 0.0D, 0.0D, 0.0D);
}
}
}
else
{
for (var6 = 0; var6 < 3; ++var6)
{
var7 = (float)par2 + par5Random.nextFloat();
var8 = (float)par3 + par5Random.nextFloat() * 0.5F + 0.5F;
var9 = (float)par4 + par5Random.nextFloat();
par1World.spawnParticle("largesmoke", (double)var7, (double)var8, (double)var9, 0.0D, 0.0D, 0.0D);
}
}
}
/**
* Side sensitive version that calls the block function.
*
* @param world The current world
* @param x X Position
* @param y Y Position
* @param z Z Position
* @param face The side the fire is coming from
* @return True if the face can catch fire.
*/
public boolean canBlockCatchFire(IBlockAccess world, int x, int y, int z, ForgeDirection face)
{
Block block = Block.blocksList[world.getBlockId(x, y, z)];
if (block != null)
{
return block.isFlammable(world, x, y, z, world.getBlockMetadata(x, y, z), face);
}
return false;
}
/**
* Side sensitive version that calls the block function.
*
* @param world The current world
* @param x X Position
* @param y Y Position
* @param z Z Position
* @param oldChance The previous maximum chance.
* @param face The side the fire is coming from
* @return The chance of the block catching fire, or oldChance if it is higher
*/
public int getChanceToEncourageFire(World world, int x, int y, int z, int oldChance, ForgeDirection face)
{
int newChance = 0;
Block block = Block.blocksList[world.getBlockId(x, y, z)];
if (block != null)
{
newChance = block.getFireSpreadSpeed(world, x, y, z, world.getBlockMetadata(x, y, z), face);
}
return (newChance > oldChance ? newChance : oldChance);
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity ent) {
ent.setFire(10);
}
}
| true | true | public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
if (par1World.getGameRules().getGameRuleBooleanValue("doFireTick"))
{
Block base = Block.blocksList[par1World.getBlockId(par2, par3 - 1, par4)];
boolean var6 = (base != null && base.isFireSource(par1World, par2, par3 - 1, par4, par1World.getBlockMetadata(par2, par3 - 1, par4), UP));
if (!this.canPlaceBlockAt(par1World, par2, par3, par4))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
if (!var6 && par1World.isRaining() && (par1World.canLightningStrikeAt(par2, par3, par4) || par1World.canLightningStrikeAt(par2 - 1, par3, par4) || par1World.canLightningStrikeAt(par2 + 1, par3, par4) || par1World.canLightningStrikeAt(par2, par3, par4 - 1) || par1World.canLightningStrikeAt(par2, par3, par4 + 1)))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
else
{
int var7 = par1World.getBlockMetadata(par2, par3, par4);
if (var7 < 15)
{
par1World.setBlockMetadata(par2, par3, par4, var7 + par5Random.nextInt(3) / 2);
}
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate() + par5Random.nextInt(10));
if (!var6 && !this.canNeighborBurn(par1World, par2, par3, par4))
{
if (!par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) || var7 > 3)
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
}
else if (!var6 && !this.canBlockCatchFire(par1World, par2, par3 - 1, par4, UP) && var7 == 15 && par5Random.nextInt(4) == 0)
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
else
{
boolean var8 = par1World.isBlockHighHumidity(par2, par3, par4);
byte var9 = 0;
if (var8)
{
var9 = -50;
}
this.tryToCatchBlockOnFire(par1World, par2 + 1, par3, par4, 300 + var9, par5Random, var7, WEST );
this.tryToCatchBlockOnFire(par1World, par2 - 1, par3, par4, 300 + var9, par5Random, var7, EAST );
this.tryToCatchBlockOnFire(par1World, par2, par3 - 1, par4, 250 + var9, par5Random, var7, UP );
this.tryToCatchBlockOnFire(par1World, par2, par3 + 1, par4, 250 + var9, par5Random, var7, DOWN );
this.tryToCatchBlockOnFire(par1World, par2, par3, par4 - 1, 300 + var9, par5Random, var7, SOUTH);
this.tryToCatchBlockOnFire(par1World, par2, par3, par4 + 1, 300 + var9, par5Random, var7, NORTH);
for (int var10 = par2 - 1; var10 <= par2 + 1; ++var10)
{
for (int var11 = par4 - 1; var11 <= par4 + 1; ++var11)
{
for (int var12 = par3 - 1; var12 <= par3 + 4; ++var12)
{
if (var10 != par2 || var12 != par3 || var11 != par4)
{
int var13 = 100;
if (var12 > par3 + 1)
{
var13 += (var12 - (par3 + 1)) * 100;
}
int var14 = this.getChanceOfNeighborsEncouragingFire(par1World, var10, var12, var11);
if (var14 > 0)
{
int var15 = (var14 + 40 + par1World.difficultySetting * 7) / (var7 + 30);
if (var8)
{
var15 /= 2;
}
if (var15 > 0 && par5Random.nextInt(var13) <= var15 && (!par1World.isRaining() || !par1World.canLightningStrikeAt(var10, var12, var11)) && !par1World.canLightningStrikeAt(var10 - 1, var12, par4) && !par1World.canLightningStrikeAt(var10 + 1, var12, var11) && !par1World.canLightningStrikeAt(var10, var12, var11 - 1) && !par1World.canLightningStrikeAt(var10, var12, var11 + 1))
{
int var16 = var7 + par5Random.nextInt(5) / 4;
if (var16 > 15)
{
var16 = 15;
}
par1World.setBlockAndMetadataWithNotify(var10, var12, var11, this.blockID, var16);
}
}
}
}
}
}
}
}
}
}
| public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
if (par1World.getGameRules().getGameRuleBooleanValue("doFireTick"))
{
Block base = Block.blocksList[par1World.getBlockId(par2, par3 - 1, par4)];
boolean var6 = (base != null && (base.isFireSource(par1World, par2, par3 - 1, par4, par1World.getBlockMetadata(par2, par3 - 1, par4), UP) || par1World.getBlockId(par2, par3 - 1, par4) == SBlocks.netherrackDeep.blockID));
if (!this.canPlaceBlockAt(par1World, par2, par3, par4))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
if (!var6 && par1World.isRaining() && (par1World.canLightningStrikeAt(par2, par3, par4) || par1World.canLightningStrikeAt(par2 - 1, par3, par4) || par1World.canLightningStrikeAt(par2 + 1, par3, par4) || par1World.canLightningStrikeAt(par2, par3, par4 - 1) || par1World.canLightningStrikeAt(par2, par3, par4 + 1)))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
else
{
int var7 = par1World.getBlockMetadata(par2, par3, par4);
if (var7 < 15)
{
par1World.setBlockMetadata(par2, par3, par4, var7 + par5Random.nextInt(3) / 2);
}
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate() + par5Random.nextInt(10));
if (!var6 && !this.canNeighborBurn(par1World, par2, par3, par4))
{
if (!par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) || var7 > 3)
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
}
else if (!var6 && !this.canBlockCatchFire(par1World, par2, par3 - 1, par4, UP) && var7 == 15 && par5Random.nextInt(4) == 0)
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
}
else
{
boolean var8 = par1World.isBlockHighHumidity(par2, par3, par4);
byte var9 = 0;
if (var8)
{
var9 = -50;
}
this.tryToCatchBlockOnFire(par1World, par2 + 1, par3, par4, 300 + var9, par5Random, var7, WEST );
this.tryToCatchBlockOnFire(par1World, par2 - 1, par3, par4, 300 + var9, par5Random, var7, EAST );
this.tryToCatchBlockOnFire(par1World, par2, par3 - 1, par4, 250 + var9, par5Random, var7, UP );
this.tryToCatchBlockOnFire(par1World, par2, par3 + 1, par4, 250 + var9, par5Random, var7, DOWN );
this.tryToCatchBlockOnFire(par1World, par2, par3, par4 - 1, 300 + var9, par5Random, var7, SOUTH);
this.tryToCatchBlockOnFire(par1World, par2, par3, par4 + 1, 300 + var9, par5Random, var7, NORTH);
for (int var10 = par2 - 1; var10 <= par2 + 1; ++var10)
{
for (int var11 = par4 - 1; var11 <= par4 + 1; ++var11)
{
for (int var12 = par3 - 1; var12 <= par3 + 4; ++var12)
{
if (var10 != par2 || var12 != par3 || var11 != par4)
{
int var13 = 100;
if (var12 > par3 + 1)
{
var13 += (var12 - (par3 + 1)) * 100;
}
int var14 = this.getChanceOfNeighborsEncouragingFire(par1World, var10, var12, var11);
if (var14 > 0)
{
int var15 = (var14 + 40 + par1World.difficultySetting * 7) / (var7 + 30);
if (var8)
{
var15 /= 2;
}
if (var15 > 0 && par5Random.nextInt(var13) <= var15 && (!par1World.isRaining() || !par1World.canLightningStrikeAt(var10, var12, var11)) && !par1World.canLightningStrikeAt(var10 - 1, var12, par4) && !par1World.canLightningStrikeAt(var10 + 1, var12, var11) && !par1World.canLightningStrikeAt(var10, var12, var11 - 1) && !par1World.canLightningStrikeAt(var10, var12, var11 + 1))
{
int var16 = var7 + par5Random.nextInt(5) / 4;
if (var16 > 15)
{
var16 = 15;
}
par1World.setBlockAndMetadataWithNotify(var10, var12, var11, this.blockID, var16);
}
}
}
}
}
}
}
}
}
}
|
diff --git a/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java b/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java
index 543971924..8130a1c20 100644
--- a/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java
+++ b/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java
@@ -1,122 +1,123 @@
/*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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 org.obiba.opal.web.magma;
import java.net.URI;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import org.obiba.magma.Datasource;
import org.obiba.magma.DatasourceFactory;
import org.obiba.magma.MagmaEngine;
import org.obiba.magma.MagmaRuntimeException;
import org.obiba.magma.support.DatasourceParsingException;
import org.obiba.magma.support.Disposables;
import org.obiba.magma.support.MagmaEngineTableResolver;
import org.obiba.opal.web.magma.support.DatasourceFactoryRegistry;
import org.obiba.opal.web.model.Magma;
import org.obiba.opal.web.model.Magma.DatasourceDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
@Component
@Path("/datasources")
public class DatasourcesResource {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(DatasourcesResource.class);
private String keysDatasourceName;
private DatasourceFactoryRegistry datasourceFactoryRegistry;
@Autowired
public DatasourcesResource(@Value("${org.obiba.opal.keys.tableReference}") String keysTableReference, DatasourceFactoryRegistry datasourceFactoryRegistry) {
keysDatasourceName = MagmaEngineTableResolver.valueOf(keysTableReference).getDatasourceName();
this.datasourceFactoryRegistry = datasourceFactoryRegistry;
if(keysDatasourceName == null) {
throw new IllegalArgumentException("invalid keys table reference");
}
}
@GET
public List<Magma.DatasourceDto> getDatasources() {
final List<Magma.DatasourceDto> datasources = Lists.newArrayList();
for(Datasource from : MagmaEngine.get().getDatasources()) {
// OPAL-365: Hide the keys datasource.
if(from.getName().equals(keysDatasourceName)) continue;
URI dslink = UriBuilder.fromPath("/").path(DatasourceResource.class).build(from.getName());
Magma.DatasourceDto.Builder ds = Dtos.asDto(from).setLink(dslink.toString());
datasources.add(ds.build());
}
sortByName(datasources);
return datasources;
}
@POST
public Response createDatasource(@Context final UriInfo uriInfo, Magma.DatasourceFactoryDto factoryDto) {
DatasourceFactory factory = datasourceFactoryRegistry.parse(factoryDto);
ResponseBuilder response = null;
if(factory != null) {
String uid = MagmaEngine.get().addTransientDatasource(factory);
try {
Datasource ds = MagmaEngine.get().getTransientDatasourceInstance(uid);
UriBuilder ub = uriInfo.getBaseUriBuilder().path("datasource").path(uid);
response = Response.created(ub.build()).entity(Dtos.asDto(ds).build());
Disposables.silentlyDispose(ds);
} catch(DatasourceParsingException pe) {
// unable to create a datasource from that, so rollback
MagmaEngine.get().removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", pe).build());
} catch(MagmaRuntimeException e) {
// unable to create a datasource from that too, so rollback
MagmaEngine.get().removeTransientDatasource(uid);
- response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", e).build());
+ response = Response.status(Status.BAD_REQUEST).entity("{}");// ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST,
+ // "DatasourceCreationFailed", e).build());
}
} else {
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "UnidentifiedDatasourceFactory").build());
}
return response.build();
}
private void sortByName(List<Magma.DatasourceDto> datasources) {
// sort alphabetically
Collections.sort(datasources, new Comparator<Magma.DatasourceDto>() {
@Override
public int compare(DatasourceDto d1, DatasourceDto d2) {
return d1.getName().compareTo(d2.getName());
}
});
}
}
| true | true | public Response createDatasource(@Context final UriInfo uriInfo, Magma.DatasourceFactoryDto factoryDto) {
DatasourceFactory factory = datasourceFactoryRegistry.parse(factoryDto);
ResponseBuilder response = null;
if(factory != null) {
String uid = MagmaEngine.get().addTransientDatasource(factory);
try {
Datasource ds = MagmaEngine.get().getTransientDatasourceInstance(uid);
UriBuilder ub = uriInfo.getBaseUriBuilder().path("datasource").path(uid);
response = Response.created(ub.build()).entity(Dtos.asDto(ds).build());
Disposables.silentlyDispose(ds);
} catch(DatasourceParsingException pe) {
// unable to create a datasource from that, so rollback
MagmaEngine.get().removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", pe).build());
} catch(MagmaRuntimeException e) {
// unable to create a datasource from that too, so rollback
MagmaEngine.get().removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", e).build());
}
} else {
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "UnidentifiedDatasourceFactory").build());
}
return response.build();
}
| public Response createDatasource(@Context final UriInfo uriInfo, Magma.DatasourceFactoryDto factoryDto) {
DatasourceFactory factory = datasourceFactoryRegistry.parse(factoryDto);
ResponseBuilder response = null;
if(factory != null) {
String uid = MagmaEngine.get().addTransientDatasource(factory);
try {
Datasource ds = MagmaEngine.get().getTransientDatasourceInstance(uid);
UriBuilder ub = uriInfo.getBaseUriBuilder().path("datasource").path(uid);
response = Response.created(ub.build()).entity(Dtos.asDto(ds).build());
Disposables.silentlyDispose(ds);
} catch(DatasourceParsingException pe) {
// unable to create a datasource from that, so rollback
MagmaEngine.get().removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", pe).build());
} catch(MagmaRuntimeException e) {
// unable to create a datasource from that too, so rollback
MagmaEngine.get().removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity("{}");// ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST,
// "DatasourceCreationFailed", e).build());
}
} else {
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "UnidentifiedDatasourceFactory").build());
}
return response.build();
}
|
diff --git a/src/LoginController.java b/src/LoginController.java
index a2d4a56..a2e3747 100644
--- a/src/LoginController.java
+++ b/src/LoginController.java
@@ -1,88 +1,92 @@
package ca.awesome;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
public class LoginController extends Controller {
public static String USERNAME_FIELD = "USERNAME";
public static String PASSWORD_FIELD = "PASSWORD";
public static String PASSWORD_CONF_FIELD = "PASSWORD_CONF";
public static String FIRST_NAME = "FIRSTNAME";
public static String LAST_NAME = "LASTNAME";
public static String ADDRESS = "ADDRESS";
public static String EMAIL = "EMAIL";
public static String PHONE = "PHONE";
public LoginController(ServletContext context, HttpServletRequest request,
HttpServletResponse response, HttpSession session) {
super(context, request, response, session);
}
public boolean attemptLogin() {
String userName = request.getParameter(USERNAME_FIELD).trim();
String password = request.getParameter(PASSWORD_FIELD).trim();
DatabaseConnection connection = getDatabaseConnection(context);
User foundUser = User.findUserByName(userName, connection);
if (foundUser != null && foundUser.getPassword().equals(password)) {
user = foundUser;
session.setAttribute("user", user);
return true;
}
return false;
}
public void logout() {
session.setAttribute("user", null);
user = null;
}
public boolean attemptChangePassword() {
String password = request.getParameter(PASSWORD_FIELD).trim();
String passwordConf = request.getParameter(PASSWORD_CONF_FIELD).trim();
if (!password.equals(passwordConf)) {
error = "password fields did not match";
return false;
}
DatabaseConnection connection = getDatabaseConnection(context);
User.updateUserPassword(user, password, connection);
return true;
}
// GET editPersonalInfo.jsp
public void getUpdateInfo() {
if (!user.loadPersonalInfo(getDatabaseConnection())) {
user.addEmptyPersonalInfo();
}
}
public boolean attemptUpdateInfo() {
String firstName = request.getParameter(FIRST_NAME).trim();
String lastName = request.getParameter(LAST_NAME).trim();
String address = request.getParameter(ADDRESS).trim();
String email = request.getParameter(EMAIL).trim();
String phone = request.getParameter(PHONE).trim();
boolean valid = true;
// do validation
valid &= validateStringLength(firstName, "first name", 24);
valid &= validateStringLength(lastName, "last name", 24);
valid &= validateStringLength(address, "address", 128);
valid &= validateStringLength(email, "email", 128);
valid &= validateStringLength(phone, "phone", 10);
if (valid == false) {
return false;
}
- return user.upsertPersonalInfo(firstName, lastName, address, email,
- phone, getDatabaseConnection());
+ if (!user.upsertPersonalInfo(firstName, lastName, address, email,
+ phone, getDatabaseConnection())) {
+ error = "Failed to edit personal info.";
+ return false;
+ }
+ return true;
}
};
| true | true | public boolean attemptUpdateInfo() {
String firstName = request.getParameter(FIRST_NAME).trim();
String lastName = request.getParameter(LAST_NAME).trim();
String address = request.getParameter(ADDRESS).trim();
String email = request.getParameter(EMAIL).trim();
String phone = request.getParameter(PHONE).trim();
boolean valid = true;
// do validation
valid &= validateStringLength(firstName, "first name", 24);
valid &= validateStringLength(lastName, "last name", 24);
valid &= validateStringLength(address, "address", 128);
valid &= validateStringLength(email, "email", 128);
valid &= validateStringLength(phone, "phone", 10);
if (valid == false) {
return false;
}
return user.upsertPersonalInfo(firstName, lastName, address, email,
phone, getDatabaseConnection());
}
| public boolean attemptUpdateInfo() {
String firstName = request.getParameter(FIRST_NAME).trim();
String lastName = request.getParameter(LAST_NAME).trim();
String address = request.getParameter(ADDRESS).trim();
String email = request.getParameter(EMAIL).trim();
String phone = request.getParameter(PHONE).trim();
boolean valid = true;
// do validation
valid &= validateStringLength(firstName, "first name", 24);
valid &= validateStringLength(lastName, "last name", 24);
valid &= validateStringLength(address, "address", 128);
valid &= validateStringLength(email, "email", 128);
valid &= validateStringLength(phone, "phone", 10);
if (valid == false) {
return false;
}
if (!user.upsertPersonalInfo(firstName, lastName, address, email,
phone, getDatabaseConnection())) {
error = "Failed to edit personal info.";
return false;
}
return true;
}
|
diff --git a/src/test/java/com/github/miemiedev/mybatis/paginator/PaginatorTester.java b/src/test/java/com/github/miemiedev/mybatis/paginator/PaginatorTester.java
index 7658e11..61f7e69 100644
--- a/src/test/java/com/github/miemiedev/mybatis/paginator/PaginatorTester.java
+++ b/src/test/java/com/github/miemiedev/mybatis/paginator/PaginatorTester.java
@@ -1,47 +1,47 @@
package com.github.miemiedev.mybatis.paginator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.miemiedev.mybatis.paginator.jackson2.PageListJsonMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author miemiedev
*/
public class PaginatorTester extends SimulateBaseDao{
@Test
public void controllerMethod() throws IOException {
int page = 1;
int pageSize = 20;
String sortString = "type.asc,code.desc";
String contentSortString = "content.desc";
PageQuery pageQuery = new PageQuery(page, pageSize , sortString)
//Oracle sorting of chinese pinyin
.addSortInfo(contentSortString, "nlssort( ? ,'NLS_SORT=SCHINESE_PINYIN_M')");
- List list = find("FP_FUND",new PageQuery(sortString));
+ List list = find("FP_FUND",pageQuery);
//get totalCount
PageList pageList = (PageList)list;
System.out.println("totalCount: " + pageList.getPaginator().getTotalCount());
//convert to json , for spring mvc
ObjectMapper objectMapper = new PageListJsonMapper();
objectMapper.writeValue(System.out, list);
}
public List find(String type, PageQuery pageQuery){
Map<String, Object> params = new HashMap<String, Object>();
params.put("type",type);
return getSqlSession().selectList("financial.dict.find", params, pageQuery);
}
}
| true | true | public void controllerMethod() throws IOException {
int page = 1;
int pageSize = 20;
String sortString = "type.asc,code.desc";
String contentSortString = "content.desc";
PageQuery pageQuery = new PageQuery(page, pageSize , sortString)
//Oracle sorting of chinese pinyin
.addSortInfo(contentSortString, "nlssort( ? ,'NLS_SORT=SCHINESE_PINYIN_M')");
List list = find("FP_FUND",new PageQuery(sortString));
//get totalCount
PageList pageList = (PageList)list;
System.out.println("totalCount: " + pageList.getPaginator().getTotalCount());
//convert to json , for spring mvc
ObjectMapper objectMapper = new PageListJsonMapper();
objectMapper.writeValue(System.out, list);
}
| public void controllerMethod() throws IOException {
int page = 1;
int pageSize = 20;
String sortString = "type.asc,code.desc";
String contentSortString = "content.desc";
PageQuery pageQuery = new PageQuery(page, pageSize , sortString)
//Oracle sorting of chinese pinyin
.addSortInfo(contentSortString, "nlssort( ? ,'NLS_SORT=SCHINESE_PINYIN_M')");
List list = find("FP_FUND",pageQuery);
//get totalCount
PageList pageList = (PageList)list;
System.out.println("totalCount: " + pageList.getPaginator().getTotalCount());
//convert to json , for spring mvc
ObjectMapper objectMapper = new PageListJsonMapper();
objectMapper.writeValue(System.out, list);
}
|
diff --git a/gdp-file-management-webapp/src/main/java/gov/usgs/cida/gdp/filemanagement/servlet/GeoServerServlet.java b/gdp-file-management-webapp/src/main/java/gov/usgs/cida/gdp/filemanagement/servlet/GeoServerServlet.java
index d46b661c..a658b3b8 100644
--- a/gdp-file-management-webapp/src/main/java/gov/usgs/cida/gdp/filemanagement/servlet/GeoServerServlet.java
+++ b/gdp-file-management-webapp/src/main/java/gov/usgs/cida/gdp/filemanagement/servlet/GeoServerServlet.java
@@ -1,121 +1,122 @@
package gov.usgs.cida.gdp.filemanagement.servlet;
import gov.usgs.cida.gdp.filemanagement.bean.List;
import gov.usgs.cida.gdp.filemanagement.interfaces.geoserver.ManageWorkSpace;
import gov.usgs.cida.gdp.utilities.FileHelper;
import gov.usgs.cida.gdp.utilities.XmlUtils;
import gov.usgs.cida.gdp.utilities.bean.Acknowledgement;
import gov.usgs.cida.gdp.utilities.bean.Message;
import gov.usgs.cida.gdp.utilities.bean.XmlReply;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FileSelectionServlet
*/
public class GeoServerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GeoServerServlet.class);
/**
* @see HttpServlet#HttpServlet()
*/
public GeoServerServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ManageWorkSpace mws = new ManageWorkSpace();
String command = request.getParameter("command");
String workspace = request.getParameter("workspace");
String dataFileName = request.getParameter("datafile");
String appTempDir = System.getProperty("applicationTempDir");
String dataFileLoc = appTempDir + "upload-repository/" + dataFileName;
String delimChar = request.getParameter("delim");
String delim;
if ("c".equals(delimChar)) {
delim = ",";
} else if ("s".equals(delimChar)) {
delim = " ";
} else if ("t".equals(delimChar)) {
delim = "\t";
} else if (delimChar == null) {
delim = ""; // if command doesn't require a delim
} else {
sendReply(response, Acknowledgement.ACK_FAIL, "Invalid delimiter.");
System.err.println("ERROR: invalid delimiter: " + delimChar);
return;
}
if ("createdatastore".equals(command)) {
String shapefilePath = URLDecoder.decode(request.getParameter("shapefilepath"), "UTF-8");
+ String srsCode = URLDecoder.decode(request.getParameter("srs-code"), "UTF-8");
String shapefileName = shapefilePath.substring(
shapefilePath.lastIndexOf(File.separator) + 1,
shapefilePath.lastIndexOf("."));
- if (!mws.createDataStore(shapefilePath, shapefileName, workspace)) {
+ if (!mws.createDataStore(shapefilePath, shapefileName, workspace, srsCode)) {
sendReply(response, Acknowledgement.ACK_FAIL, "Could not create data store.");
} else {
// send back ack with workspace and layer names
sendReply(response, Acknowledgement.ACK_OK, workspace, shapefileName);
}
} else if ("getdatafileselectables".equals(command)) {
// return list of dates in data file
ArrayList<String> dates = mws.parseDates(new File(dataFileLoc), delim);
XmlReply xmlReply = new XmlReply(Acknowledgement.ACK_OK, new List(dates));
XmlUtils.sendXml(xmlReply, Long.valueOf(new Date().getTime()), response);
} else if ("createcoloredmap".equals(command)) {
// create style to color polygons given a date, stat, and data file
String shapefileName = request.getParameter("shapefilename");
String fromDate = request.getParameter("fromdate");
String toDate = request.getParameter("todate");
String attribute = request.getParameter("attribute");
String stat = request.getParameter("stat");
try {
mws.createColoredMap(dataFileLoc, workspace, shapefileName, fromDate, toDate, stat, attribute, delim);
} catch (ParseException ex) {
Logger.getLogger(GeoServerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
sendReply(response, Acknowledgement.ACK_OK);
} else if ("clearcache".equals(command)) {
//clearCache();
}
}
void sendReply(HttpServletResponse response, int status, String... messages) throws IOException {
XmlReply xmlReply = new XmlReply(status, new Message(messages));
XmlUtils.sendXml(xmlReply, Long.valueOf(new Date().getTime()), response);
}
}
| false | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ManageWorkSpace mws = new ManageWorkSpace();
String command = request.getParameter("command");
String workspace = request.getParameter("workspace");
String dataFileName = request.getParameter("datafile");
String appTempDir = System.getProperty("applicationTempDir");
String dataFileLoc = appTempDir + "upload-repository/" + dataFileName;
String delimChar = request.getParameter("delim");
String delim;
if ("c".equals(delimChar)) {
delim = ",";
} else if ("s".equals(delimChar)) {
delim = " ";
} else if ("t".equals(delimChar)) {
delim = "\t";
} else if (delimChar == null) {
delim = ""; // if command doesn't require a delim
} else {
sendReply(response, Acknowledgement.ACK_FAIL, "Invalid delimiter.");
System.err.println("ERROR: invalid delimiter: " + delimChar);
return;
}
if ("createdatastore".equals(command)) {
String shapefilePath = URLDecoder.decode(request.getParameter("shapefilepath"), "UTF-8");
String shapefileName = shapefilePath.substring(
shapefilePath.lastIndexOf(File.separator) + 1,
shapefilePath.lastIndexOf("."));
if (!mws.createDataStore(shapefilePath, shapefileName, workspace)) {
sendReply(response, Acknowledgement.ACK_FAIL, "Could not create data store.");
} else {
// send back ack with workspace and layer names
sendReply(response, Acknowledgement.ACK_OK, workspace, shapefileName);
}
} else if ("getdatafileselectables".equals(command)) {
// return list of dates in data file
ArrayList<String> dates = mws.parseDates(new File(dataFileLoc), delim);
XmlReply xmlReply = new XmlReply(Acknowledgement.ACK_OK, new List(dates));
XmlUtils.sendXml(xmlReply, Long.valueOf(new Date().getTime()), response);
} else if ("createcoloredmap".equals(command)) {
// create style to color polygons given a date, stat, and data file
String shapefileName = request.getParameter("shapefilename");
String fromDate = request.getParameter("fromdate");
String toDate = request.getParameter("todate");
String attribute = request.getParameter("attribute");
String stat = request.getParameter("stat");
try {
mws.createColoredMap(dataFileLoc, workspace, shapefileName, fromDate, toDate, stat, attribute, delim);
} catch (ParseException ex) {
Logger.getLogger(GeoServerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
sendReply(response, Acknowledgement.ACK_OK);
} else if ("clearcache".equals(command)) {
//clearCache();
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ManageWorkSpace mws = new ManageWorkSpace();
String command = request.getParameter("command");
String workspace = request.getParameter("workspace");
String dataFileName = request.getParameter("datafile");
String appTempDir = System.getProperty("applicationTempDir");
String dataFileLoc = appTempDir + "upload-repository/" + dataFileName;
String delimChar = request.getParameter("delim");
String delim;
if ("c".equals(delimChar)) {
delim = ",";
} else if ("s".equals(delimChar)) {
delim = " ";
} else if ("t".equals(delimChar)) {
delim = "\t";
} else if (delimChar == null) {
delim = ""; // if command doesn't require a delim
} else {
sendReply(response, Acknowledgement.ACK_FAIL, "Invalid delimiter.");
System.err.println("ERROR: invalid delimiter: " + delimChar);
return;
}
if ("createdatastore".equals(command)) {
String shapefilePath = URLDecoder.decode(request.getParameter("shapefilepath"), "UTF-8");
String srsCode = URLDecoder.decode(request.getParameter("srs-code"), "UTF-8");
String shapefileName = shapefilePath.substring(
shapefilePath.lastIndexOf(File.separator) + 1,
shapefilePath.lastIndexOf("."));
if (!mws.createDataStore(shapefilePath, shapefileName, workspace, srsCode)) {
sendReply(response, Acknowledgement.ACK_FAIL, "Could not create data store.");
} else {
// send back ack with workspace and layer names
sendReply(response, Acknowledgement.ACK_OK, workspace, shapefileName);
}
} else if ("getdatafileselectables".equals(command)) {
// return list of dates in data file
ArrayList<String> dates = mws.parseDates(new File(dataFileLoc), delim);
XmlReply xmlReply = new XmlReply(Acknowledgement.ACK_OK, new List(dates));
XmlUtils.sendXml(xmlReply, Long.valueOf(new Date().getTime()), response);
} else if ("createcoloredmap".equals(command)) {
// create style to color polygons given a date, stat, and data file
String shapefileName = request.getParameter("shapefilename");
String fromDate = request.getParameter("fromdate");
String toDate = request.getParameter("todate");
String attribute = request.getParameter("attribute");
String stat = request.getParameter("stat");
try {
mws.createColoredMap(dataFileLoc, workspace, shapefileName, fromDate, toDate, stat, attribute, delim);
} catch (ParseException ex) {
Logger.getLogger(GeoServerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
sendReply(response, Acknowledgement.ACK_OK);
} else if ("clearcache".equals(command)) {
//clearCache();
}
}
|
diff --git a/src/main/java/com/webbricks/controllers/WBParameterController.java b/src/main/java/com/webbricks/controllers/WBParameterController.java
index f2e30cb..4c132bf 100644
--- a/src/main/java/com/webbricks/controllers/WBParameterController.java
+++ b/src/main/java/com/webbricks/controllers/WBParameterController.java
@@ -1,251 +1,251 @@
package com.webbricks.controllers;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.webbricks.cache.DefaultWBCacheFactory;
import com.webbricks.cache.WBCacheFactory;
import com.webbricks.cache.WBParametersCache;
import com.webbricks.cmsdata.WBParameter;
import com.webbricks.cmsdata.WBUri;
import com.webbricks.cmsdata.WBWebPage;
import com.webbricks.datautility.AdminDataStorage;
import com.webbricks.datautility.AdminDataStorage.AdminQueryOperator;
import com.webbricks.datautility.AdminDataStorageListener;
import com.webbricks.datautility.AdminDataStorageListener.AdminDataStorageOperation;
import com.webbricks.datautility.GaeAdminDataStorage;
import com.webbricks.datautility.WBDefaultGaeDataFactory;
import com.webbricks.datautility.WBJSONToFromObjectConverter;
import com.webbricks.exception.WBException;
import com.webbricks.exception.WBIOException;
import com.webbricks.utility.HttpServletToolbox;
public class WBParameterController extends WBController implements AdminDataStorageListener<WBParameter> {
private HttpServletToolbox httpServletToolbox;
private WBJSONToFromObjectConverter jsonObjectConverter;
private AdminDataStorage adminStorage;
private WBParameterValidator parameterValidator;
private WBParametersCache wbParameterCache;
public WBParameterController() {
httpServletToolbox = new HttpServletToolbox();
jsonObjectConverter = new WBJSONToFromObjectConverter();
adminStorage = new GaeAdminDataStorage();
parameterValidator = new WBParameterValidator();
WBCacheFactory wbCacheFactory = new DefaultWBCacheFactory();
wbParameterCache = wbCacheFactory.createWBParametersCacheInstance();
adminStorage.addStorageListener(this);
}
public void notify (WBParameter t, AdminDataStorageOperation o)
{
try
{
wbParameterCache.Refresh();
} catch (WBIOException e)
{
// TBD
}
}
public void get(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
Long key = Long.valueOf((String)request.getAttribute("key"));
WBParameter wbparameter = adminStorage.get(key, WBParameter.class);
String jsonReturn = jsonObjectConverter.JSONStringFromObject(wbparameter, null);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn, null);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_GET_RECORDS);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
public void getAll(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
List<WBParameter> parameters = null;
String keyOwner = request.getParameter("ownerExternalKey");
if (keyOwner != null)
{
parameters = adminStorage.query(WBParameter.class, "ownerExternalKey", AdminQueryOperator.EQUAL, keyOwner);
} else
{
parameters = adminStorage.getAllRecords(WBParameter.class);
}
String jsonReturn = jsonObjectConverter.JSONStringFromListObjects(parameters);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn, null);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_GET_RECORDS);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
public void update(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
Long key = Long.valueOf((String)request.getAttribute("key"));
String jsonRequest = httpServletToolbox.getBodyText(request);
WBParameter wbParameter = (WBParameter)jsonObjectConverter.objectFromJSONString(jsonRequest, WBParameter.class);
wbParameter.setKey(key);
Map<String, String> errors = parameterValidator.validateUpdate(wbParameter);
if (errors.size()>0)
{
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
return;
}
wbParameter.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
WBParameter newParameter = adminStorage.update(wbParameter);
String jsonReturn = jsonObjectConverter.JSONStringFromObject(newParameter, null);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn.toString(), errors);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_UPDATE_RECORD);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
public void delete(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
Long key = Long.valueOf((String)request.getAttribute("key"));
adminStorage.delete(key, WBParameter.class);
WBParameter param = new WBParameter();
param.setKey(key);
String jsonReturn = jsonObjectConverter.JSONStringFromObject(param, null);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn, null);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_DELETE_RECORD);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
public void createSingle(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
String jsonRequest = httpServletToolbox.getBodyText(request);
WBParameter wbParameter = (WBParameter)jsonObjectConverter.objectFromJSONString(jsonRequest, WBParameter.class);
Map<String, String> errors = parameterValidator.validateCreate(wbParameter);
if (errors.size()>0)
{
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
return;
}
wbParameter.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
wbParameter.setExternalKey(adminStorage.getUniqueId());
WBParameter newParameter = adminStorage.add(wbParameter);
String jsonReturn = jsonObjectConverter.JSONStringFromObject(newParameter, null);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn.toString(), errors);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_CREATE_RECORD);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
public void createFromOwner(String fromOwnerExternalKey, String ownerExternalKey, HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
Map<String, String> errors = new HashMap<String, String>();
if (ownerExternalKey == null || ownerExternalKey.equals(0L))
{
errors.put("", WBErrors.WBPARAMETER_NO_OWNER_KEY);
}
if (fromOwnerExternalKey == null || fromOwnerExternalKey.equals(0L))
{
errors.put("", WBErrors.WBPARAMETER_NO_FROMOWNER_KEY);
}
if (errors.size()>0)
{
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
- List<WBParameter> ownerParams = adminStorage.query(WBParameter.class, "ownerExternalKey", AdminQueryOperator.EQUAL, Long.valueOf(fromOwnerExternalKey));
+ List<WBParameter> ownerParams = adminStorage.query(WBParameter.class, "ownerExternalKey", AdminQueryOperator.EQUAL, fromOwnerExternalKey);
List<WBParameter> newParams = new ArrayList<WBParameter>();
for(WBParameter parameter: ownerParams)
{
parameter.setOwnerExternalKey(ownerExternalKey);
parameter.setKey(null);
parameter.setExternalKey(adminStorage.getUniqueId());
parameter.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
WBParameter newParam = adminStorage.add(parameter);
newParams.add(newParam);
}
String jsonReturn = jsonObjectConverter.JSONStringFromListObjects(newParams);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn.toString(), errors);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_CREATE_RECORD);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
public void create(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
String ownerExternalKeyStr = request.getParameter("ownerExternalKey");
String fromOwnerExternalKeyStr = request.getParameter("fromOwnerExternalKey");
if (ownerExternalKeyStr != null || fromOwnerExternalKeyStr != null)
{
createFromOwner(fromOwnerExternalKeyStr, ownerExternalKeyStr, request, response, requestUri);
return;
}
createSingle(request, response, requestUri);
}
public void setHttpServletToolbox(HttpServletToolbox httpServletToolbox) {
this.httpServletToolbox = httpServletToolbox;
}
public void setJsonObjectConverter(
WBJSONToFromObjectConverter jsonObjectConverter) {
this.jsonObjectConverter = jsonObjectConverter;
}
public void setAdminStorage(AdminDataStorage adminStorage) {
this.adminStorage = adminStorage;
}
public void setParameterValidator(WBParameterValidator parameterValidator) {
this.parameterValidator = parameterValidator;
}
public void setParameterCache(WBParametersCache parameterCache)
{
this.wbParameterCache = parameterCache;
}
}
| true | true | public void createFromOwner(String fromOwnerExternalKey, String ownerExternalKey, HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
Map<String, String> errors = new HashMap<String, String>();
if (ownerExternalKey == null || ownerExternalKey.equals(0L))
{
errors.put("", WBErrors.WBPARAMETER_NO_OWNER_KEY);
}
if (fromOwnerExternalKey == null || fromOwnerExternalKey.equals(0L))
{
errors.put("", WBErrors.WBPARAMETER_NO_FROMOWNER_KEY);
}
if (errors.size()>0)
{
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
List<WBParameter> ownerParams = adminStorage.query(WBParameter.class, "ownerExternalKey", AdminQueryOperator.EQUAL, Long.valueOf(fromOwnerExternalKey));
List<WBParameter> newParams = new ArrayList<WBParameter>();
for(WBParameter parameter: ownerParams)
{
parameter.setOwnerExternalKey(ownerExternalKey);
parameter.setKey(null);
parameter.setExternalKey(adminStorage.getUniqueId());
parameter.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
WBParameter newParam = adminStorage.add(parameter);
newParams.add(newParam);
}
String jsonReturn = jsonObjectConverter.JSONStringFromListObjects(newParams);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn.toString(), errors);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_CREATE_RECORD);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
| public void createFromOwner(String fromOwnerExternalKey, String ownerExternalKey, HttpServletRequest request, HttpServletResponse response, String requestUri) throws WBException
{
try
{
Map<String, String> errors = new HashMap<String, String>();
if (ownerExternalKey == null || ownerExternalKey.equals(0L))
{
errors.put("", WBErrors.WBPARAMETER_NO_OWNER_KEY);
}
if (fromOwnerExternalKey == null || fromOwnerExternalKey.equals(0L))
{
errors.put("", WBErrors.WBPARAMETER_NO_FROMOWNER_KEY);
}
if (errors.size()>0)
{
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
List<WBParameter> ownerParams = adminStorage.query(WBParameter.class, "ownerExternalKey", AdminQueryOperator.EQUAL, fromOwnerExternalKey);
List<WBParameter> newParams = new ArrayList<WBParameter>();
for(WBParameter parameter: ownerParams)
{
parameter.setOwnerExternalKey(ownerExternalKey);
parameter.setKey(null);
parameter.setExternalKey(adminStorage.getUniqueId());
parameter.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
WBParameter newParam = adminStorage.add(parameter);
newParams.add(newParam);
}
String jsonReturn = jsonObjectConverter.JSONStringFromListObjects(newParams);
httpServletToolbox.writeBodyResponseAsJson(response, jsonReturn.toString(), errors);
} catch (Exception e)
{
Map<String, String> errors = new HashMap<String, String>();
errors.put("", WBErrors.WB_CANT_CREATE_RECORD);
httpServletToolbox.writeBodyResponseAsJson(response, "", errors);
}
}
|
diff --git a/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/wizards/pages/EntriesPage.java b/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/wizards/pages/EntriesPage.java
index 233eff9ab..bd6c0d9bd 100644
--- a/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/wizards/pages/EntriesPage.java
+++ b/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/wizards/pages/EntriesPage.java
@@ -1,554 +1,556 @@
/*
* Copyright (c) 2005 Borland Software Corporation
*
* 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:
* Artem Tikhomirov (Borland) - initial API and implementation
*/
package org.eclipse.gmf.internal.codegen.wizards.pages;
import java.util.Arrays;
import java.util.Iterator;
import org.eclipse.emf.ecore.ENamedElement;
import org.eclipse.gmf.mappings.FeatureSeqInitializer;
import org.eclipse.gmf.mappings.FeatureValueSpec;
import org.eclipse.gmf.mappings.GMFMapFactory;
import org.eclipse.gmf.mappings.LinkMapping;
import org.eclipse.gmf.mappings.Mapping;
import org.eclipse.gmf.mappings.MappingEntry;
import org.eclipse.gmf.mappings.NodeMapping;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.dialogs.ListDialog;
/**
* @author artem
*
*/
public class EntriesPage extends WizardPage {
private final WizardInput myHolder;
public EntriesPage(WizardInput input) {
super("entriesPage");
this.myHolder = input;
}
protected Mapping getMapInstance() {
return myHolder.getMapping();
}
protected WizardInput getHolder() {
return myHolder;
}
public void createControl(Composite parent) {
setControl(new PageControl(parent));
}
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
((PageControl) getControl()).populate();
}
}
private class PageControl extends Composite {
private Group group = null;
private List nodesList = null;
private Group group1 = null;
private List linksList = null;
private Composite detailsPart = null;
private Group groupStructure = null;
private Group groupEdit = null;
private Group groupVisual = null;
private Composite composite2 = null;
private Composite composite = null;
private Button asNodeButton = null;
private Button asLinkButton = null;
private Button removeButton = null;
private Button changeDetailsButton = null;
private Button restoreButton = null;
private Group groupConstaints = null;
private Label specLabel = null;
private Label initLabel = null;
private Label editFeatureLabel = null;
private Label displayFeatureLabel = null;
private Label diagramElementLabel = null;
private Label metaElementLabel;
private Label containmentLabel;
private Label linkMetaFeatureLabel;
private MappingEntry selectedEntry;
private final ILabelProvider myLabelProvider = new LabelProvider() {
public String getText(Object element) {
if (element instanceof LinkMapping) {
LinkMapping next = (LinkMapping) element;
StringBuffer sb = new StringBuffer();
if (next.getDomainMetaElement() == null) {
sb.append(next.getLinkMetaFeature() == null ? "Link" : next.getLinkMetaFeature().getName());
} else {
sb.append(next.getDomainMetaElement().getName());
}
sb.append(" (");
if (next.getDiagramLink() != null) {
sb.append(next.getDiagramLink().getName());
if (next.getContainmentFeature() != null) {
sb.append("; ");
}
}
if (next.getContainmentFeature() != null) {
sb.append(next.getContainmentFeature().getName());
}
sb.append(")");
return sb.toString();
} else {
NodeMapping next = (NodeMapping) element;
StringBuffer sb = new StringBuffer();
sb.append(next.getDomainMetaElement() == null ? "Node" : next.getDomainMetaElement().getName());
sb.append(" (");
if (next.getDiagramNode() != null) {
sb.append(next.getDiagramNode().getName());
if (next.getContainmentFeature() != null) {
sb.append("; ");
}
}
if (next.getContainmentFeature() != null) {
sb.append(next.getContainmentFeature().getName());
}
sb.append(")");
return sb.toString();
}
}
};
private SelectionListener myListListener = new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
final boolean nodeSelected = e.widget == nodesList;
asLinkButton.setEnabled(nodeSelected);
removeButton.setEnabled(true);
changeDetailsButton.setEnabled(true);
restoreButton.setEnabled(true);
if (nodeSelected) {
asNodeButton.setEnabled(false);
assert nodesList.getSelectionIndex() != -1;
selectedEntry = (NodeMapping) getMapInstance().getNodes().get(nodesList.getSelectionIndex());
refreshNodeDetails();
linksList.deselectAll();
} else {
// e.widget == linksList
assert linksList.getSelectionIndex() != -1;
selectedEntry =(LinkMapping) getMapInstance().getLinks().get(linksList.getSelectionIndex());
asNodeButton.setEnabled(selectedEntry.getDomainMetaElement() != null);
refreshLinkDetails();
nodesList.deselectAll();
}
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
};
public PageControl(Composite parent) {
super(parent, SWT.NONE);
initialize();
}
public void populate() {
populateNodesList();
populateLinksList();
}
private void populateNodesList() {
String[] items = new String[getMapInstance().getNodes().size()];
int i = 0;
for (Iterator it = getMapInstance().getNodes().iterator(); it.hasNext(); i++) {
items[i] = myLabelProvider.getText(it.next());
}
nodesList.setItems(items);
}
private void populateLinksList() {
String[] items = new String[getMapInstance().getLinks().size()];
int i = 0;
for (Iterator it = getMapInstance().getLinks().iterator(); it.hasNext(); i++) {
items[i] = myLabelProvider.getText(it.next());
}
linksList.setItems(items);
}
private void initialize() {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
this.setLayout(gridLayout);
// setSize(new org.eclipse.swt.graphics.Point(990,612));
createNodesList();
createButtonsPane();
createLinksList();
createDetailsPart();
}
private void createNodesList() {
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.verticalAlignment = GridData.FILL;
group = new Group(this, SWT.NONE);
group.setLayout(new FillLayout());
group.setLayoutData(gridData);
group.setText("Nodes");
nodesList = new List(group, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
nodesList.addSelectionListener(myListListener);
}
private void createLinksList() {
GridData gridData1 = new GridData();
gridData1.grabExcessHorizontalSpace = true;
gridData1.horizontalAlignment = GridData.FILL;
gridData1.verticalAlignment = GridData.FILL;
gridData1.grabExcessVerticalSpace = true;
group1 = new Group(this, SWT.NONE);
group1.setLayout(new FillLayout());
group1.setLayoutData(gridData1);
group1.setText("Links");
linksList = new List(group1, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
linksList.addSelectionListener(myListListener);
}
private void createDetailsPart() {
GridData gridData3 = new GridData();
gridData3.horizontalSpan = 5;
gridData3.verticalAlignment = GridData.FILL;
gridData3.grabExcessHorizontalSpace = true;
gridData3.grabExcessVerticalSpace = false;
gridData3.horizontalAlignment = GridData.FILL;
detailsPart = new Composite(this, SWT.NONE);
detailsPart.setLayoutData(gridData3);
GridLayout gridLayout1 = new GridLayout();
gridLayout1.numColumns = 7;
gridLayout1.makeColumnsEqualWidth = true;
detailsPart.setLayout(gridLayout1);
createStructureGroup();
createEditGroup();
changeDetailsButton = new Button(detailsPart, SWT.NONE);
changeDetailsButton.setText("Change...");
changeDetailsButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
MessageDialog.openInformation(getShell(), "Mapping Details", "Please use EMF-generated editor to modify values for a while...");
}
});
GridData gridData8 = new GridData();
gridData8.grabExcessHorizontalSpace = true;
gridData8.verticalAlignment = GridData.CENTER;
gridData8.verticalSpan = 2;
gridData8.horizontalAlignment = GridData.CENTER;
changeDetailsButton.setLayoutData(gridData8);
createVisualGroup();
createConstraintsGroup();
}
private void createStructureGroup() {
groupStructure = new Group(detailsPart, SWT.SHADOW_OUT);
groupStructure.setText("Structure");
groupStructure.setLayoutData(newDetailGroupConstraint());
groupStructure.setLayout(newDetailGroupLayout());
Label l = new Label(groupStructure, SWT.NONE);
l.setText("Element:");
metaElementLabel = new Label(groupStructure, SWT.NONE);
metaElementLabel.setLayoutData(newDetailLabelConstraint());
l = new Label(groupStructure, SWT.NONE);
l.setText("Containment:");
containmentLabel = new Label(groupStructure, SWT.NONE);
containmentLabel.setLayoutData(newDetailLabelConstraint());
l = new Label(groupStructure, SWT.NONE);
l.setText("Target Feature:");
linkMetaFeatureLabel = new Label(groupStructure, SWT.NONE);
linkMetaFeatureLabel.setLayoutData(newDetailLabelConstraint());
}
private void createEditGroup() {
groupEdit = new Group(detailsPart, SWT.NONE);
groupEdit.setText("Edit");
groupEdit.setLayout(newDetailGroupLayout());
groupEdit.setLayoutData(newDetailGroupConstraint());
Label l = new Label(groupEdit, SWT.NONE);
l.setText("In-place edit:");
editFeatureLabel = new Label(groupEdit, SWT.NONE);
editFeatureLabel.setLayoutData(newDetailLabelConstraint());
l = new Label(groupEdit, SWT.NONE);
l.setText("Display feature:");
displayFeatureLabel = new Label(groupEdit, SWT.NONE);
displayFeatureLabel.setLayoutData(newDetailLabelConstraint());
}
private void createVisualGroup() {
groupVisual = new Group(detailsPart, SWT.NONE);
groupVisual.setText("Visual");
groupVisual.setLayoutData(newDetailGroupConstraint());
groupVisual.setLayout(newDetailGroupLayout());
Label l = new Label(groupVisual, SWT.NONE);
l.setText("Diagram Element:");
diagramElementLabel = new Label(groupVisual, SWT.NONE);
diagramElementLabel.setLayoutData(newDetailLabelConstraint());
}
private void createButtonsPane() {
GridData gridData2 = new GridData();
gridData2.horizontalAlignment = GridData.FILL;
gridData2.verticalAlignment = GridData.CENTER;
composite2 = new Composite(this, SWT.NONE);
composite2.setLayout(new FillLayout());
composite2.setLayoutData(gridData2);
createComposite();
}
private void createComposite() {
RowLayout rowLayout = new RowLayout();
rowLayout.type = org.eclipse.swt.SWT.VERTICAL;
rowLayout.justify = true;
rowLayout.marginHeight = 0;
rowLayout.marginWidth = 0;
rowLayout.pack = false;
rowLayout.spacing = 6;
rowLayout.marginLeft = 10;
rowLayout.marginRight = 10;
rowLayout.fill = false;
composite = new Composite(composite2, SWT.NONE);
composite.setLayout(rowLayout);
asNodeButton = new Button(composite, SWT.NONE);
asNodeButton.setText("As node <--");
asNodeButton.setEnabled(false);
asNodeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
NodeMapping nm = GMFMapFactory.eINSTANCE.createNodeMapping();
nm.setDomainMetaElement(selectedEntry.getDomainMetaElement());
nm.setContainmentFeature(selectedEntry.getContainmentFeature());
nm.setDomainInitializer(selectedEntry.getDomainInitializer());
nm.setDomainSpecialization(selectedEntry.getDomainSpecialization());
final LinkMapping linkMapping = (LinkMapping) selectedEntry;
nm.setEditFeature(linkMapping.getLabelEditFeature());
nm.setTool(linkMapping.getTool());
nm.setContextMenu(linkMapping.getContextMenu());
nm.setAppearanceStyle(linkMapping.getAppearanceStyle());
getMapInstance().getNodes().add(nm);
+ getMapInstance().getLinks().remove(selectedEntry);
linksList.remove(linksList.getSelectionIndex());
nodesList.add(myLabelProvider.getText(nm));
nodesList.select(nodesList.getItemCount() - 1);
}
});
asLinkButton = new Button(composite, SWT.NONE);
asLinkButton.setText("As link -->");
asLinkButton.setEnabled(false);
asLinkButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
LinkMapping lm = GMFMapFactory.eINSTANCE.createLinkMapping();
lm.setDomainMetaElement(selectedEntry.getDomainMetaElement());
lm.setContainmentFeature(selectedEntry.getContainmentFeature());
lm.setDomainInitializer(selectedEntry.getDomainInitializer());
lm.setDomainSpecialization(selectedEntry.getDomainSpecialization());
final NodeMapping nodeMapping = (NodeMapping) selectedEntry;
lm.setLabelEditFeature(nodeMapping.getEditFeature());
lm.setTool(nodeMapping.getTool());
lm.setContextMenu(nodeMapping.getContextMenu());
lm.setAppearanceStyle(nodeMapping.getAppearanceStyle());
getMapInstance().getLinks().add(lm);
+ getMapInstance().getNodes().remove(selectedEntry);
nodesList.remove(nodesList.getSelectionIndex());
linksList.add(myLabelProvider.getText(lm));
linksList.select(linksList.getItemCount() - 1);
}
});
removeButton = new Button(composite, SWT.NONE);
removeButton.setText("Remove");
removeButton.setEnabled(false);
removeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (nodesList.getSelectionIndex() != -1) {
int i = nodesList.getSelectionIndex();
nodesList.remove(i);
getMapInstance().getNodes().remove(i);
if (i == nodesList.getItemCount() && i > 0) {
i--;
}
nodesList.select(i);
}
if (linksList.getSelectionIndex() != -1) {
int i = linksList.getSelectionIndex();
linksList.remove(i);
getMapInstance().getLinks().remove(i);
if (i == linksList.getItemCount() && i > 0) {
i--;
}
linksList.select(i);
}
}
});
restoreButton = new Button(composite, SWT.NONE);
restoreButton.setText("Restore...");
restoreButton.setEnabled(false);
restoreButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ListDialog d = new ListDialog(getShell());
d.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public void dispose() {
}
});
d.setLabelProvider(PageControl.this.myLabelProvider);
final boolean isNodeMap = selectedEntry instanceof NodeMapping;
if (isNodeMap) {
d.setInput(getHolder().nodeCandidates());
} else {
d.setInput(getHolder().linkCandidates());
}
if (d.open() == ListDialog.OK) {
if (isNodeMap) {
getMapInstance().getNodes().addAll(Arrays.asList(d.getResult()));
nodesList.removeAll();
populateNodesList();
} else {
getMapInstance().getLinks().addAll(Arrays.asList(d.getResult()));
linksList.removeAll();
populateLinksList();
}
}
}
});
}
private void createConstraintsGroup() {
groupConstaints = new Group(detailsPart, SWT.NONE);
groupConstaints.setText("Constraints");
groupConstaints.setLayout(newDetailGroupLayout());
groupConstaints.setLayoutData(newDetailGroupConstraint());
Label label = new Label(groupConstaints, SWT.NONE);
label.setText("Specialization:");
specLabel = new Label(groupConstaints, SWT.NONE);
specLabel.setLayoutData(newDetailLabelConstraint());
label = new Label(groupConstaints, SWT.NONE);
label.setText("Initializer:");
initLabel = new Label(groupConstaints, SWT.NONE);
initLabel.setLayoutData(newDetailLabelConstraint());
// TODO link creation constraints
}
private GridLayout newDetailGroupLayout() {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
gridLayout.makeColumnsEqualWidth = true;
return gridLayout;
}
private GridData newDetailGroupConstraint() {
GridData groupGridData = new GridData();
groupGridData.horizontalAlignment = GridData.FILL;
groupGridData.grabExcessHorizontalSpace = true;
groupGridData.grabExcessVerticalSpace = true;
groupGridData.horizontalSpan = 3;
groupGridData.verticalAlignment = GridData.FILL;
return groupGridData;
}
private GridData newDetailLabelConstraint() {
GridData labelGridData = new GridData();
labelGridData.horizontalSpan = 2;
labelGridData.grabExcessHorizontalSpace = true;
labelGridData.horizontalAlignment = GridData.FILL;
return labelGridData;
}
private void refreshCommonDetails() {
affix(metaElementLabel, selectedEntry.getDomainMetaElement());
affix(containmentLabel, selectedEntry.getContainmentFeature());
refreshDomainSpecialization();
refreshDomainInitializer();
}
private void refreshDomainSpecialization() {
if (selectedEntry.getDomainSpecialization() == null) {
specLabel.setText("");
return;
}
specLabel.setText(selectedEntry.getDomainSpecialization().getBody());
}
private void refreshDomainInitializer() {
if (selectedEntry.getDomainInitializer() == null || false == selectedEntry.getDomainInitializer() instanceof FeatureSeqInitializer) {
initLabel.setText("");
return;
}
FeatureSeqInitializer fsi = (FeatureSeqInitializer) selectedEntry.getDomainInitializer();
StringBuffer sb = new StringBuffer();
for (Iterator it = fsi.getInitializers().iterator(); it.hasNext();) {
FeatureValueSpec next = (FeatureValueSpec) it.next();
sb.append(next.getFeature().getName());
sb.append("; ");
}
initLabel.setText(sb.toString());
}
private void affix(Label l, ENamedElement el) {
if (el != null) {
l.setText(el.getName());
} else {
l.setText("");
}
}
private void refreshNodeDetails() {
refreshCommonDetails();
NodeMapping m = (NodeMapping) selectedEntry;
if (m.getDiagramNode() != null) {
diagramElementLabel.setText(m.getDiagramNode().getName());
} else {
diagramElementLabel.setText("");
}
affix(editFeatureLabel, m.getEditFeature());
linkMetaFeatureLabel.setText("");
}
private void refreshLinkDetails() {
refreshCommonDetails();
LinkMapping l = (LinkMapping) selectedEntry;
if (l.getDiagramLink() != null) {
diagramElementLabel.setText(l.getDiagramLink().getName());
} else {
diagramElementLabel.setText("");
}
affix(editFeatureLabel, l.getLabelEditFeature());
affix(displayFeatureLabel, l.getLabelDisplayFeature());
affix(linkMetaFeatureLabel, l.getLinkMetaFeature());
}
}
}
| false | true | private void createComposite() {
RowLayout rowLayout = new RowLayout();
rowLayout.type = org.eclipse.swt.SWT.VERTICAL;
rowLayout.justify = true;
rowLayout.marginHeight = 0;
rowLayout.marginWidth = 0;
rowLayout.pack = false;
rowLayout.spacing = 6;
rowLayout.marginLeft = 10;
rowLayout.marginRight = 10;
rowLayout.fill = false;
composite = new Composite(composite2, SWT.NONE);
composite.setLayout(rowLayout);
asNodeButton = new Button(composite, SWT.NONE);
asNodeButton.setText("As node <--");
asNodeButton.setEnabled(false);
asNodeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
NodeMapping nm = GMFMapFactory.eINSTANCE.createNodeMapping();
nm.setDomainMetaElement(selectedEntry.getDomainMetaElement());
nm.setContainmentFeature(selectedEntry.getContainmentFeature());
nm.setDomainInitializer(selectedEntry.getDomainInitializer());
nm.setDomainSpecialization(selectedEntry.getDomainSpecialization());
final LinkMapping linkMapping = (LinkMapping) selectedEntry;
nm.setEditFeature(linkMapping.getLabelEditFeature());
nm.setTool(linkMapping.getTool());
nm.setContextMenu(linkMapping.getContextMenu());
nm.setAppearanceStyle(linkMapping.getAppearanceStyle());
getMapInstance().getNodes().add(nm);
linksList.remove(linksList.getSelectionIndex());
nodesList.add(myLabelProvider.getText(nm));
nodesList.select(nodesList.getItemCount() - 1);
}
});
asLinkButton = new Button(composite, SWT.NONE);
asLinkButton.setText("As link -->");
asLinkButton.setEnabled(false);
asLinkButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
LinkMapping lm = GMFMapFactory.eINSTANCE.createLinkMapping();
lm.setDomainMetaElement(selectedEntry.getDomainMetaElement());
lm.setContainmentFeature(selectedEntry.getContainmentFeature());
lm.setDomainInitializer(selectedEntry.getDomainInitializer());
lm.setDomainSpecialization(selectedEntry.getDomainSpecialization());
final NodeMapping nodeMapping = (NodeMapping) selectedEntry;
lm.setLabelEditFeature(nodeMapping.getEditFeature());
lm.setTool(nodeMapping.getTool());
lm.setContextMenu(nodeMapping.getContextMenu());
lm.setAppearanceStyle(nodeMapping.getAppearanceStyle());
getMapInstance().getLinks().add(lm);
nodesList.remove(nodesList.getSelectionIndex());
linksList.add(myLabelProvider.getText(lm));
linksList.select(linksList.getItemCount() - 1);
}
});
removeButton = new Button(composite, SWT.NONE);
removeButton.setText("Remove");
removeButton.setEnabled(false);
removeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (nodesList.getSelectionIndex() != -1) {
int i = nodesList.getSelectionIndex();
nodesList.remove(i);
getMapInstance().getNodes().remove(i);
if (i == nodesList.getItemCount() && i > 0) {
i--;
}
nodesList.select(i);
}
if (linksList.getSelectionIndex() != -1) {
int i = linksList.getSelectionIndex();
linksList.remove(i);
getMapInstance().getLinks().remove(i);
if (i == linksList.getItemCount() && i > 0) {
i--;
}
linksList.select(i);
}
}
});
restoreButton = new Button(composite, SWT.NONE);
restoreButton.setText("Restore...");
restoreButton.setEnabled(false);
restoreButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ListDialog d = new ListDialog(getShell());
d.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public void dispose() {
}
});
d.setLabelProvider(PageControl.this.myLabelProvider);
final boolean isNodeMap = selectedEntry instanceof NodeMapping;
if (isNodeMap) {
d.setInput(getHolder().nodeCandidates());
} else {
d.setInput(getHolder().linkCandidates());
}
if (d.open() == ListDialog.OK) {
if (isNodeMap) {
getMapInstance().getNodes().addAll(Arrays.asList(d.getResult()));
nodesList.removeAll();
populateNodesList();
} else {
getMapInstance().getLinks().addAll(Arrays.asList(d.getResult()));
linksList.removeAll();
populateLinksList();
}
}
}
});
}
| private void createComposite() {
RowLayout rowLayout = new RowLayout();
rowLayout.type = org.eclipse.swt.SWT.VERTICAL;
rowLayout.justify = true;
rowLayout.marginHeight = 0;
rowLayout.marginWidth = 0;
rowLayout.pack = false;
rowLayout.spacing = 6;
rowLayout.marginLeft = 10;
rowLayout.marginRight = 10;
rowLayout.fill = false;
composite = new Composite(composite2, SWT.NONE);
composite.setLayout(rowLayout);
asNodeButton = new Button(composite, SWT.NONE);
asNodeButton.setText("As node <--");
asNodeButton.setEnabled(false);
asNodeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
NodeMapping nm = GMFMapFactory.eINSTANCE.createNodeMapping();
nm.setDomainMetaElement(selectedEntry.getDomainMetaElement());
nm.setContainmentFeature(selectedEntry.getContainmentFeature());
nm.setDomainInitializer(selectedEntry.getDomainInitializer());
nm.setDomainSpecialization(selectedEntry.getDomainSpecialization());
final LinkMapping linkMapping = (LinkMapping) selectedEntry;
nm.setEditFeature(linkMapping.getLabelEditFeature());
nm.setTool(linkMapping.getTool());
nm.setContextMenu(linkMapping.getContextMenu());
nm.setAppearanceStyle(linkMapping.getAppearanceStyle());
getMapInstance().getNodes().add(nm);
getMapInstance().getLinks().remove(selectedEntry);
linksList.remove(linksList.getSelectionIndex());
nodesList.add(myLabelProvider.getText(nm));
nodesList.select(nodesList.getItemCount() - 1);
}
});
asLinkButton = new Button(composite, SWT.NONE);
asLinkButton.setText("As link -->");
asLinkButton.setEnabled(false);
asLinkButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
LinkMapping lm = GMFMapFactory.eINSTANCE.createLinkMapping();
lm.setDomainMetaElement(selectedEntry.getDomainMetaElement());
lm.setContainmentFeature(selectedEntry.getContainmentFeature());
lm.setDomainInitializer(selectedEntry.getDomainInitializer());
lm.setDomainSpecialization(selectedEntry.getDomainSpecialization());
final NodeMapping nodeMapping = (NodeMapping) selectedEntry;
lm.setLabelEditFeature(nodeMapping.getEditFeature());
lm.setTool(nodeMapping.getTool());
lm.setContextMenu(nodeMapping.getContextMenu());
lm.setAppearanceStyle(nodeMapping.getAppearanceStyle());
getMapInstance().getLinks().add(lm);
getMapInstance().getNodes().remove(selectedEntry);
nodesList.remove(nodesList.getSelectionIndex());
linksList.add(myLabelProvider.getText(lm));
linksList.select(linksList.getItemCount() - 1);
}
});
removeButton = new Button(composite, SWT.NONE);
removeButton.setText("Remove");
removeButton.setEnabled(false);
removeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (nodesList.getSelectionIndex() != -1) {
int i = nodesList.getSelectionIndex();
nodesList.remove(i);
getMapInstance().getNodes().remove(i);
if (i == nodesList.getItemCount() && i > 0) {
i--;
}
nodesList.select(i);
}
if (linksList.getSelectionIndex() != -1) {
int i = linksList.getSelectionIndex();
linksList.remove(i);
getMapInstance().getLinks().remove(i);
if (i == linksList.getItemCount() && i > 0) {
i--;
}
linksList.select(i);
}
}
});
restoreButton = new Button(composite, SWT.NONE);
restoreButton.setText("Restore...");
restoreButton.setEnabled(false);
restoreButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ListDialog d = new ListDialog(getShell());
d.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public void dispose() {
}
});
d.setLabelProvider(PageControl.this.myLabelProvider);
final boolean isNodeMap = selectedEntry instanceof NodeMapping;
if (isNodeMap) {
d.setInput(getHolder().nodeCandidates());
} else {
d.setInput(getHolder().linkCandidates());
}
if (d.open() == ListDialog.OK) {
if (isNodeMap) {
getMapInstance().getNodes().addAll(Arrays.asList(d.getResult()));
nodesList.removeAll();
populateNodesList();
} else {
getMapInstance().getLinks().addAll(Arrays.asList(d.getResult()));
linksList.removeAll();
populateLinksList();
}
}
}
});
}
|
diff --git a/AceGWT/src/edu/ycp/cs/dh/acegwt/client/ace/AceEditor.java b/AceGWT/src/edu/ycp/cs/dh/acegwt/client/ace/AceEditor.java
index 986d8a3..27877cd 100644
--- a/AceGWT/src/edu/ycp/cs/dh/acegwt/client/ace/AceEditor.java
+++ b/AceGWT/src/edu/ycp/cs/dh/acegwt/client/ace/AceEditor.java
@@ -1,378 +1,378 @@
// Copyright (c) 2011-2012, David H. Hovemeyer <[email protected]>
//
// 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 edu.ycp.cs.dh.acegwt.client.ace;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.RequiresResize;
/**
* A GWT widget for the Ajax.org Code Editor (ACE).
*
* @see <a href="http://ace.ajax.org/">Ajax.org Code Editor</a>
*/
public class AceEditor extends Composite implements RequiresResize {
// Used to generate unique element ids for Ace widgets.
private static int nextId = 0;
private final String elementId;
private JavaScriptObject editor;
private JsArray<AceAnnotation> annotations = JavaScriptObject.createArray().cast();
private Element divElement;
/**
* Preferred constructor.
*/
public AceEditor() {
elementId = "_aceGWT" + nextId;
nextId++;
FlowPanel div = new FlowPanel();
div.getElement().setId(elementId);
initWidget(div);
divElement = div.getElement();
}
/**
* Do not use this constructor: just use the default constructor.
*/
@Deprecated
public AceEditor(boolean unused) {
this();
}
/**
* Call this method to start the editor.
* Make sure that the widget has been attached to the DOM tree
* before calling this method.
*/
public native void startEditor() /*-{
- var editor = $wnd.ace.edit([email protected]::::divElement);
+ var editor = $wnd.ace.edit([email protected]::divElement);
editor.getSession().setUseWorker(false);
[email protected]::editor = editor;
// I have been noticing sporadic failures of the editor
// to display properly and receive key/mouse events.
// Try to force the editor to resize and display itself fully. See:
// https://groups.google.com/group/ace-discuss/browse_thread/thread/237262b521dcea33
editor.resize();
[email protected]::redisplay();
}-*/;
/**
* Call this to force the editor contents to be redisplayed.
* There seems to be a problem when an AceEditor is embedded in a LayoutPanel:
* the editor contents don't appear, and it refuses to accept focus
* and mouse events, until the browser window is resized.
* Calling this method works around the problem by forcing
* the underlying editor to redisplay itself fully. (?)
*/
public native void redisplay() /*-{
var editor = [email protected]::editor;
editor.renderer.onResize(true);
editor.renderer.updateFull();
editor.resize();
editor.focus();
}-*/;
/**
* Cleans up the entire editor.
*/
public native void destroy() /*-{
var editor = [email protected]::editor;
editor.destroy();
}-*/;
/**
* Set the theme.
*
* @param theme the theme (one of the values in the {@link AceEditorTheme}
* enumeration)
*/
public void setTheme(final AceEditorTheme theme) {
setThemeByName(theme.getName());
}
/**
* Set the theme by name.
*
* @param themeName the theme name (e.g., "twilight")
*/
public native void setThemeByName(String themeName) /*-{
var editor = [email protected]::editor;
editor.setTheme("ace/theme/" + themeName);
}-*/;
/**
* Set the mode.
*
* @param mode the mode (one of the values in the
* {@link AceEditorMode} enumeration)
*/
public void setMode(final AceEditorMode mode) {
setModeByName(mode.getName());
}
/**
* Set the mode by name.
*
* @param shortModeName name of mode (e.g., "eclipse")
*/
public native void setModeByName(String shortModeName) /*-{
var editor = [email protected]::editor;
var modeName = "ace/mode/" + shortModeName;
var TheMode = $wnd.require(modeName).Mode;
editor.getSession().setMode(new TheMode());
}-*/;
/**
* Register a handler for change events generated by the editor.
*
* @param callback the change event handler
*/
public native void addOnChangeHandler(AceEditorCallback callback) /*-{
var editor = [email protected]::editor;
editor.getSession().on("change", function(e) {
[email protected]::invokeAceCallback(Lcom/google/gwt/core/client/JavaScriptObject;)(e);
});
}-*/;
/**
* Register a handler for cursor position change events generated by the editor.
*
* @param callback the cursor position change event handler
*/
public native void addOnCursorPositionChangeHandler(AceEditorCallback callback) /*-{
var editor = [email protected]::editor;
editor.getSession().selection.on("changeCursor", function(e) {
[email protected]::invokeAceCallback(Lcom/google/gwt/core/client/JavaScriptObject;)(e);
});
}-*/;
/**
* Set font size.
*/
public native void setFontSize(String fontSize) /*-{
var elementId = [email protected]::elementId;
var elt = $doc.getElementById(elementId);
elt.style.fontSize = fontSize;
}-*/;
/**
* Get the complete text in the editor as a String.
*
* @return the text in the editor
*/
public native String getText() /*-{
var editor = [email protected]::editor;
return editor.getSession().getValue();
}-*/;
/**
* Set the complete text in the editor from a String.
*
* @param text the text to set in the editor
*/
public native void setText(String text) /*-{
var editor = [email protected]::editor;
editor.getSession().setValue(text);
}-*/;
/**
* Insert given text at the cursor.
*
* @param text text to insert at the cursor
*/
public native void insertAtCursor(String text) /*-{
var editor = [email protected]::editor;
editor.insert(text);
}-*/;
/**
* Get the current cursor position.
*
* @return the current cursor position
*/
public native AceEditorCursorPosition getCursorPosition() /*-{
var editor = [email protected]::editor;
var pos = editor.getCursorPosition();
return [email protected]::getCursorPositionImpl(DD)(pos.row, pos.column);
}-*/;
private AceEditorCursorPosition getCursorPositionImpl(final double row, final double column) {
return new AceEditorCursorPosition((int) row, (int) column);
}
/**
* Set whether or not soft tabs should be used.
*
* @param useSoftTabs true if soft tabs should be used, false otherwise
*/
public native void setUseSoftTabs(boolean useSoftTabs) /*-{
var editor = [email protected]::editor;
editor.getSession().setUseSoftTabs(useSoftTabs);
}-*/;
/**
* Set tab size. (Default is 4.)
*
* @param tabSize the tab size to set
*/
public native void setTabSize(int tabSize) /*-{
var editor = [email protected]::editor;
editor.getSession().setTabSize(tabSize);
}-*/;
/**
* Go to given line.
*
* @param line the line to go to
*/
public native void gotoLine(int line) /*-{
var editor = [email protected]::editor;
editor.gotoLine(line);
}-*/;
/**
* Set whether or not the horizontal scrollbar is always visible.
*
* @param hScrollBarAlwaysVisible true if the horizontal scrollbar is always
* visible, false if it is hidden when not needed
*/
public native void setHScrollBarAlwaysVisible(boolean hScrollBarAlwaysVisible) /*-{
var editor = [email protected]::editor;
editor.renderer.setHScrollBarAlwaysVisible(hScrollBarAlwaysVisible);
}-*/;
/**
* Set whether or not the gutter is shown.
*
* @param showGutter true if the gutter should be shown, false if it should be hidden
*/
public native void setShowGutter(boolean showGutter) /*-{
var editor = [email protected]::editor;
editor.renderer.setShowGutter(showGutter);
}-*/;
/**
* Set or unset read-only mode.
*
* @param readOnly true if editor should be set to readonly, false if the
* editor should be set to read-write
*/
public native void setReadOnly(boolean readOnly) /*-{
var editor = [email protected]::editor;
editor.setReadOnly(readOnly);
}-*/;
/**
* Set or unset highlighting of currently selected word.
*
* @param highlightSelectedWord true to highlight currently selected word, false otherwise
*/
public native void setHighlightSelectedWord(boolean highlightSelectedWord) /*-{
var editor = [email protected]::editor;
editor.setHighlightSelectedWord(highlightSelectedWord);
}-*/;
/**
* Set or unset the visibility of the print margin.
*
* @param showPrintMargin true if the print margin should be shown, false otherwise
*/
public native void setShowPrintMargin(boolean showPrintMargin) /*-{
var editor = [email protected]::editor;
editor.renderer.setShowPrintMargin(showPrintMargin);
}-*/;
/**
* Add an annotation to a the local <code>annotations</code> JsArray<AceAnnotation>, but does not set it on the editor
*
* @param row to which the annotation should be added
* @param column to which the annotation applies
* @param text to display as a tooltip with the annotation
* @param type to be displayed (one of the values in the
* {@link AceAnnotationType} enumeration)
*/
public void addAnnotation(final int row, final int column, final String text, final AceAnnotationType type) {
annotations.push(AceAnnotation.create(row, column, text, type.getName()));
}
/**
* Set any annotations which have been added via <code>addAnnotation</code> on the editor
*/
public native void setAnnotations() /*-{
var editor = [email protected]::editor;
var annotations = [email protected]::annotations;
editor.getSession().setAnnotations(annotations);
}-*/;
/**
* Clear any annotations from the editor and reset the local <code>annotations</code> JsArray<AceAnnotation>
*/
public native void clearAnnotations() /*-{
var editor = [email protected]::editor;
editor.getSession().clearAnnotations();
[email protected]::resetAnnotations()();
}-*/;
/**
* Reset any annotations in the local <code>annotations</code> JsArray<AceAnnotation>
*/
private void resetAnnotations() {
annotations = JavaScriptObject.createArray().cast();
}
/**
* Remove a command from the editor.
*
* @param command the command (one of the values in the
* {@link AceCommand} enumeration)
*/
public void removeCommand(final AceCommand command) {
removeCommandByName(command.getName());
}
/**
* Remove commands, that may not me required, from the editor
*
* @param command to be removed, one of
* "gotoline", "findnext", "findprevious", "find", "replace", "replaceall"
*/
public native void removeCommandByName(String command) /*-{
var editor = [email protected]::editor;
editor.commands.removeCommand(command);
}-*/;
/* (non-Javadoc)
* @see com.google.gwt.user.client.ui.ResizeComposite#onResize()
*/
@Override
public void onResize() {
redisplay();
}
}
| true | true | public native void startEditor() /*-{
var editor = $wnd.ace.edit([email protected]::::divElement);
editor.getSession().setUseWorker(false);
[email protected]::editor = editor;
// I have been noticing sporadic failures of the editor
// to display properly and receive key/mouse events.
// Try to force the editor to resize and display itself fully. See:
// https://groups.google.com/group/ace-discuss/browse_thread/thread/237262b521dcea33
editor.resize();
[email protected]::redisplay();
}-*/;
| public native void startEditor() /*-{
var editor = $wnd.ace.edit([email protected]::divElement);
editor.getSession().setUseWorker(false);
[email protected]::editor = editor;
// I have been noticing sporadic failures of the editor
// to display properly and receive key/mouse events.
// Try to force the editor to resize and display itself fully. See:
// https://groups.google.com/group/ace-discuss/browse_thread/thread/237262b521dcea33
editor.resize();
[email protected]::redisplay();
}-*/;
|
diff --git a/modules/plugin/imagemosaic/src/main/java/org/geotools/gce/imagemosaic/RasterLayerResponse.java b/modules/plugin/imagemosaic/src/main/java/org/geotools/gce/imagemosaic/RasterLayerResponse.java
index 6f2053e12..7e2431e48 100644
--- a/modules/plugin/imagemosaic/src/main/java/org/geotools/gce/imagemosaic/RasterLayerResponse.java
+++ b/modules/plugin/imagemosaic/src/main/java/org/geotools/gce/imagemosaic/RasterLayerResponse.java
@@ -1,1219 +1,1219 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2007-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.gce.imagemosaic;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageReadParam;
import javax.measure.unit.Unit;
import javax.media.jai.BorderExtender;
import javax.media.jai.ImageLayout;
import javax.media.jai.Interpolation;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.ROI;
import javax.media.jai.ROIShape;
import javax.media.jai.RenderedOp;
import javax.media.jai.TileCache;
import javax.media.jai.TileScheduler;
import javax.media.jai.operator.AffineDescriptor;
import javax.media.jai.operator.ConstantDescriptor;
import javax.media.jai.operator.MosaicDescriptor;
import org.geotools.coverage.Category;
import org.geotools.coverage.GridSampleDimension;
import org.geotools.coverage.TypeMap;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.grid.GridEnvelope2D;
import org.geotools.data.DataSourceException;
import org.geotools.data.Query;
import org.geotools.data.QueryCapabilities;
import org.geotools.factory.Hints;
import org.geotools.feature.visitor.MaxVisitor;
import org.geotools.filter.IllegalFilterException;
import org.geotools.filter.SortByImpl;
import org.geotools.gce.imagemosaic.OverviewsController.OverviewLevel;
import org.geotools.gce.imagemosaic.catalog.GranuleCatalogVisitor;
import org.geotools.geometry.Envelope2D;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.image.ImageWorker;
import org.geotools.referencing.CRS;
import org.geotools.referencing.operation.builder.GridToEnvelopeMapper;
import org.geotools.referencing.operation.transform.AffineTransform2D;
import org.geotools.resources.coverage.CoverageUtilities;
import org.geotools.resources.coverage.FeatureUtilities;
import org.geotools.resources.i18n.Vocabulary;
import org.geotools.resources.i18n.VocabularyKeys;
import org.geotools.resources.image.ImageUtilities;
import org.geotools.util.Converters;
import org.geotools.util.NumberRange;
import org.geotools.util.SimpleInternationalString;
import org.opengis.coverage.ColorInterpretation;
import org.opengis.coverage.SampleDimension;
import org.opengis.coverage.SampleDimensionType;
import org.opengis.coverage.grid.GridCoverage;
import org.opengis.feature.Feature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.filter.PropertyIsEqualTo;
import org.opengis.filter.expression.Expression;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
import org.opengis.geometry.BoundingBox;
import org.opengis.referencing.datum.PixelInCell;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.MathTransform1D;
import org.opengis.referencing.operation.MathTransform2D;
import org.opengis.referencing.operation.TransformException;
import org.opengis.util.InternationalString;
import com.sun.media.jai.codecimpl.util.ImagingException;
import com.vividsolutions.jts.geom.Geometry;
/**
* A RasterLayerResponse. An instance of this class is produced everytime a
* requestCoverage is called to a reader.
*
* @author Simone Giannecchini, GeoSolutions
* @author Daniele Romagnoli, GeoSolutions
* @author Stefan Alfons Krueger (alfonx), Wikisquare.de : Support for jar:file:foo.jar/bar.properties URLs
*/
class RasterLayerResponse{
/**
* Simple placeholder class to store the result of a Granule Loading
* which comprises of a raster as well as a {@link ROIShape} for its footprint.
*
* @author Daniele Romagnoli, GeoSolutions S.A.S.
*
*/
static class GranuleLoadingResult {
RenderedImage loadedImage;
ROIShape footprint;
public ROIShape getFootprint() {
return footprint;
}
public RenderedImage getRaster() {
return loadedImage;
}
GranuleLoadingResult(RenderedImage loadedImage, ROIShape inclusionArea) {
this.loadedImage = loadedImage;
this.footprint = inclusionArea;
}
}
private static final class SimplifiedGridSampleDimension extends GridSampleDimension implements SampleDimension{
/**
*
*/
private static final long serialVersionUID = 2227219522016820587L;
private double nodata;
private double minimum;
private double maximum;
private double scale;
private double offset;
private Unit<?> unit;
private SampleDimensionType type;
private ColorInterpretation color;
private Category bkg;
public SimplifiedGridSampleDimension(
CharSequence description,
SampleDimensionType type,
ColorInterpretation color,
double nodata,
double minimum,
double maximum,
double scale,
double offset,
Unit<?> unit) {
super(description,!Double.isNaN(nodata)?
new Category[]{new Category(Vocabulary
.formatInternational(VocabularyKeys.NODATA), new Color[]{new Color(0, 0, 0, 0)} , NumberRange
.create(nodata, nodata), NumberRange
.create(nodata, nodata))}:null,unit);
this.nodata=nodata;
this.minimum=minimum;
this.maximum=maximum;
this.scale=scale;
this.offset=offset;
this.unit=unit;
this.type=type;
this.color=color;
this.bkg=new Category("Background", Utils.TRANSPARENT, 0);
}
@Override
public double getMaximumValue() {
return maximum;
}
@Override
public double getMinimumValue() {
return minimum;
}
@Override
public double[] getNoDataValues() throws IllegalStateException {
return new double[]{nodata};
}
@Override
public double getOffset() throws IllegalStateException {
return offset;
}
@Override
public NumberRange<? extends Number> getRange() {
return super.getRange();
}
@Override
public SampleDimensionType getSampleDimensionType() {
return type;
}
@Override
public MathTransform1D getSampleToGeophysics() {
return super.getSampleToGeophysics();
}
@Override
public Unit<?> getUnits() {
return unit;
}
@Override
public double getScale() {
return scale;
}
@Override
public ColorInterpretation getColorInterpretation() {
return color;
}
@Override
public Category getBackground() {
return bkg;
}
@Override
public InternationalString[] getCategoryNames()
throws IllegalStateException {
return new InternationalString[]{SimpleInternationalString.wrap("Background")};
}
}
/**
* My specific {@link MaxVisitor} that keeps track of the feature used for the maximum.
* @author Simone Giannecchini, GeoSolutions SAS
*
*/
public static class MaxVisitor2 extends MaxVisitor{
@SuppressWarnings("unchecked")
private Comparable oldValue;
private int oldNanCount;
private int oldNullCount;
private Feature targetFeature=null;
public MaxVisitor2(Expression expr) throws IllegalFilterException {
super(expr);
}
public MaxVisitor2(int attributeTypeIndex, SimpleFeatureType type)
throws IllegalFilterException {
super(attributeTypeIndex, type);
}
public Feature getTargetFeature() {
return targetFeature;
}
public MaxVisitor2(String attrName, SimpleFeatureType type)
throws IllegalFilterException {
super(attrName, type);
}
public MaxVisitor2(String attributeTypeName) {
super(attributeTypeName);
}
@Override
public void reset() {
super.reset();
this.oldValue=null;
this.targetFeature=null;
}
@Override
public void setValue(Object result) {
super.setValue(result);
this.oldValue=null;
this.targetFeature=null;
}
@SuppressWarnings("unchecked")
@Override
public void visit(Feature feature) {
super.visit(feature);
// if we got a NAN let's leave
final int nanCount=getNaNCount();
if(oldNanCount!=nanCount)
{
oldNanCount=nanCount;
return;
}
// if we got a null let's leave
final int nullCount=getNullCount();
if(oldNullCount!=nullCount)
{
oldNullCount=nullCount;
return;
}
// check if we got a real value
final Comparable max=getMax();
if ( oldValue==null||max.compareTo(oldValue) != 0) {
targetFeature=feature;
oldValue=max;
}
}
}
/**
* This class is responsible for putting together the granules for the final mosaic.
*
* @author Simone Giannecchini, GeoSolutions SAS
*
*/
class MosaicBuilder implements GranuleCatalogVisitor{
/**
* Default {@link Constructor}
*/
public MosaicBuilder() {
}
private final List<Future<GranuleLoadingResult>> tasks= new ArrayList<Future<GranuleLoadingResult>>();
private int granulesNumber;
private List<ROI> rois = new ArrayList<ROI>();
private Color inputTransparentColor;
private PlanarImage[] alphaChannels;
private RasterLayerRequest request;
private ROI[] sourceRoi;
private double[][] sourceThreshold;
private boolean doInputTransparency;
private List<RenderedImage> sources = new ArrayList<RenderedImage>();
public RenderedImage[] getSourcesAsArray() {
RenderedImage []imageSources = new RenderedImage[sources.size()];
sources.toArray(imageSources);
return imageSources;
}
public void visit(GranuleDescriptor granuleDescriptor, Object o) {
//
// load raster data
//
//create a granuleDescriptor loader
final Geometry bb = JTS.toGeometry((BoundingBox)mosaicBBox);
final Geometry inclusionGeometry = granuleDescriptor.inclusionGeometry;
if (!footprintManagement || inclusionGeometry == null || footprintManagement && inclusionGeometry.intersects(bb)){
final GranuleLoader loader = new GranuleLoader(baseReadParameters, imageChoice, mosaicBBox, finalWorldToGridCorner, granuleDescriptor, request, hints);
if (multithreadingAllowed && rasterManager.parent.multiThreadedLoader != null)
tasks.add(rasterManager.parent.multiThreadedLoader.submit(loader));
else
tasks.add(new FutureTask<GranuleLoadingResult>(loader));
granulesNumber++;
}
if(granulesNumber>request.getMaximumNumberOfGranules())
throw new IllegalStateException("The maximum number of allowed granules ("+request.getMaximumNumberOfGranules()+")has been exceeded.");
}
public void produce(){
// reusable parameters
alphaChannels = new PlanarImage[granulesNumber];
int granuleIndex=0;
inputTransparentColor = request.getInputTransparentColor();
doInputTransparency = inputTransparentColor != null&&!footprintManagement;
// execute them all
boolean firstGranule=true;
int[] alphaIndex=null;
for (Future<GranuleLoadingResult> future :tasks) {
final RenderedImage loadedImage;
final GranuleLoadingResult result;
try {
if(!multithreadingAllowed)
{
//run the loading in this thread
final FutureTask<GranuleLoadingResult> task=(FutureTask<GranuleLoadingResult>) future;
task.run();
}
result = future.get();
if (result == null) {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE, "Unable to load the raster for granule "
+ granuleIndex + " with request " + request.toString());
continue;
}
loadedImage = result.getRaster();
if(loadedImage==null)
{
if(LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE,"Unable to load the raster for granuleDescriptor " +granuleIndex+ " with request "+request.toString());
continue;
}
if(firstGranule){
//
// We check here if the images have an alpha channel or some
// other sort of transparency. In case we have transparency
// I also save the index of the transparent channel.
//
// Specifically, I have to check if the loaded image have
// transparency, because if we do a ROI and/or we have a
// transparent color to set we have to remove it.
//
final ColorModel cm = loadedImage.getColorModel();
alphaIn = cm.hasAlpha();
if (alphaIn||doInputTransparency)
alphaIndex = new int[] { cm.getNumComponents() - 1 };
//
// we set the input threshold accordingly to the input
// image data type. I find the default value (which is 0) very bad
// for data type other than byte and ushort. With float and double
// it can cut off a large par of the dynamic.
//
sourceThreshold = new double[][] { { CoverageUtilities.getMosaicThreshold(loadedImage.getSampleModel().getDataType()) } };
firstGranule=false;
}
} catch (InterruptedException e) {
if(LOGGER.isLoggable(Level.SEVERE))
LOGGER.log(Level.SEVERE,"Unable to load the raster for granuleDescriptor " +granuleIndex,e);
continue;
} catch (ExecutionException e) {
if(LOGGER.isLoggable(Level.SEVERE))
LOGGER.log(Level.SEVERE,"Unable to load the raster for granuleDescriptor " +granuleIndex,e);
continue;
}
catch (ImagingException e) {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine("Adding to mosaic image number " + granuleIndex+ " failed, original request was "+request);
continue;
}
catch (javax.media.jai.util.ImagingException e) {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine("Adding to mosaic image number " + granuleIndex+ " failed, original request was "+request);
continue;
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Adding to mosaic image number " + granuleIndex);
}
//
// add to the mosaic collection, with preprocessing
//
final RenderedImage raster = processGranuleRaster(
loadedImage,
granuleIndex,
alphaIndex,
alphaIn,
alphaChannels,
doInputTransparency,
inputTransparentColor);
// we need to add its roi in order to avoid problems whith the mosaic overl
ROI imageBounds = new ROIShape(PlanarImage.wrapRenderedImage(raster).getBounds());
if (footprintManagement){
final ROIShape footprint = result.getFootprint();
if (footprint != null){
if (imageBounds.contains(footprint.getBounds())) {
imageBounds = footprint;
} else {
imageBounds = imageBounds.intersect(footprint);
}
}
}
rois.add(imageBounds);
// add to mosaic
sources.add(raster);
//increment index
granuleIndex++;
}
granulesNumber=granuleIndex;
if(granulesNumber==0)
{
if(LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE,"Unable to load any granuleDescriptor ");
return;
}
sourceRoi = rois.toArray(new ROI[rois.size()]);
}
}
/** Logger. */
private final static Logger LOGGER = org.geotools.util.logging.Logging.getLogger(RasterLayerResponse.class);
/**
* The GridCoverage produced after a {@link #compute()} method call
*/
private GridCoverage2D gridCoverage;
/** The {@link RasterLayerRequest} originating this response */
private RasterLayerRequest request;
/** The coverage factory producing a {@link GridCoverage} from an image */
private GridCoverageFactory coverageFactory;
/** The base envelope related to the input coverage */
private GeneralEnvelope coverageEnvelope;
private boolean frozen = false;
private RasterManager rasterManager;
private Color finalTransparentColor;
private ReferencedEnvelope mosaicBBox;
private Rectangle rasterBounds;
private MathTransform2D finalGridToWorldCorner;
private MathTransform2D finalWorldToGridCorner;
private int imageChoice=0;
private ImageReadParam baseReadParameters= new ImageReadParam();
private boolean multithreadingAllowed=false;
private boolean footprintManagement = !Utils.IGNORE_FOOTPRINT;
private boolean setRoiProperty;
private boolean alphaIn=false;
private boolean oversampledRequest = false;
private MathTransform baseGridToWorld;
private Interpolation interpolation;
private boolean needsReprojection;
private double[] backgroundValues;
private Hints hints;
/**
* Construct a {@code RasterLayerResponse} given a specific
* {@link RasterLayerRequest}, a {@code GridCoverageFactory} to produce
* {@code GridCoverage}s and an {@code ImageReaderSpi} to be used for
* instantiating an Image Reader for a read operation,
*
* @param request
* a {@link RasterLayerRequest} originating this response.
* @param coverageFactory
* a {@code GridCoverageFactory} to produce a {@code
* GridCoverage} when calling the {@link #compute()} method.
* @param readerSpi
* the Image Reader Service provider interface.
*/
public RasterLayerResponse(final RasterLayerRequest request,
final RasterManager rasterManager) {
this.request = request;
coverageEnvelope = rasterManager.spatialDomainManager.coverageEnvelope;
this.coverageFactory = rasterManager.getCoverageFactory();
this.rasterManager = rasterManager;
this.hints = rasterManager.getHints();
baseGridToWorld=rasterManager.spatialDomainManager.coverageGridToWorld2D;
finalTransparentColor=request.getOutputTransparentColor();
// are we doing multithreading?
multithreadingAllowed= request.isMultithreadingAllowed();
footprintManagement = request.isFootprintManagement();
setRoiProperty = request.isSetRoiProperty();
backgroundValues = request.getBackgroundValues();
interpolation = request.getInterpolation();
needsReprojection = request.isNeedsReprojection();
}
/**
* Compute the coverage request and produce a grid coverage which will be
* returned by {@link #createResponse()}. The produced grid coverage may be
* {@code null} in case of empty request.
*
* @return the {@link GridCoverage} produced as computation of this response
* using the {@link #compute()} method.
* @throws IOException
* @uml.property name="gridCoverage"
*/
public GridCoverage2D createResponse() throws IOException {
processRequest();
return gridCoverage;
}
/**
* @return the {@link RasterLayerRequest} originating this response.
*
* @uml.property name="request"
*/
public RasterLayerRequest getOriginatingCoverageRequest() {
return request;
}
/**
* This method creates the GridCoverage2D from the underlying file given a
* specified envelope, and a requested dimension.
*
* @param iUseJAI
* specify if the underlying read process should leverage on a
* JAI ImageRead operation or a simple direct call to the {@code
* read} method of a proper {@code ImageReader}.
* @param overviewPolicy
* the overview policy which need to be adopted
* @return a {@code GridCoverage}
*
* @throws java.io.IOException
*/
private void processRequest() throws IOException {
if (request.isEmpty())
{
if(LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE,"Request is empty: "+request.toString());
this.gridCoverage=null;
return;
}
if (frozen)
return;
// assemble granules
final RenderedImage mosaic = prepareResponse();
//postproc
RenderedImage finalRaster = postProcessRaster(mosaic);
//create the coverage
gridCoverage = prepareCoverage(finalRaster);
//freeze
frozen = true;
}
private RenderedImage postProcessRaster(RenderedImage mosaic) {
// alpha on the final mosaic
if (finalTransparentColor != null) {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine("Support for alpha on final mosaic");
return Utils.makeColorTransparent(finalTransparentColor,mosaic);
}
if (oversampledRequest){
try {
// creating source grid to world corrected to the pixel corner
final AffineTransform sourceGridToWorld = new AffineTransform((AffineTransform) baseGridToWorld);
sourceGridToWorld.concatenate(CoverageUtilities.CENTER_TO_CORNER);
// creating target grid to world corrected to the pixel corner
final AffineTransform targetGridToWorld = new AffineTransform(request.getRequestedGridToWorld());
targetGridToWorld.concatenate(CoverageUtilities.CENTER_TO_CORNER);
// target world to grid at the corner
final AffineTransform targetWorldToGrid=targetGridToWorld.createInverse();
// final complete transformation
targetWorldToGrid.concatenate(sourceGridToWorld);
// create final image
// TODO this one could be optimized further depending on how the affine is created
mosaic = AffineDescriptor.create(mosaic, targetWorldToGrid , interpolation, backgroundValues, hints);
} catch (NoninvertibleTransformException e) {
if (LOGGER.isLoggable(Level.SEVERE)){
LOGGER.log(Level.SEVERE, "Unable to create the requested mosaic ", e );
}
}
}
return mosaic;
}
/**
* This method loads the granules which overlap the requested
* {@link GeneralEnvelope} using the provided values for alpha and input
* ROI.
* @return
* @throws DataSourceException
*/
private RenderedImage prepareResponse() throws DataSourceException {
try {
//
// prepare the params for executing a mosaic operation.
//
// It might important to set the mosaic type to blend otherwise
// sometimes strange results jump in.
// select the relevant overview, notice that at this time we have
// relaxed a bit the requirement to have the same exact resolution
// for all the overviews, but still we do not allow for reading the
// various grid to world transform directly from the input files,
// therefore we are assuming that each granuleDescriptor has a scale and
// translate only grid to world that can be deduced from its base
// level dimension and envelope. The grid to world transforms for
// the other levels can be computed accordingly knowing the scale
// factors.
if (request.getRequestedBBox() != null && request.getRequestedRasterArea() != null && !request.isHeterogeneousGranules())
imageChoice = ReadParamsController.setReadParams(
request.getRequestedResolution(),
request.getOverviewPolicy(),
request.getDecimationPolicy(),
baseReadParameters,
request.rasterManager,
request.rasterManager.overviewsController); // use general overviews controller
else
imageChoice = 0;
assert imageChoice>=0;
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine(new StringBuffer("Loading level ").append(
imageChoice).append(" with subsampling factors ")
.append(baseReadParameters.getSourceXSubsampling()).append(" ")
.append(baseReadParameters.getSourceYSubsampling()).toString());
// ok we got something to return, let's load records from the index
final BoundingBox cropBBOX = request.getCropBBox();
if (cropBBOX != null)
mosaicBBox = ReferencedEnvelope.reference(cropBBOX);
else
mosaicBBox = new ReferencedEnvelope(coverageEnvelope);
//compute final world to grid
// base grid to world for the center of pixels
final AffineTransform g2w;
final OverviewLevel baseLevel = rasterManager.overviewsController.resolutionsLevels
.get(0);
final double resX = baseLevel.resolutionX;
final double resY = baseLevel.resolutionY;
final double[] requestRes = request.getRequestedResolution();
if ((requestRes[0] < resX || requestRes[1] < resY) && !needsReprojection) {
// Using the best available resolution
oversampledRequest = true;
g2w = new AffineTransform((AffineTransform) baseGridToWorld);
g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);
} else {
if (!needsReprojection) {
g2w = new AffineTransform(request.getRequestedGridToWorld());
g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);
} else {
GridToEnvelopeMapper mapper = new GridToEnvelopeMapper(
new GridEnvelope2D(request.getRequestedRasterArea()),
mosaicBBox);
mapper.setPixelAnchor(PixelInCell.CELL_CORNER);
g2w = mapper.createAffineTransform();
}
}
// move it to the corner
finalGridToWorldCorner = new AffineTransform2D(g2w);
finalWorldToGridCorner = finalGridToWorldCorner.inverse();// compute raster bounds
final GeneralEnvelope tempRasterBounds = CRS.transform(finalWorldToGridCorner, mosaicBBox);
-// rasterBounds=tempRasterBounds.toRectangle2D().getBounds();
+ rasterBounds=tempRasterBounds.toRectangle2D().getBounds();
// SG using the above may lead to problems since the reason is that may be a little (1 px) bigger
// than what we need. The code below is a bit better since it uses a proper logic (see GridEnvelope
// Javadoc)
- rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
+ //rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
if (rasterBounds.width == 0)
rasterBounds.width++;
if (rasterBounds.height == 0)
rasterBounds.height++;
// create the index visitor and visit the feature
final MosaicBuilder visitor = new MosaicBuilder();
visitor.request = request;
final List<Date> times = request.getRequestedTimes();
final List<Double> elevations=request.getElevation();
final Filter filter = request.getFilter();
final boolean hasTime=(times!=null&×.size()>0);
final boolean hasElevation=(elevations!=null && elevations.size()>0);
final boolean hasFilter = filter != null;
final SimpleFeatureType type = rasterManager.granuleCatalog.getType();
Query query = null;
if (type != null){
query= new Query(rasterManager.granuleCatalog.getType().getTypeName());
final Filter bbox=FeatureUtilities.DEFAULT_FILTER_FACTORY.bbox(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.granuleCatalog.getType().getGeometryDescriptor().getName()),mosaicBBox);
query.setFilter( bbox);
}
if(hasTime||hasElevation||hasFilter )
{
//handle elevation indexing first since we then combine this with the max in case we are asking for current in time
if (hasElevation){
final Filter oldFilter = query.getFilter();
final PropertyIsEqualTo elevationF =
FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(
FeatureUtilities.DEFAULT_FILTER_FACTORY.property(
rasterManager.elevationAttribute),
FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(elevations.get(0)),
true
);
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, elevationF));
}
//handle runtime indexing since we then combine this with the max in case we are asking for current in time
if (hasFilter){
final Filter oldFilter = query.getFilter();
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, filter));
}
// fuse time query with the bbox query
if(hasTime){
final Filter oldFilter = query.getFilter();
final int size=times.size();
boolean current= size==1&×.get(0)==null;
if( !current){
Filter temporal=null;
if(size==1)
temporal=FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(times.get(0)),true);
else{
boolean first =true;
for( Date datetime: times){
if(first){
temporal=FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(datetime),true);
first =false;
}
else{
final PropertyIsEqualTo temp =
FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(datetime),true);
temporal= FeatureUtilities.DEFAULT_FILTER_FACTORY.or(Arrays.asList(temporal,temp));
}
}
}
if(temporal!=null)//should not happen
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, temporal));
}
else{
// current management
final SortBy[] descendingSortOrder = new SortBy[]{
new SortByImpl(
FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute),
SortOrder.DESCENDING
)};
final QueryCapabilities queryCapabilities = rasterManager.granuleCatalog.getQueryCapabilities();
if(queryCapabilities.supportsSorting(descendingSortOrder))
query.setSortBy(descendingSortOrder);
else{
// the datastore does not support descending sortby, let's support the maximum
final MaxVisitor max = new MaxVisitor(rasterManager.timeAttribute);
rasterManager.granuleCatalog.computeAggregateFunction(query,max);
final Object result=max.getResult().getValue();
// now let's get this feature by is fid
final Filter temporal = FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(Converters.convert(result, Date.class)),true);
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, temporal));
}
}
}
rasterManager.getGranules(query, visitor);
} else {
rasterManager.getGranules(mosaicBBox, visitor);
}
// get those granules
visitor.produce();
//
// Did we actually load anything?? Notice that it might happen that
// either we have holes inside the definition area for the mosaic
// or we had some problem with missing tiles, therefore it might
// happen that for some bboxes we don't have anything to load.
//
if (visitor.granulesNumber>=1) {
//
// Create the mosaic image by doing a crop if necessary and also
// managing the transparent color if applicable. Be aware that
// management of the transparent color involves removing
// transparency information from the input images.
//
if (LOGGER.isLoggable(Level.FINER))
LOGGER.finer(new StringBuilder("Loaded bbox ").append(
mosaicBBox.toString()).append(" while crop bbox ")
.append(request.getCropBBox().toString())
.toString());
return buildMosaic(visitor);
}
else{
// if we get here that means that we do not have anything to load
// but still we are inside the definition area for the mosaic,
// therefore we create a fake coverage using the background values,
// if provided (defaulting to 0), as well as the compute raster
// bounds, envelope and grid to world.
final Number[] values = Utils.getBackgroundValues(rasterManager.defaultSM, backgroundValues);
// create a constant image with a proper layout
return ConstantDescriptor.create(
Float.valueOf(rasterBounds.width),
Float.valueOf(rasterBounds.height),
values,
rasterManager.defaultImageLayout!=null?new RenderingHints(JAI.KEY_IMAGE_LAYOUT,rasterManager.defaultImageLayout):null);
}
} catch (IOException e) {
throw new DataSourceException("Unable to create this mosaic", e);
} catch (TransformException e) {
throw new DataSourceException("Unable to create this mosaic", e);
}
}
private RenderedImage processGranuleRaster(
RenderedImage granule,
final int granuleIndex,
final int[] alphaIndex,
final boolean alphaIn,
final PlanarImage[] alphaChannels,
final boolean doTransparentColor, final Color transparentColor) {
//
// INDEX COLOR MODEL EXPANSION
//
// Take into account the need for an expansions of the original color
// model.
//
// If the original color model is an index color model an expansion
// might be requested in case the different palettes are not all the
// same. In this case the mosaic operator from JAI would provide wrong
// results since it would take the first palette and use that one for
// all the other images.
//
// There is a special case to take into account here. In case the input
// images use an IndexColorModel it might happen that the transparent
// color is present in some of them while it is not present in some
// others. This case is the case where for sure a color expansion is
// needed. However we have to take into account that during the masking
// phase the images where the requested transparent color was present
// will have 4 bands, the other 3. If we want the mosaic to work we
// have to add an extra band to the latter type of images for providing
// alpha information to them.
//
//
if (rasterManager.expandMe && granule.getColorModel() instanceof IndexColorModel) {
granule = new ImageWorker(granule).forceComponentColorModel().getRenderedImage();
}
//
// TRANSPARENT COLOR MANAGEMENT
//
if (doTransparentColor) {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine("Support for alpha on input image number "+ granuleIndex);
granule = Utils.makeColorTransparent(transparentColor, granule);
alphaIndex[0]= granule.getColorModel().getNumComponents() - 1 ;
}
//
// ROI
//
if (alphaIn || doTransparentColor) {
ImageWorker w = new ImageWorker(granule);
if (granule.getSampleModel() instanceof MultiPixelPackedSampleModel)
w.forceComponentColorModel();
//
// ALPHA in INPUT
//
// I have to select the alpha band and provide it to the final
// mosaic operator. I have to force going to ComponentColorModel in
// case the image is indexed.
//
if (granule.getColorModel() instanceof IndexColorModel) {
alphaChannels[granuleIndex] = w.forceComponentColorModel().retainLastBand().getPlanarImage();
} else
alphaChannels[granuleIndex] = w.retainBands(alphaIndex).getPlanarImage();
}
return granule;
}
/**
* Once we reach this method it means that we have loaded all the images
* which were intersecting the requested envelope. Next step is to create
* the final mosaic image and cropping it to the exact requested envelope.
* @param visitor
*
* @return A {@link RenderedImage}}.
*/
private RenderedImage buildMosaic(final MosaicBuilder visitor) throws IOException {
final ImageLayout layout = new ImageLayout(
rasterBounds.x,
rasterBounds.y,
rasterBounds.width,
rasterBounds.height);
//tiling
final Dimension tileDimensions=request.getTileDimensions();
if(tileDimensions!=null)
layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
final RenderingHints localHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT,layout);
if (hints != null && !hints.isEmpty()){
if (hints.containsKey(JAI.KEY_TILE_CACHE)){
final Object tc = hints.get(JAI.KEY_TILE_CACHE);
if (tc != null && tc instanceof TileCache)
localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) tc));
}
boolean addBorderExtender = true;
if (hints != null && hints.containsKey(JAI.KEY_BORDER_EXTENDER)){
final Object extender = hints.get(JAI.KEY_BORDER_EXTENDER);
if (extender != null && extender instanceof BorderExtender) {
localHints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, (BorderExtender) extender));
addBorderExtender = false;
}
}
if (addBorderExtender){
localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
}
if (hints.containsKey(JAI.KEY_TILE_SCHEDULER)){
final Object ts = hints.get(JAI.KEY_TILE_SCHEDULER);
if (ts != null && ts instanceof TileScheduler)
localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) ts));
}
}
final ROI[] sourceRoi = visitor.sourceRoi;
final RenderedImage mosaic = MosaicDescriptor.create(visitor.getSourcesAsArray(),
request.isBlend()? MosaicDescriptor.MOSAIC_TYPE_BLEND: MosaicDescriptor.MOSAIC_TYPE_OVERLAY
, (alphaIn || visitor.doInputTransparency) ? visitor.alphaChannels : null, sourceRoi, visitor.sourceThreshold, backgroundValues, localHints);
if (setRoiProperty) {
//Adding globalRoi to the output
RenderedOp rop = (RenderedOp) mosaic;
ROI globalRoi = null;
ROI[] rois = sourceRoi;
for (int i=0; i<rois.length; i++){
if (globalRoi == null){
globalRoi = new ROI(rois[i].getAsImage());
} else {
globalRoi = globalRoi.add(rois[i]);
}
}
rop.setProperty("ROI", globalRoi);
}
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine(new StringBuffer("Mosaic created ").toString());
// create the coverage
return mosaic;
}
/**
* This method is responsible for creating a coverage from the supplied {@link RenderedImage}.
*
* @param image
* @return
* @throws IOException
*/
private GridCoverage2D prepareCoverage(RenderedImage image) throws IOException {
// creating bands
final SampleModel sm=image.getSampleModel();
final ColorModel cm=image.getColorModel();
final int numBands = sm.getNumBands();
final GridSampleDimension[] bands = new GridSampleDimension[numBands];
// setting bands names.
for (int i = 0; i < numBands; i++) {
// color interpretation
final ColorInterpretation colorInterpretation=TypeMap.getColorInterpretation(cm, i);
if(colorInterpretation==null)
throw new IOException("Unrecognized sample dimension type");
// sample dimension type
final SampleDimensionType st=TypeMap.getSampleDimensionType(sm, i);
// set some no data values, as well as Min and Max values
final double noData;
double min=-Double.MAX_VALUE,max=Double.MAX_VALUE;
if(backgroundValues!=null)
{
// sometimes background values are not specified as 1 per each band, therefore we need to be careful
noData= backgroundValues[backgroundValues.length > i ? i:0];
}
else
{
if(st.compareTo(SampleDimensionType.REAL_32BITS)==0)
noData= Float.NaN;
else
if(st.compareTo(SampleDimensionType.REAL_64BITS)==0)
noData= Double.NaN;
else
if(st.compareTo(SampleDimensionType.SIGNED_16BITS)==0)
{
noData=Short.MIN_VALUE;
min=Short.MIN_VALUE;
max=Short.MAX_VALUE;
}
else
if(st.compareTo(SampleDimensionType.SIGNED_32BITS)==0)
{
noData= Integer.MIN_VALUE;
min=Integer.MIN_VALUE;
max=Integer.MAX_VALUE;
}
else
if(st.compareTo(SampleDimensionType.SIGNED_8BITS)==0)
{
noData= -128;
min=-128;
max=127;
}
else
{
//unsigned
noData= 0;
min=0;
// compute max
if(st.compareTo(SampleDimensionType.UNSIGNED_1BIT)==0)
max=1;
else
if(st.compareTo(SampleDimensionType.UNSIGNED_2BITS)==0)
max=3;
else
if(st.compareTo(SampleDimensionType.UNSIGNED_4BITS)==0)
max=7;
else
if(st.compareTo(SampleDimensionType.UNSIGNED_8BITS)==0)
max=255;
else
if(st.compareTo(SampleDimensionType.UNSIGNED_16BITS)==0)
max=65535;
else
if(st.compareTo(SampleDimensionType.UNSIGNED_32BITS)==0)
max=Math.pow(2, 32)-1;
}
}
bands[i] = new SimplifiedGridSampleDimension(
colorInterpretation.name(),
st,
colorInterpretation,
noData,
min,
max,
1, //no scale
0, //no offset
null
).geophysics(true);
}
return coverageFactory.create(rasterManager.getCoverageIdentifier(), image,new GeneralEnvelope(mosaicBBox), bands, null, null);
}
}
| false | true | private RenderedImage prepareResponse() throws DataSourceException {
try {
//
// prepare the params for executing a mosaic operation.
//
// It might important to set the mosaic type to blend otherwise
// sometimes strange results jump in.
// select the relevant overview, notice that at this time we have
// relaxed a bit the requirement to have the same exact resolution
// for all the overviews, but still we do not allow for reading the
// various grid to world transform directly from the input files,
// therefore we are assuming that each granuleDescriptor has a scale and
// translate only grid to world that can be deduced from its base
// level dimension and envelope. The grid to world transforms for
// the other levels can be computed accordingly knowing the scale
// factors.
if (request.getRequestedBBox() != null && request.getRequestedRasterArea() != null && !request.isHeterogeneousGranules())
imageChoice = ReadParamsController.setReadParams(
request.getRequestedResolution(),
request.getOverviewPolicy(),
request.getDecimationPolicy(),
baseReadParameters,
request.rasterManager,
request.rasterManager.overviewsController); // use general overviews controller
else
imageChoice = 0;
assert imageChoice>=0;
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine(new StringBuffer("Loading level ").append(
imageChoice).append(" with subsampling factors ")
.append(baseReadParameters.getSourceXSubsampling()).append(" ")
.append(baseReadParameters.getSourceYSubsampling()).toString());
// ok we got something to return, let's load records from the index
final BoundingBox cropBBOX = request.getCropBBox();
if (cropBBOX != null)
mosaicBBox = ReferencedEnvelope.reference(cropBBOX);
else
mosaicBBox = new ReferencedEnvelope(coverageEnvelope);
//compute final world to grid
// base grid to world for the center of pixels
final AffineTransform g2w;
final OverviewLevel baseLevel = rasterManager.overviewsController.resolutionsLevels
.get(0);
final double resX = baseLevel.resolutionX;
final double resY = baseLevel.resolutionY;
final double[] requestRes = request.getRequestedResolution();
if ((requestRes[0] < resX || requestRes[1] < resY) && !needsReprojection) {
// Using the best available resolution
oversampledRequest = true;
g2w = new AffineTransform((AffineTransform) baseGridToWorld);
g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);
} else {
if (!needsReprojection) {
g2w = new AffineTransform(request.getRequestedGridToWorld());
g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);
} else {
GridToEnvelopeMapper mapper = new GridToEnvelopeMapper(
new GridEnvelope2D(request.getRequestedRasterArea()),
mosaicBBox);
mapper.setPixelAnchor(PixelInCell.CELL_CORNER);
g2w = mapper.createAffineTransform();
}
}
// move it to the corner
finalGridToWorldCorner = new AffineTransform2D(g2w);
finalWorldToGridCorner = finalGridToWorldCorner.inverse();// compute raster bounds
final GeneralEnvelope tempRasterBounds = CRS.transform(finalWorldToGridCorner, mosaicBBox);
// rasterBounds=tempRasterBounds.toRectangle2D().getBounds();
// SG using the above may lead to problems since the reason is that may be a little (1 px) bigger
// than what we need. The code below is a bit better since it uses a proper logic (see GridEnvelope
// Javadoc)
rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
if (rasterBounds.width == 0)
rasterBounds.width++;
if (rasterBounds.height == 0)
rasterBounds.height++;
// create the index visitor and visit the feature
final MosaicBuilder visitor = new MosaicBuilder();
visitor.request = request;
final List<Date> times = request.getRequestedTimes();
final List<Double> elevations=request.getElevation();
final Filter filter = request.getFilter();
final boolean hasTime=(times!=null&×.size()>0);
final boolean hasElevation=(elevations!=null && elevations.size()>0);
final boolean hasFilter = filter != null;
final SimpleFeatureType type = rasterManager.granuleCatalog.getType();
Query query = null;
if (type != null){
query= new Query(rasterManager.granuleCatalog.getType().getTypeName());
final Filter bbox=FeatureUtilities.DEFAULT_FILTER_FACTORY.bbox(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.granuleCatalog.getType().getGeometryDescriptor().getName()),mosaicBBox);
query.setFilter( bbox);
}
if(hasTime||hasElevation||hasFilter )
{
//handle elevation indexing first since we then combine this with the max in case we are asking for current in time
if (hasElevation){
final Filter oldFilter = query.getFilter();
final PropertyIsEqualTo elevationF =
FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(
FeatureUtilities.DEFAULT_FILTER_FACTORY.property(
rasterManager.elevationAttribute),
FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(elevations.get(0)),
true
);
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, elevationF));
}
//handle runtime indexing since we then combine this with the max in case we are asking for current in time
if (hasFilter){
final Filter oldFilter = query.getFilter();
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, filter));
}
// fuse time query with the bbox query
if(hasTime){
final Filter oldFilter = query.getFilter();
final int size=times.size();
boolean current= size==1&×.get(0)==null;
if( !current){
Filter temporal=null;
if(size==1)
temporal=FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(times.get(0)),true);
else{
boolean first =true;
for( Date datetime: times){
if(first){
temporal=FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(datetime),true);
first =false;
}
else{
final PropertyIsEqualTo temp =
FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(datetime),true);
temporal= FeatureUtilities.DEFAULT_FILTER_FACTORY.or(Arrays.asList(temporal,temp));
}
}
}
if(temporal!=null)//should not happen
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, temporal));
}
else{
// current management
final SortBy[] descendingSortOrder = new SortBy[]{
new SortByImpl(
FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute),
SortOrder.DESCENDING
)};
final QueryCapabilities queryCapabilities = rasterManager.granuleCatalog.getQueryCapabilities();
if(queryCapabilities.supportsSorting(descendingSortOrder))
query.setSortBy(descendingSortOrder);
else{
// the datastore does not support descending sortby, let's support the maximum
final MaxVisitor max = new MaxVisitor(rasterManager.timeAttribute);
rasterManager.granuleCatalog.computeAggregateFunction(query,max);
final Object result=max.getResult().getValue();
// now let's get this feature by is fid
final Filter temporal = FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(Converters.convert(result, Date.class)),true);
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, temporal));
}
}
}
rasterManager.getGranules(query, visitor);
} else {
rasterManager.getGranules(mosaicBBox, visitor);
}
// get those granules
visitor.produce();
//
// Did we actually load anything?? Notice that it might happen that
// either we have holes inside the definition area for the mosaic
// or we had some problem with missing tiles, therefore it might
// happen that for some bboxes we don't have anything to load.
//
if (visitor.granulesNumber>=1) {
//
// Create the mosaic image by doing a crop if necessary and also
// managing the transparent color if applicable. Be aware that
// management of the transparent color involves removing
// transparency information from the input images.
//
if (LOGGER.isLoggable(Level.FINER))
LOGGER.finer(new StringBuilder("Loaded bbox ").append(
mosaicBBox.toString()).append(" while crop bbox ")
.append(request.getCropBBox().toString())
.toString());
return buildMosaic(visitor);
}
else{
// if we get here that means that we do not have anything to load
// but still we are inside the definition area for the mosaic,
// therefore we create a fake coverage using the background values,
// if provided (defaulting to 0), as well as the compute raster
// bounds, envelope and grid to world.
final Number[] values = Utils.getBackgroundValues(rasterManager.defaultSM, backgroundValues);
// create a constant image with a proper layout
return ConstantDescriptor.create(
Float.valueOf(rasterBounds.width),
Float.valueOf(rasterBounds.height),
values,
rasterManager.defaultImageLayout!=null?new RenderingHints(JAI.KEY_IMAGE_LAYOUT,rasterManager.defaultImageLayout):null);
}
} catch (IOException e) {
throw new DataSourceException("Unable to create this mosaic", e);
} catch (TransformException e) {
throw new DataSourceException("Unable to create this mosaic", e);
}
}
| private RenderedImage prepareResponse() throws DataSourceException {
try {
//
// prepare the params for executing a mosaic operation.
//
// It might important to set the mosaic type to blend otherwise
// sometimes strange results jump in.
// select the relevant overview, notice that at this time we have
// relaxed a bit the requirement to have the same exact resolution
// for all the overviews, but still we do not allow for reading the
// various grid to world transform directly from the input files,
// therefore we are assuming that each granuleDescriptor has a scale and
// translate only grid to world that can be deduced from its base
// level dimension and envelope. The grid to world transforms for
// the other levels can be computed accordingly knowing the scale
// factors.
if (request.getRequestedBBox() != null && request.getRequestedRasterArea() != null && !request.isHeterogeneousGranules())
imageChoice = ReadParamsController.setReadParams(
request.getRequestedResolution(),
request.getOverviewPolicy(),
request.getDecimationPolicy(),
baseReadParameters,
request.rasterManager,
request.rasterManager.overviewsController); // use general overviews controller
else
imageChoice = 0;
assert imageChoice>=0;
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine(new StringBuffer("Loading level ").append(
imageChoice).append(" with subsampling factors ")
.append(baseReadParameters.getSourceXSubsampling()).append(" ")
.append(baseReadParameters.getSourceYSubsampling()).toString());
// ok we got something to return, let's load records from the index
final BoundingBox cropBBOX = request.getCropBBox();
if (cropBBOX != null)
mosaicBBox = ReferencedEnvelope.reference(cropBBOX);
else
mosaicBBox = new ReferencedEnvelope(coverageEnvelope);
//compute final world to grid
// base grid to world for the center of pixels
final AffineTransform g2w;
final OverviewLevel baseLevel = rasterManager.overviewsController.resolutionsLevels
.get(0);
final double resX = baseLevel.resolutionX;
final double resY = baseLevel.resolutionY;
final double[] requestRes = request.getRequestedResolution();
if ((requestRes[0] < resX || requestRes[1] < resY) && !needsReprojection) {
// Using the best available resolution
oversampledRequest = true;
g2w = new AffineTransform((AffineTransform) baseGridToWorld);
g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);
} else {
if (!needsReprojection) {
g2w = new AffineTransform(request.getRequestedGridToWorld());
g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);
} else {
GridToEnvelopeMapper mapper = new GridToEnvelopeMapper(
new GridEnvelope2D(request.getRequestedRasterArea()),
mosaicBBox);
mapper.setPixelAnchor(PixelInCell.CELL_CORNER);
g2w = mapper.createAffineTransform();
}
}
// move it to the corner
finalGridToWorldCorner = new AffineTransform2D(g2w);
finalWorldToGridCorner = finalGridToWorldCorner.inverse();// compute raster bounds
final GeneralEnvelope tempRasterBounds = CRS.transform(finalWorldToGridCorner, mosaicBBox);
rasterBounds=tempRasterBounds.toRectangle2D().getBounds();
// SG using the above may lead to problems since the reason is that may be a little (1 px) bigger
// than what we need. The code below is a bit better since it uses a proper logic (see GridEnvelope
// Javadoc)
//rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
if (rasterBounds.width == 0)
rasterBounds.width++;
if (rasterBounds.height == 0)
rasterBounds.height++;
// create the index visitor and visit the feature
final MosaicBuilder visitor = new MosaicBuilder();
visitor.request = request;
final List<Date> times = request.getRequestedTimes();
final List<Double> elevations=request.getElevation();
final Filter filter = request.getFilter();
final boolean hasTime=(times!=null&×.size()>0);
final boolean hasElevation=(elevations!=null && elevations.size()>0);
final boolean hasFilter = filter != null;
final SimpleFeatureType type = rasterManager.granuleCatalog.getType();
Query query = null;
if (type != null){
query= new Query(rasterManager.granuleCatalog.getType().getTypeName());
final Filter bbox=FeatureUtilities.DEFAULT_FILTER_FACTORY.bbox(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.granuleCatalog.getType().getGeometryDescriptor().getName()),mosaicBBox);
query.setFilter( bbox);
}
if(hasTime||hasElevation||hasFilter )
{
//handle elevation indexing first since we then combine this with the max in case we are asking for current in time
if (hasElevation){
final Filter oldFilter = query.getFilter();
final PropertyIsEqualTo elevationF =
FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(
FeatureUtilities.DEFAULT_FILTER_FACTORY.property(
rasterManager.elevationAttribute),
FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(elevations.get(0)),
true
);
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, elevationF));
}
//handle runtime indexing since we then combine this with the max in case we are asking for current in time
if (hasFilter){
final Filter oldFilter = query.getFilter();
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, filter));
}
// fuse time query with the bbox query
if(hasTime){
final Filter oldFilter = query.getFilter();
final int size=times.size();
boolean current= size==1&×.get(0)==null;
if( !current){
Filter temporal=null;
if(size==1)
temporal=FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(times.get(0)),true);
else{
boolean first =true;
for( Date datetime: times){
if(first){
temporal=FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(datetime),true);
first =false;
}
else{
final PropertyIsEqualTo temp =
FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(datetime),true);
temporal= FeatureUtilities.DEFAULT_FILTER_FACTORY.or(Arrays.asList(temporal,temp));
}
}
}
if(temporal!=null)//should not happen
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, temporal));
}
else{
// current management
final SortBy[] descendingSortOrder = new SortBy[]{
new SortByImpl(
FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute),
SortOrder.DESCENDING
)};
final QueryCapabilities queryCapabilities = rasterManager.granuleCatalog.getQueryCapabilities();
if(queryCapabilities.supportsSorting(descendingSortOrder))
query.setSortBy(descendingSortOrder);
else{
// the datastore does not support descending sortby, let's support the maximum
final MaxVisitor max = new MaxVisitor(rasterManager.timeAttribute);
rasterManager.granuleCatalog.computeAggregateFunction(query,max);
final Object result=max.getResult().getValue();
// now let's get this feature by is fid
final Filter temporal = FeatureUtilities.DEFAULT_FILTER_FACTORY.equal(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(rasterManager.timeAttribute), FeatureUtilities.DEFAULT_FILTER_FACTORY.literal(Converters.convert(result, Date.class)),true);
query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(oldFilter, temporal));
}
}
}
rasterManager.getGranules(query, visitor);
} else {
rasterManager.getGranules(mosaicBBox, visitor);
}
// get those granules
visitor.produce();
//
// Did we actually load anything?? Notice that it might happen that
// either we have holes inside the definition area for the mosaic
// or we had some problem with missing tiles, therefore it might
// happen that for some bboxes we don't have anything to load.
//
if (visitor.granulesNumber>=1) {
//
// Create the mosaic image by doing a crop if necessary and also
// managing the transparent color if applicable. Be aware that
// management of the transparent color involves removing
// transparency information from the input images.
//
if (LOGGER.isLoggable(Level.FINER))
LOGGER.finer(new StringBuilder("Loaded bbox ").append(
mosaicBBox.toString()).append(" while crop bbox ")
.append(request.getCropBBox().toString())
.toString());
return buildMosaic(visitor);
}
else{
// if we get here that means that we do not have anything to load
// but still we are inside the definition area for the mosaic,
// therefore we create a fake coverage using the background values,
// if provided (defaulting to 0), as well as the compute raster
// bounds, envelope and grid to world.
final Number[] values = Utils.getBackgroundValues(rasterManager.defaultSM, backgroundValues);
// create a constant image with a proper layout
return ConstantDescriptor.create(
Float.valueOf(rasterBounds.width),
Float.valueOf(rasterBounds.height),
values,
rasterManager.defaultImageLayout!=null?new RenderingHints(JAI.KEY_IMAGE_LAYOUT,rasterManager.defaultImageLayout):null);
}
} catch (IOException e) {
throw new DataSourceException("Unable to create this mosaic", e);
} catch (TransformException e) {
throw new DataSourceException("Unable to create this mosaic", e);
}
}
|
diff --git a/src/org/servalproject/batphone/UnsecuredCall.java b/src/org/servalproject/batphone/UnsecuredCall.java
index 680e275a..b22b17c2 100644
--- a/src/org/servalproject/batphone/UnsecuredCall.java
+++ b/src/org/servalproject/batphone/UnsecuredCall.java
@@ -1,258 +1,255 @@
package org.servalproject.batphone;
import org.servalproject.R;
import org.servalproject.ServalBatPhoneApplication;
import org.servalproject.account.AccountService;
import org.servalproject.servald.PeerListService;
import org.servalproject.servald.SubscriberId;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class UnsecuredCall extends Activity {
ServalBatPhoneApplication app;
CallHandler callHandler;
private TextView remote_name_1;
private TextView remote_number_1;
private TextView callstatus_1;
private TextView action_1;
private TextView remote_name_2;
private TextView remote_number_2;
private TextView callstatus_2;
private TextView action_2;
// Create runnable for posting
final Runnable updateCallStatus = new Runnable() {
@Override
public void run() {
updateUI();
}
};
private Button endButton;
private Button incomingEndButton;
private Button incomingAnswerButton;
private Chronometer chron;
private String stateSummary()
{
return callHandler.local_state.code + "."
+ callHandler.remote_state.code;
}
private void updateUI()
{
final Window win = getWindow();
int incomingCallFlags =
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
Log.d("VoMPCall", "Updating UI for state " + stateSummary());
showSubLayout();
if (callHandler.local_state == VoMP.State.RingingIn)
win.addFlags(incomingCallFlags);
else
win.clearFlags(incomingCallFlags);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("VoMPCall", "Activity started");
app = (ServalBatPhoneApplication) this.getApplication();
if (app.servaldMonitor==null){
app.displayToastMessage("Unable to place a call at this time");
finish();
return;
}
if (app.callHandler == null) {
SubscriberId sid = null;
try {
Intent intent = this.getIntent();
String action = intent.getAction();
- if (Intent.ACTION_VIEW.equals(action)
- && AccountService.SID_FIELD_MIMETYPE.equals(intent
- .getType())) {
+ if (Intent.ACTION_VIEW.equals(action)) {
// This activity has been triggered from clicking on a SID
- // in
- // contacts.
+ // in contacts.
Cursor cursor = getContentResolver().query(
intent.getData(),
new String[] {
ContactsContract.Data.DATA1
},
ContactsContract.Data.MIMETYPE + " = ?",
new String[] {
AccountService.SID_FIELD_MIMETYPE
},
null);
try {
if (cursor.moveToNext())
sid = new SubscriberId(cursor.getString(0));
} finally {
cursor.close();
}
} else {
String sidString = intent.getStringExtra("sid");
if (sidString != null)
sid = new SubscriberId(sidString);
}
if (sid == null)
throw new IllegalArgumentException("Missing argument sid");
} catch (Exception e) {
ServalBatPhoneApplication.context.displayToastMessage(e
.getMessage());
Log.e("BatPhone", e.getMessage(), e);
finish();
return;
}
app.callHandler = new CallHandler(PeerListService.getPeer(
getContentResolver(), sid));
app.callHandler.setCallUI(this);
app.callHandler.dial();
} else {
app.callHandler.setCallUI(this);
}
this.callHandler = app.callHandler;
Log.d("VoMPCall", "Setup keepalive timer");
setContentView(R.layout.call_layered);
chron = (Chronometer) findViewById(R.id.call_time);
remote_name_1 = (TextView) findViewById(R.id.caller_name);
remote_number_1 = (TextView) findViewById(R.id.ph_no_display);
callstatus_1 = (TextView) findViewById(R.id.call_status);
action_1 = (TextView) findViewById(R.id.call_action_type);
action_2 = (TextView) findViewById(R.id.call_action_type_incoming);
remote_name_2 = (TextView) findViewById(R.id.caller_name_incoming);
remote_number_2 = (TextView) findViewById(R.id.ph_no_display_incoming);
callstatus_2 = (TextView) findViewById(R.id.call_status_incoming);
updatePeerDisplay();
if (callHandler.remotePeer.cacheUntil < SystemClock.elapsedRealtime()) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void result) {
updatePeerDisplay();
}
@Override
protected Void doInBackground(Void... params) {
PeerListService.resolve(callHandler.remotePeer);
return null;
}
}.execute();
}
updateUI();
endButton = (Button) this.findViewById(R.id.cancel_call_button);
endButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.hangup();
}
});
incomingEndButton = (Button) this.findViewById(R.id.incoming_decline);
incomingEndButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.hangup();
}
});
incomingAnswerButton = (Button) this
.findViewById(R.id.answer_button_incoming);
incomingAnswerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.pickup();
}
});
}
private void updatePeerDisplay() {
remote_name_1.setText(callHandler.remotePeer.getContactName());
remote_number_1.setText(callHandler.remotePeer.did);
remote_name_2.setText(callHandler.remotePeer.getContactName());
remote_number_2.setText(callHandler.remotePeer.did);
}
private void showSubLayout() {
View incoming = findViewById(R.id.incoming);
View incall = findViewById(R.id.incall);
if (callHandler.local_state == VoMP.State.InCall) {
chron.setBase(SystemClock.elapsedRealtime());
chron.start();
}
switch (callHandler.local_state) {
case RingingIn:
callstatus_2
.setText(getString(callHandler.local_state.displayResource)
+ " ("
+ stateSummary()
+ ")...");
incall.setVisibility(View.GONE);
incoming.setVisibility(View.VISIBLE);
break;
case NoSuchCall:
case NoCall:
case CallPrep:
case RingingOut:
case InCall:
action_1.setText(getString(callHandler.local_state.displayResource));
callstatus_1
.setText(getString(callHandler.local_state.displayResource)
+ " ("
+ stateSummary()
+ ")...");
incall.setVisibility(View.VISIBLE);
incoming.setVisibility(View.GONE);
break;
case CallEnded:
case Error:
// The animation when switching to the call ended
// activity is annoying, but I don't know how to fix it.
incoming.setVisibility(View.GONE);
incall.setVisibility(View.GONE);
Log.d("VoMPCall", "Calling finish()");
finish();
callHandler.setCallUI(null);
break;
}
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("VoMPCall", "Activity started");
app = (ServalBatPhoneApplication) this.getApplication();
if (app.servaldMonitor==null){
app.displayToastMessage("Unable to place a call at this time");
finish();
return;
}
if (app.callHandler == null) {
SubscriberId sid = null;
try {
Intent intent = this.getIntent();
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)
&& AccountService.SID_FIELD_MIMETYPE.equals(intent
.getType())) {
// This activity has been triggered from clicking on a SID
// in
// contacts.
Cursor cursor = getContentResolver().query(
intent.getData(),
new String[] {
ContactsContract.Data.DATA1
},
ContactsContract.Data.MIMETYPE + " = ?",
new String[] {
AccountService.SID_FIELD_MIMETYPE
},
null);
try {
if (cursor.moveToNext())
sid = new SubscriberId(cursor.getString(0));
} finally {
cursor.close();
}
} else {
String sidString = intent.getStringExtra("sid");
if (sidString != null)
sid = new SubscriberId(sidString);
}
if (sid == null)
throw new IllegalArgumentException("Missing argument sid");
} catch (Exception e) {
ServalBatPhoneApplication.context.displayToastMessage(e
.getMessage());
Log.e("BatPhone", e.getMessage(), e);
finish();
return;
}
app.callHandler = new CallHandler(PeerListService.getPeer(
getContentResolver(), sid));
app.callHandler.setCallUI(this);
app.callHandler.dial();
} else {
app.callHandler.setCallUI(this);
}
this.callHandler = app.callHandler;
Log.d("VoMPCall", "Setup keepalive timer");
setContentView(R.layout.call_layered);
chron = (Chronometer) findViewById(R.id.call_time);
remote_name_1 = (TextView) findViewById(R.id.caller_name);
remote_number_1 = (TextView) findViewById(R.id.ph_no_display);
callstatus_1 = (TextView) findViewById(R.id.call_status);
action_1 = (TextView) findViewById(R.id.call_action_type);
action_2 = (TextView) findViewById(R.id.call_action_type_incoming);
remote_name_2 = (TextView) findViewById(R.id.caller_name_incoming);
remote_number_2 = (TextView) findViewById(R.id.ph_no_display_incoming);
callstatus_2 = (TextView) findViewById(R.id.call_status_incoming);
updatePeerDisplay();
if (callHandler.remotePeer.cacheUntil < SystemClock.elapsedRealtime()) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void result) {
updatePeerDisplay();
}
@Override
protected Void doInBackground(Void... params) {
PeerListService.resolve(callHandler.remotePeer);
return null;
}
}.execute();
}
updateUI();
endButton = (Button) this.findViewById(R.id.cancel_call_button);
endButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.hangup();
}
});
incomingEndButton = (Button) this.findViewById(R.id.incoming_decline);
incomingEndButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.hangup();
}
});
incomingAnswerButton = (Button) this
.findViewById(R.id.answer_button_incoming);
incomingAnswerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.pickup();
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("VoMPCall", "Activity started");
app = (ServalBatPhoneApplication) this.getApplication();
if (app.servaldMonitor==null){
app.displayToastMessage("Unable to place a call at this time");
finish();
return;
}
if (app.callHandler == null) {
SubscriberId sid = null;
try {
Intent intent = this.getIntent();
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
// This activity has been triggered from clicking on a SID
// in contacts.
Cursor cursor = getContentResolver().query(
intent.getData(),
new String[] {
ContactsContract.Data.DATA1
},
ContactsContract.Data.MIMETYPE + " = ?",
new String[] {
AccountService.SID_FIELD_MIMETYPE
},
null);
try {
if (cursor.moveToNext())
sid = new SubscriberId(cursor.getString(0));
} finally {
cursor.close();
}
} else {
String sidString = intent.getStringExtra("sid");
if (sidString != null)
sid = new SubscriberId(sidString);
}
if (sid == null)
throw new IllegalArgumentException("Missing argument sid");
} catch (Exception e) {
ServalBatPhoneApplication.context.displayToastMessage(e
.getMessage());
Log.e("BatPhone", e.getMessage(), e);
finish();
return;
}
app.callHandler = new CallHandler(PeerListService.getPeer(
getContentResolver(), sid));
app.callHandler.setCallUI(this);
app.callHandler.dial();
} else {
app.callHandler.setCallUI(this);
}
this.callHandler = app.callHandler;
Log.d("VoMPCall", "Setup keepalive timer");
setContentView(R.layout.call_layered);
chron = (Chronometer) findViewById(R.id.call_time);
remote_name_1 = (TextView) findViewById(R.id.caller_name);
remote_number_1 = (TextView) findViewById(R.id.ph_no_display);
callstatus_1 = (TextView) findViewById(R.id.call_status);
action_1 = (TextView) findViewById(R.id.call_action_type);
action_2 = (TextView) findViewById(R.id.call_action_type_incoming);
remote_name_2 = (TextView) findViewById(R.id.caller_name_incoming);
remote_number_2 = (TextView) findViewById(R.id.ph_no_display_incoming);
callstatus_2 = (TextView) findViewById(R.id.call_status_incoming);
updatePeerDisplay();
if (callHandler.remotePeer.cacheUntil < SystemClock.elapsedRealtime()) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void result) {
updatePeerDisplay();
}
@Override
protected Void doInBackground(Void... params) {
PeerListService.resolve(callHandler.remotePeer);
return null;
}
}.execute();
}
updateUI();
endButton = (Button) this.findViewById(R.id.cancel_call_button);
endButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.hangup();
}
});
incomingEndButton = (Button) this.findViewById(R.id.incoming_decline);
incomingEndButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.hangup();
}
});
incomingAnswerButton = (Button) this
.findViewById(R.id.answer_button_incoming);
incomingAnswerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callHandler.pickup();
}
});
}
|
diff --git a/src/gov/nih/nci/cadsr/cdecurate/tool/tags/ObjMenuTag.java b/src/gov/nih/nci/cadsr/cdecurate/tool/tags/ObjMenuTag.java
index 19647d2f..12ab8a17 100644
--- a/src/gov/nih/nci/cadsr/cdecurate/tool/tags/ObjMenuTag.java
+++ b/src/gov/nih/nci/cadsr/cdecurate/tool/tags/ObjMenuTag.java
@@ -1,198 +1,198 @@
/**
*
*/
package gov.nih.nci.cadsr.cdecurate.tool.tags;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
/**
* This JSP tag library class is for action Menu
* @author hveerla
*
*/
public class ObjMenuTag extends MenuTag {
public int doEndTag() throws JspException {
getSessionAttributes();
HttpSession session = pageContext.getSession();
int rowsChecked = 0;
if (vCheckList!=null){
rowsChecked = vCheckList.size();
}
JspWriter objMenu = this.pageContext.getOut();
if (selACType != null) {
try {
- objMenu.println("<table style = \"border-collapse: collapse; bgcolor: #d8d8df\">");
+ objMenu.println("<table style = \"border-collapse: collapse; background-color: #d8d8df\">");
objMenu.println("<tr><td colspan=\"3\"><p style=\"margin: 0px 0px 5px 0px; color: red\"><span id=\"selCnt\">" + rowsChecked + "</span> Record(s) Selected</p></td></tr>");
objMenu.println("<tr style = \"background-color:#4876FF\"><td class=\"cell\" align=\"center\"><input type=\"checkbox\" onclick=\"this.checked=false;\"></td><td class=\"cell\" align=\"center\"><b><font color = \"#FFFFFF\">Action</b></td><td class=\"cell\" align=\"center\"><input type=\"checkbox\" checked onclick=\"this.checked=true;\"></td></tr>");
if ((selACType).equals("DataElement")) {
objMenu.println(displayEdit()
+ displayView()
+ displayDesignate()
+ displayViewDetiails()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("DataElementConcept")) {
objMenu.println(displayEdit()
+ displayView()
+ displayGetAssociatedDE()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("ValueDomain")) {
objMenu.println(displayEdit()
+ displayView()
+ displayGetAssociatedDE()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("ConceptualDomain")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("PermissibleValue")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ClassSchemeItems")){
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ValueMeaning")) {
objMenu.println(generateTR("edit","edit","performUncheckedCkBoxAction('edit')","","","Edit")
+ displayView()
+ displayGetAssociatedDE()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ConceptClass")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ObjectClass")){
objMenu.println(displayGetAssociatedDEC());
}
if ((selACType).equals("Property")) {
objMenu.println(displayGetAssociatedDEC());
}
objMenu.println(generateTR("","","","16_show_rows","ShowSelectedRows(true)","Show Selected Rows"));
objMenu.println(generateTR("","","","select_all","SelectAllCheckBox()","Select All"));
objMenu.println(generateTR("","","","unselect_all","UnSelectAllCheckBox()","Unselect All"));
objMenu.println("</table></div>");
} catch (IOException e) {
e.printStackTrace();
}
}
return EVAL_PAGE;
}
public String generateTR(String id, String imageSingle, String jsMethodSingle, String imageMultiple, String jsMethodMultiple, String value){
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
String image_single = null;
String image_multiple = null;
String tdTag1 = null;
String tdTag2 = null;
if (imageSingle != null && !(imageSingle == "" ))
image_single = "<img src=\""+ request.getContextPath() +"/images/"+imageSingle+".gif\" border=\"0\">";
else
image_single = "---";
if (imageMultiple != null && !(imageMultiple == "" ))
image_multiple = "<img src=\""+ request.getContextPath() +"/images/"+imageMultiple+".gif\" border=\"0\">";
else
image_multiple = "---";
if (image_single == "---"){
tdTag1 = "<td class=\"cell\" align = \"center\" style = \"cursor:default\">"+image_single+"</td>";
}else{
tdTag1 = "<td class=\"cell\" align = \"center\" onmouseover=\"menuItemFocus(this);\" onmouseout=\"menuItemNormal(this);\" onclick=\"javascript:" + jsMethodSingle + ";\">"+image_single+"</td>";
}
if (image_multiple == "---"){
tdTag2 = "<td class=\"cell\" align = \"center\" style = \"cursor:default\">"+image_multiple+"</td>" ;
}else{
tdTag2 = "<td class=\"cell\" align = \"center\" onmouseover=\"menuItemFocus(this);\" onmouseout=\"menuItemNormal(this);\" onclick=\"javascript:" + jsMethodMultiple + ";\">"+image_multiple+"</td>";
}
String tag ="<tr>"
+ tdTag1
+"<td class=\"cell\" align = \"left\">"+ value +"</td>"
+ tdTag2
+"</tr>";
return tag;
}
public String displayEdit(){
String tag = generateTR("edit","edit_16","performUncheckedCkBoxAction('edit')","block_edit_new","performAction('blockEdit')","Edit");
return tag;
}
public String displayView(){
String tag = generateTR("view","16_preview","viewAC()","","","View");
return tag;
}
public String displayDesignate(){
String tag = generateTR("","16_designate","performUncheckedCkBoxAction('designate')","16_designate_multi","performAction('designate')","Designate");
return tag;
}
public String displayViewDetiails(){
String tag = generateTR("details","cde-book-16","GetDetails()","","","View Details");
return tag;
}
public String displayGetAssociatedDE(){
String tag = generateTR("associatedDE","16_associated","getAssocDEs()","","","Get Associated DE");
return tag;
}
public String displayGetAssociatedDEC(){
String tag = generateTR("associatedDEC","16_associated","getAssocDECs()","","","Get Associated DEC");
return tag;
}
public String displayGetAssociatedVD(){
String tag = generateTR("associatedVD","16_associated","getAssocVDs()","","","Get Associated VD");
return tag;
}
public String displayUploadDoc(){
String tag = generateTR("uploadDoc","16_uploading","performUncheckedCkBoxAction('uploadDoc')","","","Upload Document(s)");
return tag;
}
public String displayMonitor(){
String tag = generateTR("","monitor","performUncheckedCkBoxAction('monitor')","monitor_multi","performAction('monitor')","Monitor");
return tag;
}
public String displayUnMonitor(){
String tag = generateTR("","unmonitor","performUncheckedCkBoxAction('unmonitor')","unmonitor_multi","performAction('unmonitor')","Unmonitor");
return tag;
}
public String displayNewUsingExisting(){
String tag = generateTR("newUE","16_new_use_existing","createNew('newUsingExisting')","","","New Using Existing");
return tag;
}
public String displayNewVersion(){
String tag = generateTR("newVersion","16_new_version","createNew('newVersion')","","","New Version");
return tag;
}
public String displayAppend(){
String tag = generateTR("","","","16_append","performAction('append')","Append");
return tag;
}
}
| true | true | public int doEndTag() throws JspException {
getSessionAttributes();
HttpSession session = pageContext.getSession();
int rowsChecked = 0;
if (vCheckList!=null){
rowsChecked = vCheckList.size();
}
JspWriter objMenu = this.pageContext.getOut();
if (selACType != null) {
try {
objMenu.println("<table style = \"border-collapse: collapse; bgcolor: #d8d8df\">");
objMenu.println("<tr><td colspan=\"3\"><p style=\"margin: 0px 0px 5px 0px; color: red\"><span id=\"selCnt\">" + rowsChecked + "</span> Record(s) Selected</p></td></tr>");
objMenu.println("<tr style = \"background-color:#4876FF\"><td class=\"cell\" align=\"center\"><input type=\"checkbox\" onclick=\"this.checked=false;\"></td><td class=\"cell\" align=\"center\"><b><font color = \"#FFFFFF\">Action</b></td><td class=\"cell\" align=\"center\"><input type=\"checkbox\" checked onclick=\"this.checked=true;\"></td></tr>");
if ((selACType).equals("DataElement")) {
objMenu.println(displayEdit()
+ displayView()
+ displayDesignate()
+ displayViewDetiails()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("DataElementConcept")) {
objMenu.println(displayEdit()
+ displayView()
+ displayGetAssociatedDE()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("ValueDomain")) {
objMenu.println(displayEdit()
+ displayView()
+ displayGetAssociatedDE()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("ConceptualDomain")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("PermissibleValue")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ClassSchemeItems")){
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ValueMeaning")) {
objMenu.println(generateTR("edit","edit","performUncheckedCkBoxAction('edit')","","","Edit")
+ displayView()
+ displayGetAssociatedDE()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ConceptClass")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ObjectClass")){
objMenu.println(displayGetAssociatedDEC());
}
if ((selACType).equals("Property")) {
objMenu.println(displayGetAssociatedDEC());
}
objMenu.println(generateTR("","","","16_show_rows","ShowSelectedRows(true)","Show Selected Rows"));
objMenu.println(generateTR("","","","select_all","SelectAllCheckBox()","Select All"));
objMenu.println(generateTR("","","","unselect_all","UnSelectAllCheckBox()","Unselect All"));
objMenu.println("</table></div>");
} catch (IOException e) {
e.printStackTrace();
}
}
return EVAL_PAGE;
}
| public int doEndTag() throws JspException {
getSessionAttributes();
HttpSession session = pageContext.getSession();
int rowsChecked = 0;
if (vCheckList!=null){
rowsChecked = vCheckList.size();
}
JspWriter objMenu = this.pageContext.getOut();
if (selACType != null) {
try {
objMenu.println("<table style = \"border-collapse: collapse; background-color: #d8d8df\">");
objMenu.println("<tr><td colspan=\"3\"><p style=\"margin: 0px 0px 5px 0px; color: red\"><span id=\"selCnt\">" + rowsChecked + "</span> Record(s) Selected</p></td></tr>");
objMenu.println("<tr style = \"background-color:#4876FF\"><td class=\"cell\" align=\"center\"><input type=\"checkbox\" onclick=\"this.checked=false;\"></td><td class=\"cell\" align=\"center\"><b><font color = \"#FFFFFF\">Action</b></td><td class=\"cell\" align=\"center\"><input type=\"checkbox\" checked onclick=\"this.checked=true;\"></td></tr>");
if ((selACType).equals("DataElement")) {
objMenu.println(displayEdit()
+ displayView()
+ displayDesignate()
+ displayViewDetiails()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("DataElementConcept")) {
objMenu.println(displayEdit()
+ displayView()
+ displayGetAssociatedDE()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("ValueDomain")) {
objMenu.println(displayEdit()
+ displayView()
+ displayGetAssociatedDE()
+ displayUploadDoc()
+ displayMonitor()
+ displayUnMonitor()
+ displayNewUsingExisting()
+ displayNewVersion()
+ displayAppend());
}
if ((selACType).equals("ConceptualDomain")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("PermissibleValue")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ClassSchemeItems")){
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ValueMeaning")) {
objMenu.println(generateTR("edit","edit","performUncheckedCkBoxAction('edit')","","","Edit")
+ displayView()
+ displayGetAssociatedDE()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ConceptClass")) {
objMenu.println(displayGetAssociatedDE()
+ displayGetAssociatedDEC()
+ displayGetAssociatedVD());
}
if ((selACType).equals("ObjectClass")){
objMenu.println(displayGetAssociatedDEC());
}
if ((selACType).equals("Property")) {
objMenu.println(displayGetAssociatedDEC());
}
objMenu.println(generateTR("","","","16_show_rows","ShowSelectedRows(true)","Show Selected Rows"));
objMenu.println(generateTR("","","","select_all","SelectAllCheckBox()","Select All"));
objMenu.println(generateTR("","","","unselect_all","UnSelectAllCheckBox()","Unselect All"));
objMenu.println("</table></div>");
} catch (IOException e) {
e.printStackTrace();
}
}
return EVAL_PAGE;
}
|
diff --git a/app/models/Location.java b/app/models/Location.java
index 7ce475e..e0eec0b 100644
--- a/app/models/Location.java
+++ b/app/models/Location.java
@@ -1,232 +1,232 @@
package models;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
import util.LocationFilter;
import vo.Track;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.SqlQuery;
import com.avaje.ebean.SqlRow;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import controllers.Application;
@Entity
public class Location extends Model implements Comparable<Location> {
private static final long serialVersionUID = 1973445298197201545L;
@Id
private Long id;
@Column
private boolean isStart = false;
@Column(nullable = false)
private Date serverDate = null;
@Embedded
private User user = null;
@Column(nullable = false)
protected Double lat = 0.0d;
@Column(nullable = false)
protected Double lon = 0.0d;
public Location() {
this.serverDate = new Date();
}
public Location(final User aUser, final Double aLat, final Double aLon,
final Boolean aIsStart) {
this.user = aUser;
this.lat = aLat;
this.lon = aLon;
this.isStart = aIsStart;
this.serverDate = new Date();
}
public boolean isStart() {
return isStart;
}
public void setStart(final boolean isStart) {
this.isStart = isStart;
}
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
public Date getServerDate() {
return serverDate;
}
public void setServerDate(final Date serverDate) {
this.serverDate = serverDate;
}
public Double getLat() {
return lat;
}
public void setLat(final Double x) {
this.lat = x;
}
public Double getLon() {
return lon;
}
public void setLon(final Double y) {
this.lon = y;
}
private static Finder<Long, Location> finder = new Finder<Long, Location>(
Long.class, Location.class);
public static void saveLocation(final Location l) {
l.save();
}
public static int locationsCount() {
return finder.findRowCount();
}
public static List<User> getUsers() {
SqlQuery query = Ebean.createSqlQuery("SELECT DISTINCT user_id FROM location;");
List<SqlRow> locations = query.findList();
return Lists.transform(locations, new Function<SqlRow, User>() {
@Override
public User apply(@Nullable SqlRow arg0) {
return new User(arg0.getString("user_id"));
}
});
}
public static void removeLocationsForUser(String id) {
List<Location> locations = finder.where().eq("user_id", id).findList();
for (Location loc : locations) {
loc.delete();
}
}
public static List<Location> getBoundedLocations(final Float minLat,
final Float maxLat, final Float minLon, final Float maxLon, String givenUserId) {
List<Location> result = new ArrayList<Location>();
List<Location> locations = null;
if (givenUserId != null && !givenUserId.isEmpty() && !givenUserId.equals(Application.FULLSCREEN_MAP_ID)){
locations = finder.where().eq("user.id", givenUserId).orderBy("serverDate").findList();
}
else{
locations = finder.where().orderBy("serverDate").findList();
}
// results ordered by tracks
List<Track> resultTracks = new ArrayList<Track>();
// a map containing tracks mapped by user id, ie last track seen for a user
Map<String,Track> tracks = new HashMap<String,Track>();
// current track user id
String userId;
// current track
Track track;
for (Location loc : locations) {
userId = loc.getUser().getId();
// new track
if (loc.isStart || !tracks.containsKey(userId)) {
// !tracks.containsKey(userId) -->> case if the data is not well formatted (ie not starting with a isStart)
track = new Track();
// if not the first track for user, store last one if it's in the bounds
if (tracks.containsKey(userId) && tracks.get(userId).isInBounds()) {
resultTracks.add(tracks.remove(userId));
}
tracks.put(userId,track);
} else {
track = tracks.get(userId);
}
// update the track
track.addLocation(loc);
// set is in bounds
if (!track.isInBounds() &&
loc.lat >= minLat && loc.lat <= maxLat &&
loc.lon >= minLon && loc.lon <= maxLon) {
track.setInBounds(true);
}
}
// fill resultTracks with remaining tracks
for (Track tck : tracks.values()) {
if (tck.isInBounds()) {
resultTracks.add(tck);
}
}
// track to location translation
for (Track tck : resultTracks) {
result.addAll(tck.getLocations());
}
- List<Location> finalList = new ArrayList<Location>();
- finalList.addAll(LocationFilter.filterNearLocations(result, 2.0));
- Collections.sort(finalList);
- return finalList;
+// List<Location> finalList = new ArrayList<Location>();
+// finalList.addAll(LocationFilter.filterNearLocations(result, 2.0));
+// Collections.sort(finalList);
+ return result;
}
@Override
public String toString(){
return "["+id+"] lat:"+lat+" lon:"+lon+" start:"+isStart;
}
@Override
public int compareTo(Location o) {
int cmp = 0;
if (this.getServerDate().getTime() > o.getServerDate().getTime()){
cmp = 1;
}
else if (this.getServerDate().getTime() < o.getServerDate().getTime()){
cmp = -1;
}
return cmp;
}
}
| true | true | public static List<Location> getBoundedLocations(final Float minLat,
final Float maxLat, final Float minLon, final Float maxLon, String givenUserId) {
List<Location> result = new ArrayList<Location>();
List<Location> locations = null;
if (givenUserId != null && !givenUserId.isEmpty() && !givenUserId.equals(Application.FULLSCREEN_MAP_ID)){
locations = finder.where().eq("user.id", givenUserId).orderBy("serverDate").findList();
}
else{
locations = finder.where().orderBy("serverDate").findList();
}
// results ordered by tracks
List<Track> resultTracks = new ArrayList<Track>();
// a map containing tracks mapped by user id, ie last track seen for a user
Map<String,Track> tracks = new HashMap<String,Track>();
// current track user id
String userId;
// current track
Track track;
for (Location loc : locations) {
userId = loc.getUser().getId();
// new track
if (loc.isStart || !tracks.containsKey(userId)) {
// !tracks.containsKey(userId) -->> case if the data is not well formatted (ie not starting with a isStart)
track = new Track();
// if not the first track for user, store last one if it's in the bounds
if (tracks.containsKey(userId) && tracks.get(userId).isInBounds()) {
resultTracks.add(tracks.remove(userId));
}
tracks.put(userId,track);
} else {
track = tracks.get(userId);
}
// update the track
track.addLocation(loc);
// set is in bounds
if (!track.isInBounds() &&
loc.lat >= minLat && loc.lat <= maxLat &&
loc.lon >= minLon && loc.lon <= maxLon) {
track.setInBounds(true);
}
}
// fill resultTracks with remaining tracks
for (Track tck : tracks.values()) {
if (tck.isInBounds()) {
resultTracks.add(tck);
}
}
// track to location translation
for (Track tck : resultTracks) {
result.addAll(tck.getLocations());
}
List<Location> finalList = new ArrayList<Location>();
finalList.addAll(LocationFilter.filterNearLocations(result, 2.0));
Collections.sort(finalList);
return finalList;
}
| public static List<Location> getBoundedLocations(final Float minLat,
final Float maxLat, final Float minLon, final Float maxLon, String givenUserId) {
List<Location> result = new ArrayList<Location>();
List<Location> locations = null;
if (givenUserId != null && !givenUserId.isEmpty() && !givenUserId.equals(Application.FULLSCREEN_MAP_ID)){
locations = finder.where().eq("user.id", givenUserId).orderBy("serverDate").findList();
}
else{
locations = finder.where().orderBy("serverDate").findList();
}
// results ordered by tracks
List<Track> resultTracks = new ArrayList<Track>();
// a map containing tracks mapped by user id, ie last track seen for a user
Map<String,Track> tracks = new HashMap<String,Track>();
// current track user id
String userId;
// current track
Track track;
for (Location loc : locations) {
userId = loc.getUser().getId();
// new track
if (loc.isStart || !tracks.containsKey(userId)) {
// !tracks.containsKey(userId) -->> case if the data is not well formatted (ie not starting with a isStart)
track = new Track();
// if not the first track for user, store last one if it's in the bounds
if (tracks.containsKey(userId) && tracks.get(userId).isInBounds()) {
resultTracks.add(tracks.remove(userId));
}
tracks.put(userId,track);
} else {
track = tracks.get(userId);
}
// update the track
track.addLocation(loc);
// set is in bounds
if (!track.isInBounds() &&
loc.lat >= minLat && loc.lat <= maxLat &&
loc.lon >= minLon && loc.lon <= maxLon) {
track.setInBounds(true);
}
}
// fill resultTracks with remaining tracks
for (Track tck : tracks.values()) {
if (tck.isInBounds()) {
resultTracks.add(tck);
}
}
// track to location translation
for (Track tck : resultTracks) {
result.addAll(tck.getLocations());
}
// List<Location> finalList = new ArrayList<Location>();
// finalList.addAll(LocationFilter.filterNearLocations(result, 2.0));
// Collections.sort(finalList);
return result;
}
|
diff --git a/fap/compiler/src/es.fap.simpleled.ui/src/es/fap/simpleled/ui/documentation/JsonDocumentation.java b/fap/compiler/src/es.fap.simpleled.ui/src/es/fap/simpleled/ui/documentation/JsonDocumentation.java
index c6b3abaa..b2c06572 100644
--- a/fap/compiler/src/es.fap.simpleled.ui/src/es/fap/simpleled/ui/documentation/JsonDocumentation.java
+++ b/fap/compiler/src/es.fap.simpleled.ui/src/es/fap/simpleled/ui/documentation/JsonDocumentation.java
@@ -1,99 +1,99 @@
package es.fap.simpleled.ui.documentation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.Keyword;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import es.fap.simpleled.led.util.DocElemento;
import es.fap.simpleled.led.util.DocParametro;
public class JsonDocumentation {
static Map<String, DocElemento> mapa;
private static String firstLower(String name){
return name.substring(0, 1).toLowerCase() + name.substring(1);
}
public static String getRuleName(EObject semantic){
return semantic.getClass().getSimpleName().split("Impl")[0];
}
public static DocElemento getElemento(Keyword keyword, EObject semantic){
initializeMap();
String ruleName = getRuleName(semantic);
String key = firstLower(ruleName);
DocElemento elemento = mapa.get(key);
if (keyword.getValue().equals(FapDocumentationProvider.docRules.get(ruleName))){
elemento.keyword = keyword.getValue();
return elemento;
}
return null;
}
public static DocParametro getParametro(Keyword keyword, EObject semantic){
return getParametro(keyword.getValue(), semantic);
}
public static DocParametro getParametro(String keyword, EObject semantic){
initializeMap();
String key = firstLower(semantic.getClass().getSimpleName().split("Impl")[0]);
DocElemento elemento = mapa.get(key);
if (elemento == null){
return null;
}
for (DocParametro p: elemento.parametros){
if (p.keyword.equals(keyword)){
return p;
}
}
return null;
}
private static void initializeMap(){
- mapa = null;
+// mapa = null; // Para debuggear
if (mapa == null){
mapa = new HashMap<String, DocElemento>();
Gson gson = new Gson();
Type tDocElemento = new TypeToken<DocElemento>(){}.getType();
Type tListString = new TypeToken<List<String>>(){}.getType();
try {
List<String> elementos = gson.fromJson(convertStreamToString(JsonDocumentation.class.getResourceAsStream("json/all.json")), tListString);
for (String name: elementos){
DocElemento e = gson.fromJson(convertStreamToString(JsonDocumentation.class.getResourceAsStream("json/" + name + ".json")), tDocElemento);
mapa.put(e.nombre, e);
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
public static String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
| true | true | private static void initializeMap(){
mapa = null;
if (mapa == null){
mapa = new HashMap<String, DocElemento>();
Gson gson = new Gson();
Type tDocElemento = new TypeToken<DocElemento>(){}.getType();
Type tListString = new TypeToken<List<String>>(){}.getType();
try {
List<String> elementos = gson.fromJson(convertStreamToString(JsonDocumentation.class.getResourceAsStream("json/all.json")), tListString);
for (String name: elementos){
DocElemento e = gson.fromJson(convertStreamToString(JsonDocumentation.class.getResourceAsStream("json/" + name + ".json")), tDocElemento);
mapa.put(e.nombre, e);
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
| private static void initializeMap(){
// mapa = null; // Para debuggear
if (mapa == null){
mapa = new HashMap<String, DocElemento>();
Gson gson = new Gson();
Type tDocElemento = new TypeToken<DocElemento>(){}.getType();
Type tListString = new TypeToken<List<String>>(){}.getType();
try {
List<String> elementos = gson.fromJson(convertStreamToString(JsonDocumentation.class.getResourceAsStream("json/all.json")), tListString);
for (String name: elementos){
DocElemento e = gson.fromJson(convertStreamToString(JsonDocumentation.class.getResourceAsStream("json/" + name + ".json")), tDocElemento);
mapa.put(e.nombre, e);
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
|
diff --git a/organization/src/main/java/module/organization/domain/AccountabilityVersion.java b/organization/src/main/java/module/organization/domain/AccountabilityVersion.java
index b7fe5ed..fb89242 100644
--- a/organization/src/main/java/module/organization/domain/AccountabilityVersion.java
+++ b/organization/src/main/java/module/organization/domain/AccountabilityVersion.java
@@ -1,166 +1,165 @@
/*
* @(#)AccountabilityVersion.java
*
* Copyright 2012 Instituto Superior Tecnico
* Founding Authors: João Figueiredo, Luis Cruz
*
* https://fenix-ashes.ist.utl.pt/
*
* This file is part of the Organization Module.
*
* The Organization Module 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.
*
* The Organization Module 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 the Organization Module. If not, see <http://www.gnu.org/licenses/>.
*
*/
package module.organization.domain;
import jvstm.cps.ConsistencyPredicate;
import module.organization.domain.util.OrganizationConsistencyException;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import pt.ist.bennu.core.domain.User;
/**
*
* @author João Antunes
* @author João Neves
* @author Susana Fernandes
*
*/
public class AccountabilityVersion extends AccountabilityVersion_Base {
private AccountabilityVersion(LocalDate beginDate, LocalDate endDate, Accountability acc, boolean erased) {
super();
super.setAccountability(acc);
super.setErased(erased);
super.setBeginDate(beginDate);
super.setEndDate(endDate);
super.setCreationDate(new DateTime());
super.setUserWhoCreated(pt.ist.bennu.core.applicationTier.Authenticate.UserView.getCurrentUser());
}
// let's protect all of the methods that could compromise the workings of
// the Acc. Version
@Deprecated
@Override
public void setAccountability(Accountability accountability) {
throw new UnsupportedOperationException("this.slot.shouldn't.be.editable.make.new.object.instead");
}
@Deprecated
@Override
public void setErased(boolean erased) {
throw new UnsupportedOperationException("this.slot.shouldn't.be.editable.make.new.object.instead");
}
@Deprecated
@Override
public void setBeginDate(LocalDate beginDate) {
throw new UnsupportedOperationException("this.slot.shouldn't.be.editable.make.new.object.instead");
}
@Deprecated
@Override
public void setEndDate(LocalDate endDate) {
throw new UnsupportedOperationException("this.slot.shouldn't.be.editable.make.new.object.instead");
}
@Deprecated
@Override
public void setCreationDate(DateTime creationDate) {
throw new UnsupportedOperationException("this.slot.shouldn't.be.editable.make.new.object.instead");
}
@Deprecated
@Override
public void setUserWhoCreated(User userWhoCreated) {
throw new UnsupportedOperationException("this.slot.shouldn't.be.editable.make.new.object.instead");
}
@ConsistencyPredicate
public boolean checkIsConnectedToList() {
return (hasPreviousAccVersion() && !hasAccountability()) || (!hasPreviousAccVersion() && hasAccountability());
}
@ConsistencyPredicate
public boolean checkErasedAsFinalVersion() {
return !getErased() || hasAccountability();
}
@ConsistencyPredicate(OrganizationConsistencyException.class)
protected boolean checkDateInterval() {
return getBeginDate() != null && (getEndDate() == null || !getBeginDate().isAfter(getEndDate()));
}
public void delete() {
super.setUserWhoCreated(null);
deleteDomainObject();
}
/**
* It creates a new AccountabilityHistory item and pushes the others (if
* they exist)
*
* @param userWhoCreated
* @param instantOfCreation
* @param beginDate
* @param endDate
* @param acc
* the Accountability which
* @param active
* if true, the new AccountabilityHistory will be marked as
* active, if it is false it is equivalent of deleting the new
* AccountabilityHistory
*
*
*/
protected static void insertAccountabilityVersion(LocalDate beginDate, LocalDate endDate, Accountability acc, boolean erased) {
if (acc == null)
throw new IllegalArgumentException("cant.provide.a.null.accountability");
// let's check on the first case i.e. when the given acc does not have
// an AccountabilityHistory associated
AccountabilityVersion firstAccHistory = acc.getAccountabilityVersion();
AccountabilityVersion newAccountabilityHistory = new AccountabilityVersion(beginDate, endDate, acc, erased);
if (firstAccHistory == null) {
//we are the first ones, let's just create ourselves
if (erased) {
throw new IllegalArgumentException("creating.a.deleted.acc.does.not.make.sense"); //we shouldn't be creating a deleted accountability to start with!
}
} else {
// let's push all of the next accHistories into their rightful
// position
if (firstAccHistory.getBeginDate().equals(beginDate)
&& firstAccHistory.getErased() == erased
&& matchingDates(firstAccHistory.getEndDate(), endDate)) {
// do not create a new version with exactly the same data
- return;
+ throw new IllegalArgumentException("creating.a.redundant.accountability.version.does.not.make.sense");
}
- firstAccHistory.setPreviousAccVersion(newAccountabilityHistory);
newAccountabilityHistory.setNextAccVersion(firstAccHistory);
}
}
public static boolean redundantInfo(AccountabilityVersion av1, AccountabilityVersion av2) {
return ((av1.getBeginDate().equals(av2.getBeginDate())) && (av1.getErased() == av2.getErased()) && matchingDates(
av1.getEndDate(), av2.getEndDate()));
}
private static boolean matchingDates(LocalDate date1, LocalDate date2) {
if (date1 == null) {
return date2 == null;
}
return date1.equals(date2);
}
}
| false | true | protected static void insertAccountabilityVersion(LocalDate beginDate, LocalDate endDate, Accountability acc, boolean erased) {
if (acc == null)
throw new IllegalArgumentException("cant.provide.a.null.accountability");
// let's check on the first case i.e. when the given acc does not have
// an AccountabilityHistory associated
AccountabilityVersion firstAccHistory = acc.getAccountabilityVersion();
AccountabilityVersion newAccountabilityHistory = new AccountabilityVersion(beginDate, endDate, acc, erased);
if (firstAccHistory == null) {
//we are the first ones, let's just create ourselves
if (erased) {
throw new IllegalArgumentException("creating.a.deleted.acc.does.not.make.sense"); //we shouldn't be creating a deleted accountability to start with!
}
} else {
// let's push all of the next accHistories into their rightful
// position
if (firstAccHistory.getBeginDate().equals(beginDate)
&& firstAccHistory.getErased() == erased
&& matchingDates(firstAccHistory.getEndDate(), endDate)) {
// do not create a new version with exactly the same data
return;
}
firstAccHistory.setPreviousAccVersion(newAccountabilityHistory);
newAccountabilityHistory.setNextAccVersion(firstAccHistory);
}
}
| protected static void insertAccountabilityVersion(LocalDate beginDate, LocalDate endDate, Accountability acc, boolean erased) {
if (acc == null)
throw new IllegalArgumentException("cant.provide.a.null.accountability");
// let's check on the first case i.e. when the given acc does not have
// an AccountabilityHistory associated
AccountabilityVersion firstAccHistory = acc.getAccountabilityVersion();
AccountabilityVersion newAccountabilityHistory = new AccountabilityVersion(beginDate, endDate, acc, erased);
if (firstAccHistory == null) {
//we are the first ones, let's just create ourselves
if (erased) {
throw new IllegalArgumentException("creating.a.deleted.acc.does.not.make.sense"); //we shouldn't be creating a deleted accountability to start with!
}
} else {
// let's push all of the next accHistories into their rightful
// position
if (firstAccHistory.getBeginDate().equals(beginDate)
&& firstAccHistory.getErased() == erased
&& matchingDates(firstAccHistory.getEndDate(), endDate)) {
// do not create a new version with exactly the same data
throw new IllegalArgumentException("creating.a.redundant.accountability.version.does.not.make.sense");
}
newAccountabilityHistory.setNextAccVersion(firstAccHistory);
}
}
|
diff --git a/votable/src/main/uk/ac/starlink/votable/VOTableWriter.java b/votable/src/main/uk/ac/starlink/votable/VOTableWriter.java
index ff8b8091b..2c92a98dd 100644
--- a/votable/src/main/uk/ac/starlink/votable/VOTableWriter.java
+++ b/votable/src/main/uk/ac/starlink/votable/VOTableWriter.java
@@ -1,424 +1,424 @@
package uk.ac.starlink.votable;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.logging.Logger;
import uk.ac.starlink.fits.FitsTableWriter;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.table.StarTableWriter;
/**
* Implementation of the <tt>StarTableWriter</tt> interface for
* VOTables. The <tt>dataFormat</tt> and <tt>inline</tt> attributes
* can be modified to affect how the bulk cell data are output -
* this may be in TABLEDATA, FITS or BINARY format, and in the
* latter two cases may be either inline as base64 encoded CDATA or
* to a separate stream.
*
* @author Mark Taylor (Starlink)
*/
public class VOTableWriter implements StarTableWriter {
private DataFormat dataFormat = DataFormat.TABLEDATA;
private boolean inline = true;
private String xmlDeclaration = DEFAULT_XML_DECLARATION;
private String doctypeDeclaration = DEFAULT_DOCTYPE_DECLARATION;
private String votableVersion = DEFAULT_VOTABLE_VERSION;
/** Default XML declaration in written documents. */
public static final String DEFAULT_XML_DECLARATION =
"<?xml version='1.0'?>";
/** Default document type declaration in written documents. */
public static final String DEFAULT_DOCTYPE_DECLARATION = "";
/** Default VOTABLE version number. */
public static final String DEFAULT_VOTABLE_VERSION = "1.1";
private static final Logger logger =
Logger.getLogger( "uk.ac.starlink.votable" );
/**
* Constructs a default VOTableWriter.
* Output is in TABLEDATA format.
*/
public VOTableWriter() {
this( DataFormat.TABLEDATA, true );
}
/**
* Constructs a VOTableWriter with specified output characteristics.
*
* @param dataFormat the format in which tables will be written
* @param inline whether output of streamed formats should be
* inline and base64-encoded or not
*/
public VOTableWriter( DataFormat dataFormat, boolean inline ) {
this.dataFormat = dataFormat;
this.inline = inline;
}
/**
* Writes a StarTable to a given location.
* The <tt>location</tt> is interpreted as a filename, unless it
* is the string "<tt>-</tt>", in which case it is taken to
* mean <tt>System.out</tt>.
* <p>
* Currently, an entire XML VOTable document is written,
* and the TABLEDATA format (all table cells written inline
* as separate XML elements) is used.
*
* @param startab the table to write
* @param location the filename to which to write the table
*/
public void writeStarTable( StarTable startab, String location )
throws IOException {
/* Get the stream to write to. */
OutputStream out;
File file;
if ( location.equals( "-" ) ) {
file = null;
out = System.out;
}
else {
file = new File( location );
out = new BufferedOutputStream( new FileOutputStream( file ) );
}
writeStarTable( startab, out, file );
}
/**
* Writes a StarTable to a given stream; must be inline.
* Same as <code>writeStarTable(startab,out,null)</code>
*
* @param startab the table to write
* @param out the stream down which to write the table
*/
public void writeStarTable( StarTable startab, OutputStream out )
throws IOException {
writeStarTable( startab, out, null );
}
/**
* Writes a StarTable to a given stream.
*
* @param startab the table to write
* @param out the stream down which to write the table
* @param file the filename to which <tt>out</tt> refers; this is used
* if necessary to come up with a suitable filename for
* related files which need to be written. May be <tt>null</tt>.
*/
public void writeStarTable( StarTable startab, OutputStream out, File file )
throws IOException {
/* For most of the output we write to a Writer; it is obtained
* here and uses the default encoding. If we write bulk data
* into the XML (using Base64 encoding) we write that direct to
* the underlying output stream, taking care to flush before and
* after. This relies on the fact that the characters output
* from the base64 encoding have 1-byte representations in the
* XML encoding we are using which are identical to their base64
* byte equivalents. So in the line below which constructs a
* Writer from an OutputStream, don't do it using e.g. UTF-16
* encoding for which that wouldn't hold.
*
* Although we frequently want to write a string followed by a
* new line, we don't use a PrintWriter here, since that doesn't
* throw any exceptions; we would like exceptions to be thrown
* where they occur. */
BufferedWriter writer =
new BufferedWriter( new OutputStreamWriter( out ) );
/* Get the format to provide a configuration object which describes
* exactly how the data from each cell is going to get written. */
VOSerializer serializer =
VOSerializer.makeSerializer( dataFormat, startab );
/* Output preamble. */
writer.write( xmlDeclaration );
writer.newLine();
if ( doctypeDeclaration != null && doctypeDeclaration.length() > 0 ) {
writer.write( doctypeDeclaration );
}
writer.newLine();
writer.write( "<VOTABLE" );
if ( votableVersion != null &&
votableVersion.matches( "1.[1-9]" ) ) {
writer.write( serializer.formatAttribute( "version",
votableVersion ) );
if ( doctypeDeclaration == null ||
doctypeDeclaration.length() == 0 ) {
writer.newLine();
writer.write( serializer.formatAttribute(
"xmlns:xsi",
"http://www.w3.org/2001/"
+ "XMLSchema-instance" ) );
writer.newLine();
writer.write( serializer.formatAttribute(
"xsi:noNamespaceSchemaLocation",
- "http://www.ivoa.net/xml/VOTable/VOTable/v"
+ "http://www.ivoa.net/xml/VOTable/v"
+ votableVersion ) );
}
}
writer.write( ">" );
writer.newLine();
writer.write( "<!--" );
writer.newLine();
writer.write( " ! VOTable written by " +
serializer.formatText( this.getClass().getName() ) );
writer.newLine();
writer.write( " !-->" );
writer.newLine();
writer.write( "<RESOURCE>" );
writer.newLine();
/* Start the TABLE element itself. */
writer.write( "<TABLE" );
/* Write the table name if we have one. */
String tname = startab.getName();
if ( tname != null && tname.trim().length() > 0 ) {
writer.write( serializer.formatAttribute( "name", tname.trim() ) );
}
/* Write the number of rows if we know it (VOTable 1.1 only). */
if ( votableVersion.matches( "1.[1-9].*" ) ) {
long nrow = startab.getRowCount();
if ( nrow > 0 ) {
writer.write( serializer
.formatAttribute( "nrows",
Long.toString( nrow ) ) );
}
}
writer.write( ">" );
writer.newLine();
/* Output table parameters as PARAM elements. */
serializer.writeParams( writer );
/* Output a DESCRIPTION element if we have something suitable. */
serializer.writeDescription( writer );
/* Output FIELD headers as determined by this object. */
serializer.writeFields( writer );
/* Now write the DATA element. */
/* First Treat the case where we write data inline. */
if ( inline || file == null ) {
/* For elements which stream data to a Base64 encoding we
* write the element by hand using some package-private methods.
* This is just an efficiency measure - it means the
* writing is done directly to the base OutputStream rather
* than wrapping a new OutputStream round the Writer which
* is wrapped round the base OutputStream.
* But we could omit this stanza altogether and let the
* work get done by serializer.writeInlineDataElement.
* I don't know whether the efficiency hit is significant or not. */
if ( serializer instanceof VOSerializer.StreamableVOSerializer ) {
VOSerializer.StreamableVOSerializer streamer =
(VOSerializer.StreamableVOSerializer) serializer;
String tagname;
if ( dataFormat == DataFormat.FITS ) {
tagname = "FITS";
}
else if ( dataFormat == DataFormat.BINARY ) {
tagname = "BINARY";
}
else {
throw new AssertionError( "Unknown format "
+ dataFormat.toString() );
}
writer.write( "<DATA>" );
writer.newLine();
writer.write( '<' + tagname + '>' );
writer.newLine();
writer.write( "<STREAM encoding='base64'>" );
writer.newLine();
writer.flush();
Base64OutputStream b64strm =
new Base64OutputStream( new BufferedOutputStream( out ),
16 );
DataOutputStream dataout = new DataOutputStream( b64strm );
streamer.streamData( dataout );
dataout.flush();
b64strm.endBase64();
b64strm.flush();
writer.write( "</STREAM>" );
writer.newLine();
writer.write( "</" + tagname + ">" );
writer.newLine();
writer.write( "</DATA>" );
writer.newLine();
}
/* Non-optimized/non-STREAM case. */
else {
serializer.writeInlineDataElement( writer );
}
}
/* Treat the case where the data is streamed to an external file. */
else {
assert file != null;
String basename = file.getName();
int dotpos = basename.lastIndexOf( '.' );
basename = dotpos > 0 ? basename.substring( 0, dotpos )
: basename;
String extension = dataFormat == DataFormat.FITS ? ".fits" : ".bin";
String dataname = basename + "-data" + extension;
File datafile = new File( file.getParentFile(), dataname );
DataOutputStream dataout =
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream( datafile ) ) );
serializer.writeHrefDataElement( writer, dataname, dataout );
dataout.close();
}
/* Close the open elements and tidy up. */
writer.write( "</TABLE>" );
writer.newLine();
writer.write( "</RESOURCE>" );
writer.newLine();
writer.write( "</VOTABLE>" );
writer.newLine();
writer.flush();
}
/**
* Returns true for filenames with the extension ".xml", ".vot" or
* ".votable";
*
* @param name of the file
* @return true if <tt>filename</tt> looks like the home of a VOTable
*/
public boolean looksLikeFile( String filename ) {
return filename.endsWith( ".xml" )
|| filename.endsWith( ".vot" )
|| filename.endsWith( ".votable" );
}
public String getFormatName() {
StringBuffer fname = new StringBuffer( "votable" );
if ( dataFormat == DataFormat.TABLEDATA ) {
fname.append( "-tabledata" );
return fname.toString();
}
if ( dataFormat == DataFormat.FITS ) {
fname.append( "-fits" );
}
else if ( dataFormat == DataFormat.BINARY ) {
fname.append( "-binary" );
}
else {
assert false;
}
fname.append( inline ? "-inline" : "-href" );
return fname.toString();
}
/**
* Sets the format in which the table data will be output.
*
* @param bulk data format
*/
public void setDataFormat( DataFormat format ) {
this.dataFormat = format;
}
/**
* Returns the format in which this writer will output the bulk table data.
*
* @return bulk data format
*/
public DataFormat getDataFormat() {
return dataFormat;
}
/**
* Sets whether STREAM elements should be written inline or to an
* external file in the case of FITS and BINARY encoding.
*
* @param inline <tt>true</tt> iff streamed data will be encoded
* inline in the STREAM element
*/
public void setInline( boolean inline ) {
this.inline = inline;
}
/**
* Indicates whether STREAM elements will be written inline or to
* an external file in the case of FITS and BINARY encoding.
*
* @return <tt>true</tt> iff streamed data will be encoded inline in
* the STREAM element
*/
public boolean getInline() {
return inline;
}
/**
* Sets the XML declaration which will be used by this writer
* at the head of any document written.
* By default this is the value of {@link #DEFAULT_XML_DECLARATION}.
*
* @param new XML declaration
*/
public void setXMLDeclaration( String xmlDecl ) {
this.xmlDeclaration = xmlDecl;
}
/**
* Returns the XML declaration which is used by this writer
* at the head of any document written.
*/
public String getXMLDeclaration() {
return xmlDeclaration;
}
/**
* Sets the document type declaration which will be used by this writer
* at the head of any document written. By default this is
* the value of {@link #DEFAULT_DOCTYPE_DECLARATION}.
*
* @param doctypeDecl new declaration
*/
public void setDoctypeDeclaration( String doctypeDecl ) {
this.doctypeDeclaration = doctypeDecl;
}
/**
* Returns the document type declaration which is used by this writer
* at the head of any document written.
*
* @return doctypeDecl
*/
public String getDoctypeDeclaration() {
return doctypeDeclaration;
}
/**
* Returns a list of votable writers with variant values of attributes.
*
* @return non-standard VOTableWriters.
*/
public static StarTableWriter[] getStarTableWriters() {
return new StarTableWriter[] {
new VOTableWriter( DataFormat.TABLEDATA, true ),
new VOTableWriter( DataFormat.BINARY, true ),
new VOTableWriter( DataFormat.FITS, false ),
new VOTableWriter( DataFormat.BINARY, false ),
new VOTableWriter( DataFormat.FITS, true ),
};
}
}
| true | true | public void writeStarTable( StarTable startab, OutputStream out, File file )
throws IOException {
/* For most of the output we write to a Writer; it is obtained
* here and uses the default encoding. If we write bulk data
* into the XML (using Base64 encoding) we write that direct to
* the underlying output stream, taking care to flush before and
* after. This relies on the fact that the characters output
* from the base64 encoding have 1-byte representations in the
* XML encoding we are using which are identical to their base64
* byte equivalents. So in the line below which constructs a
* Writer from an OutputStream, don't do it using e.g. UTF-16
* encoding for which that wouldn't hold.
*
* Although we frequently want to write a string followed by a
* new line, we don't use a PrintWriter here, since that doesn't
* throw any exceptions; we would like exceptions to be thrown
* where they occur. */
BufferedWriter writer =
new BufferedWriter( new OutputStreamWriter( out ) );
/* Get the format to provide a configuration object which describes
* exactly how the data from each cell is going to get written. */
VOSerializer serializer =
VOSerializer.makeSerializer( dataFormat, startab );
/* Output preamble. */
writer.write( xmlDeclaration );
writer.newLine();
if ( doctypeDeclaration != null && doctypeDeclaration.length() > 0 ) {
writer.write( doctypeDeclaration );
}
writer.newLine();
writer.write( "<VOTABLE" );
if ( votableVersion != null &&
votableVersion.matches( "1.[1-9]" ) ) {
writer.write( serializer.formatAttribute( "version",
votableVersion ) );
if ( doctypeDeclaration == null ||
doctypeDeclaration.length() == 0 ) {
writer.newLine();
writer.write( serializer.formatAttribute(
"xmlns:xsi",
"http://www.w3.org/2001/"
+ "XMLSchema-instance" ) );
writer.newLine();
writer.write( serializer.formatAttribute(
"xsi:noNamespaceSchemaLocation",
"http://www.ivoa.net/xml/VOTable/VOTable/v"
+ votableVersion ) );
}
}
writer.write( ">" );
writer.newLine();
writer.write( "<!--" );
writer.newLine();
writer.write( " ! VOTable written by " +
serializer.formatText( this.getClass().getName() ) );
writer.newLine();
writer.write( " !-->" );
writer.newLine();
writer.write( "<RESOURCE>" );
writer.newLine();
/* Start the TABLE element itself. */
writer.write( "<TABLE" );
/* Write the table name if we have one. */
String tname = startab.getName();
if ( tname != null && tname.trim().length() > 0 ) {
writer.write( serializer.formatAttribute( "name", tname.trim() ) );
}
/* Write the number of rows if we know it (VOTable 1.1 only). */
if ( votableVersion.matches( "1.[1-9].*" ) ) {
long nrow = startab.getRowCount();
if ( nrow > 0 ) {
writer.write( serializer
.formatAttribute( "nrows",
Long.toString( nrow ) ) );
}
}
writer.write( ">" );
writer.newLine();
/* Output table parameters as PARAM elements. */
serializer.writeParams( writer );
/* Output a DESCRIPTION element if we have something suitable. */
serializer.writeDescription( writer );
/* Output FIELD headers as determined by this object. */
serializer.writeFields( writer );
/* Now write the DATA element. */
/* First Treat the case where we write data inline. */
if ( inline || file == null ) {
/* For elements which stream data to a Base64 encoding we
* write the element by hand using some package-private methods.
* This is just an efficiency measure - it means the
* writing is done directly to the base OutputStream rather
* than wrapping a new OutputStream round the Writer which
* is wrapped round the base OutputStream.
* But we could omit this stanza altogether and let the
* work get done by serializer.writeInlineDataElement.
* I don't know whether the efficiency hit is significant or not. */
if ( serializer instanceof VOSerializer.StreamableVOSerializer ) {
VOSerializer.StreamableVOSerializer streamer =
(VOSerializer.StreamableVOSerializer) serializer;
String tagname;
if ( dataFormat == DataFormat.FITS ) {
tagname = "FITS";
}
else if ( dataFormat == DataFormat.BINARY ) {
tagname = "BINARY";
}
else {
throw new AssertionError( "Unknown format "
+ dataFormat.toString() );
}
writer.write( "<DATA>" );
writer.newLine();
writer.write( '<' + tagname + '>' );
writer.newLine();
writer.write( "<STREAM encoding='base64'>" );
writer.newLine();
writer.flush();
Base64OutputStream b64strm =
new Base64OutputStream( new BufferedOutputStream( out ),
16 );
DataOutputStream dataout = new DataOutputStream( b64strm );
streamer.streamData( dataout );
dataout.flush();
b64strm.endBase64();
b64strm.flush();
writer.write( "</STREAM>" );
writer.newLine();
writer.write( "</" + tagname + ">" );
writer.newLine();
writer.write( "</DATA>" );
writer.newLine();
}
/* Non-optimized/non-STREAM case. */
else {
serializer.writeInlineDataElement( writer );
}
}
/* Treat the case where the data is streamed to an external file. */
else {
assert file != null;
String basename = file.getName();
int dotpos = basename.lastIndexOf( '.' );
basename = dotpos > 0 ? basename.substring( 0, dotpos )
: basename;
String extension = dataFormat == DataFormat.FITS ? ".fits" : ".bin";
String dataname = basename + "-data" + extension;
File datafile = new File( file.getParentFile(), dataname );
DataOutputStream dataout =
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream( datafile ) ) );
serializer.writeHrefDataElement( writer, dataname, dataout );
dataout.close();
}
/* Close the open elements and tidy up. */
writer.write( "</TABLE>" );
writer.newLine();
writer.write( "</RESOURCE>" );
writer.newLine();
writer.write( "</VOTABLE>" );
writer.newLine();
writer.flush();
}
| public void writeStarTable( StarTable startab, OutputStream out, File file )
throws IOException {
/* For most of the output we write to a Writer; it is obtained
* here and uses the default encoding. If we write bulk data
* into the XML (using Base64 encoding) we write that direct to
* the underlying output stream, taking care to flush before and
* after. This relies on the fact that the characters output
* from the base64 encoding have 1-byte representations in the
* XML encoding we are using which are identical to their base64
* byte equivalents. So in the line below which constructs a
* Writer from an OutputStream, don't do it using e.g. UTF-16
* encoding for which that wouldn't hold.
*
* Although we frequently want to write a string followed by a
* new line, we don't use a PrintWriter here, since that doesn't
* throw any exceptions; we would like exceptions to be thrown
* where they occur. */
BufferedWriter writer =
new BufferedWriter( new OutputStreamWriter( out ) );
/* Get the format to provide a configuration object which describes
* exactly how the data from each cell is going to get written. */
VOSerializer serializer =
VOSerializer.makeSerializer( dataFormat, startab );
/* Output preamble. */
writer.write( xmlDeclaration );
writer.newLine();
if ( doctypeDeclaration != null && doctypeDeclaration.length() > 0 ) {
writer.write( doctypeDeclaration );
}
writer.newLine();
writer.write( "<VOTABLE" );
if ( votableVersion != null &&
votableVersion.matches( "1.[1-9]" ) ) {
writer.write( serializer.formatAttribute( "version",
votableVersion ) );
if ( doctypeDeclaration == null ||
doctypeDeclaration.length() == 0 ) {
writer.newLine();
writer.write( serializer.formatAttribute(
"xmlns:xsi",
"http://www.w3.org/2001/"
+ "XMLSchema-instance" ) );
writer.newLine();
writer.write( serializer.formatAttribute(
"xsi:noNamespaceSchemaLocation",
"http://www.ivoa.net/xml/VOTable/v"
+ votableVersion ) );
}
}
writer.write( ">" );
writer.newLine();
writer.write( "<!--" );
writer.newLine();
writer.write( " ! VOTable written by " +
serializer.formatText( this.getClass().getName() ) );
writer.newLine();
writer.write( " !-->" );
writer.newLine();
writer.write( "<RESOURCE>" );
writer.newLine();
/* Start the TABLE element itself. */
writer.write( "<TABLE" );
/* Write the table name if we have one. */
String tname = startab.getName();
if ( tname != null && tname.trim().length() > 0 ) {
writer.write( serializer.formatAttribute( "name", tname.trim() ) );
}
/* Write the number of rows if we know it (VOTable 1.1 only). */
if ( votableVersion.matches( "1.[1-9].*" ) ) {
long nrow = startab.getRowCount();
if ( nrow > 0 ) {
writer.write( serializer
.formatAttribute( "nrows",
Long.toString( nrow ) ) );
}
}
writer.write( ">" );
writer.newLine();
/* Output table parameters as PARAM elements. */
serializer.writeParams( writer );
/* Output a DESCRIPTION element if we have something suitable. */
serializer.writeDescription( writer );
/* Output FIELD headers as determined by this object. */
serializer.writeFields( writer );
/* Now write the DATA element. */
/* First Treat the case where we write data inline. */
if ( inline || file == null ) {
/* For elements which stream data to a Base64 encoding we
* write the element by hand using some package-private methods.
* This is just an efficiency measure - it means the
* writing is done directly to the base OutputStream rather
* than wrapping a new OutputStream round the Writer which
* is wrapped round the base OutputStream.
* But we could omit this stanza altogether and let the
* work get done by serializer.writeInlineDataElement.
* I don't know whether the efficiency hit is significant or not. */
if ( serializer instanceof VOSerializer.StreamableVOSerializer ) {
VOSerializer.StreamableVOSerializer streamer =
(VOSerializer.StreamableVOSerializer) serializer;
String tagname;
if ( dataFormat == DataFormat.FITS ) {
tagname = "FITS";
}
else if ( dataFormat == DataFormat.BINARY ) {
tagname = "BINARY";
}
else {
throw new AssertionError( "Unknown format "
+ dataFormat.toString() );
}
writer.write( "<DATA>" );
writer.newLine();
writer.write( '<' + tagname + '>' );
writer.newLine();
writer.write( "<STREAM encoding='base64'>" );
writer.newLine();
writer.flush();
Base64OutputStream b64strm =
new Base64OutputStream( new BufferedOutputStream( out ),
16 );
DataOutputStream dataout = new DataOutputStream( b64strm );
streamer.streamData( dataout );
dataout.flush();
b64strm.endBase64();
b64strm.flush();
writer.write( "</STREAM>" );
writer.newLine();
writer.write( "</" + tagname + ">" );
writer.newLine();
writer.write( "</DATA>" );
writer.newLine();
}
/* Non-optimized/non-STREAM case. */
else {
serializer.writeInlineDataElement( writer );
}
}
/* Treat the case where the data is streamed to an external file. */
else {
assert file != null;
String basename = file.getName();
int dotpos = basename.lastIndexOf( '.' );
basename = dotpos > 0 ? basename.substring( 0, dotpos )
: basename;
String extension = dataFormat == DataFormat.FITS ? ".fits" : ".bin";
String dataname = basename + "-data" + extension;
File datafile = new File( file.getParentFile(), dataname );
DataOutputStream dataout =
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream( datafile ) ) );
serializer.writeHrefDataElement( writer, dataname, dataout );
dataout.close();
}
/* Close the open elements and tidy up. */
writer.write( "</TABLE>" );
writer.newLine();
writer.write( "</RESOURCE>" );
writer.newLine();
writer.write( "</VOTABLE>" );
writer.newLine();
writer.flush();
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/SDKOptionProvider.java b/org.emftext.sdk/src/org/emftext/sdk/SDKOptionProvider.java
index 5af3611ab..14335d008 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/SDKOptionProvider.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/SDKOptionProvider.java
@@ -1,187 +1,188 @@
package org.emftext.sdk;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.codegen.ecore.genmodel.GenFeature;
import org.eclipse.emf.ecore.EObject;
import org.emftext.runtime.IOptionProvider;
import org.emftext.runtime.IOptions;
import org.emftext.runtime.IResourcePostProcessor;
import org.emftext.runtime.IResourcePostProcessorProvider;
import org.emftext.runtime.resource.ITextResource;
import org.emftext.sdk.concretesyntax.Cardinality;
import org.emftext.sdk.concretesyntax.Choice;
import org.emftext.sdk.concretesyntax.CompoundDefinition;
import org.emftext.sdk.concretesyntax.CsString;
import org.emftext.sdk.concretesyntax.Definition;
import org.emftext.sdk.concretesyntax.QUESTIONMARK;
import org.emftext.sdk.concretesyntax.Rule;
import org.emftext.sdk.concretesyntax.STAR;
import org.emftext.sdk.concretesyntax.Sequence;
import org.emftext.sdk.concretesyntax.Terminal;
public class SDKOptionProvider implements IOptionProvider {
private static final String OPTIONAL_KEYWORD_WARNING =
"The keyword might be used stand alone and will not be reprinted in such case: ";
private static final String MULTIPLE_FEATURE_WARNING =
"The feature is used multiple times. Reprinting may fail for feature: ";
public Map<?, ?> getOptions() {
Map<String, Object> options = new HashMap<String, Object>();
options.put(IOptions.RESOURCE_POSTPROCESSOR_PROVIDER, new IResourcePostProcessorProvider() {
public IResourcePostProcessor getResourcePostProcessor() {
return new IResourcePostProcessor() {
public void process(ITextResource resource) {
checkReprintProblems(resource);
}
};
}
});
return options;
}
private void checkReprintProblems(ITextResource resource) {
checkForOptionalKeywords(resource);
checkForDuplicateReferences(resource);
}
private void checkForOptionalKeywords(ITextResource resource) {
for(Iterator<EObject> i = resource.getAllContents(); i.hasNext(); ) {
EObject next = i.next();
if (next instanceof CompoundDefinition) {
CompoundDefinition compoundDefinition = (CompoundDefinition) next;
- if (compoundDefinition.getCardinality() instanceof QUESTIONMARK) {
+ if (compoundDefinition.getCardinality() instanceof QUESTIONMARK ||
+ compoundDefinition.getCardinality() instanceof STAR) {
for (Sequence sequence : compoundDefinition.getDefinitions().getOptions()) {
boolean containsKeyword = false;
boolean restOptional = true;
for (Definition definition : sequence.getParts()) {
if (definition instanceof CsString) {
containsKeyword = true;
}
else if (!(definition.getCardinality() instanceof QUESTIONMARK ||
definition.getCardinality() instanceof STAR)) {
restOptional = false;
}
}
if(containsKeyword && restOptional) {
for (Definition definition : sequence.getParts()) {
if (definition instanceof CsString) {
CsString csString = (CsString) definition;
resource.addWarning(
OPTIONAL_KEYWORD_WARNING + csString.getValue(),
definition);
}
}
}
}
}
}
}
}
private void checkForDuplicateReferences(ITextResource resource) {
Iterator<EObject> iterator = resource.getAllContents();
while (iterator.hasNext()) {
final EObject next = iterator.next();
if (next instanceof Rule) {
final Rule rule = (Rule) next;
final List<Terminal> terminals = collectAllTerminals(rule);
for (Terminal terminal : terminals) {
final GenFeature feature = terminal.getFeature();
if (canCauseReprintProblem(rule.getDefinition(), feature)) {
resource.addWarning(
MULTIPLE_FEATURE_WARNING + feature.getName(),
terminal);
}
}
}
}
}
/**
* A feature causes a reprint problem if it appears multiple times in the
* definition of a rule and if a star or question mark appearance is followed
* by another appearance.
*
* Valid sequences of cardinalities are: 1-*, 1-1-*, 1-1-1-*.
* Invalid sequences are cardinalities are: ?-*, *-*, *-?, *-1.
*
* @param definition
* @param feature
* @return
*/
private boolean canCauseReprintProblem(Choice choice, GenFeature feature) {
return countProblematicOccurrences(choice, feature, false) > 1;
}
/**
* Counts the problematic occurrences of the given feature in a depth first
* manner. Occurrences are problematic if they either have a cardinality of
* star or question mark or if a star or question mark occurrence was found
* before (i.e., earlier in the traversal process).
*
* @param choice
* @param feature
* @param foundStarOrOptionalBefore
* @return
*/
private int countProblematicOccurrences(Choice choice, GenFeature feature, boolean foundStarOrOptionalBefore) {
int occurences = 0;
List<Sequence> choices = choice.getOptions();
for (Sequence sequence : choices) {
List<Definition> definitions = sequence.getParts();
for (Definition definition : definitions) {
// incorporate cardinality of the definition
final Cardinality cardinality = definition.getCardinality();
if (definition instanceof Terminal) {
Terminal terminal = (Terminal) definition;
if (terminal.getFeature() == feature) {
final boolean isStarOrOptional = cardinality instanceof STAR || cardinality instanceof QUESTIONMARK;
if (isStarOrOptional || foundStarOrOptionalBefore) {
occurences++;
}
}
} else if (definition instanceof CompoundDefinition) {
CompoundDefinition compound = (CompoundDefinition) definition;
Choice subChoice = compound.getDefinitions();
// recursive method call
occurences += countProblematicOccurrences(subChoice, feature, occurences > 0);
}
}
}
return occurences;
}
private List<Terminal> collectAllTerminals(Rule rule) {
return collectAllTerminals(rule.getDefinition());
}
private List<Terminal> collectAllTerminals(Choice choice) {
List<Terminal> result = new ArrayList<Terminal>();
List<Sequence> choices = choice.getOptions();
for (Sequence sequence : choices) {
List<Definition> definitions = sequence.getParts();
for (Definition definition : definitions) {
if (definition instanceof Terminal) {
Terminal terminal = (Terminal) definition;
result.add(terminal);
} else if (definition instanceof CompoundDefinition) {
CompoundDefinition compound = (CompoundDefinition) definition;
Choice subChoice = compound.getDefinitions();
result.addAll(collectAllTerminals(subChoice));
}
}
}
return result;
}
}
| true | true | private void checkForOptionalKeywords(ITextResource resource) {
for(Iterator<EObject> i = resource.getAllContents(); i.hasNext(); ) {
EObject next = i.next();
if (next instanceof CompoundDefinition) {
CompoundDefinition compoundDefinition = (CompoundDefinition) next;
if (compoundDefinition.getCardinality() instanceof QUESTIONMARK) {
for (Sequence sequence : compoundDefinition.getDefinitions().getOptions()) {
boolean containsKeyword = false;
boolean restOptional = true;
for (Definition definition : sequence.getParts()) {
if (definition instanceof CsString) {
containsKeyword = true;
}
else if (!(definition.getCardinality() instanceof QUESTIONMARK ||
definition.getCardinality() instanceof STAR)) {
restOptional = false;
}
}
if(containsKeyword && restOptional) {
for (Definition definition : sequence.getParts()) {
if (definition instanceof CsString) {
CsString csString = (CsString) definition;
resource.addWarning(
OPTIONAL_KEYWORD_WARNING + csString.getValue(),
definition);
}
}
}
}
}
}
}
}
| private void checkForOptionalKeywords(ITextResource resource) {
for(Iterator<EObject> i = resource.getAllContents(); i.hasNext(); ) {
EObject next = i.next();
if (next instanceof CompoundDefinition) {
CompoundDefinition compoundDefinition = (CompoundDefinition) next;
if (compoundDefinition.getCardinality() instanceof QUESTIONMARK ||
compoundDefinition.getCardinality() instanceof STAR) {
for (Sequence sequence : compoundDefinition.getDefinitions().getOptions()) {
boolean containsKeyword = false;
boolean restOptional = true;
for (Definition definition : sequence.getParts()) {
if (definition instanceof CsString) {
containsKeyword = true;
}
else if (!(definition.getCardinality() instanceof QUESTIONMARK ||
definition.getCardinality() instanceof STAR)) {
restOptional = false;
}
}
if(containsKeyword && restOptional) {
for (Definition definition : sequence.getParts()) {
if (definition instanceof CsString) {
CsString csString = (CsString) definition;
resource.addWarning(
OPTIONAL_KEYWORD_WARNING + csString.getValue(),
definition);
}
}
}
}
}
}
}
}
|
diff --git a/src/org/intellij/erlang/inspection/ErlangHeadMismatchInspection.java b/src/org/intellij/erlang/inspection/ErlangHeadMismatchInspection.java
index a89f6f24..fab40919 100644
--- a/src/org/intellij/erlang/inspection/ErlangHeadMismatchInspection.java
+++ b/src/org/intellij/erlang/inspection/ErlangHeadMismatchInspection.java
@@ -1,74 +1,75 @@
/*
* Copyright 2012-2013 Sergey Ignatov
*
* 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.intellij.erlang.inspection;
import com.intellij.codeInspection.LocalQuickFixBase;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.intellij.erlang.psi.ErlangFile;
import org.intellij.erlang.psi.ErlangFunction;
import org.intellij.erlang.psi.ErlangFunctionClause;
import org.intellij.erlang.psi.ErlangQAtom;
import org.intellij.erlang.psi.impl.ErlangElementFactory;
import org.intellij.erlang.psi.impl.ErlangPsiImplUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @author ignatov
*/
public class ErlangHeadMismatchInspection extends ErlangInspectionBase implements DumbAware {
@Override
protected void checkFile(PsiFile file, ProblemsHolder problemsHolder) {
if (!(file instanceof ErlangFile)) return;
for (ErlangFunction function : ((ErlangFile) file).getFunctions()) {
final String functionName = function.getName();
List<ErlangFunctionClause> clauses = function.getFunctionClauseList();
if (clauses.size() > 1) {
for (ErlangFunctionClause clause : clauses) {
ErlangQAtom clauseHead = clause.getQAtom();
+ if (clauseHead.getMacros() != null) return;
String clauseSignature = ErlangPsiImplUtil.createFunctionClausePresentation(clause);
String functionSignature = ErlangPsiImplUtil.createFunctionPresentation(function);
if (!functionSignature.equals(clauseSignature)) {
problemsHolder.registerProblem(clauseHead, "Head mismatch: should be '" + functionSignature + "'",
new LocalQuickFixBase("Rename clause head") {
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement oldHead = descriptor.getPsiElement();
if (oldHead instanceof ErlangQAtom) {
PsiElement newHead = ErlangElementFactory.createQAtomFromText(project, functionName);
PsiElement atom = ((ErlangQAtom) oldHead).getAtom();
if (atom != null) {
atom.replace(newHead);
}
}
}
});
}
}
}
}
}
}
| true | true | protected void checkFile(PsiFile file, ProblemsHolder problemsHolder) {
if (!(file instanceof ErlangFile)) return;
for (ErlangFunction function : ((ErlangFile) file).getFunctions()) {
final String functionName = function.getName();
List<ErlangFunctionClause> clauses = function.getFunctionClauseList();
if (clauses.size() > 1) {
for (ErlangFunctionClause clause : clauses) {
ErlangQAtom clauseHead = clause.getQAtom();
String clauseSignature = ErlangPsiImplUtil.createFunctionClausePresentation(clause);
String functionSignature = ErlangPsiImplUtil.createFunctionPresentation(function);
if (!functionSignature.equals(clauseSignature)) {
problemsHolder.registerProblem(clauseHead, "Head mismatch: should be '" + functionSignature + "'",
new LocalQuickFixBase("Rename clause head") {
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement oldHead = descriptor.getPsiElement();
if (oldHead instanceof ErlangQAtom) {
PsiElement newHead = ErlangElementFactory.createQAtomFromText(project, functionName);
PsiElement atom = ((ErlangQAtom) oldHead).getAtom();
if (atom != null) {
atom.replace(newHead);
}
}
}
});
}
}
}
}
}
| protected void checkFile(PsiFile file, ProblemsHolder problemsHolder) {
if (!(file instanceof ErlangFile)) return;
for (ErlangFunction function : ((ErlangFile) file).getFunctions()) {
final String functionName = function.getName();
List<ErlangFunctionClause> clauses = function.getFunctionClauseList();
if (clauses.size() > 1) {
for (ErlangFunctionClause clause : clauses) {
ErlangQAtom clauseHead = clause.getQAtom();
if (clauseHead.getMacros() != null) return;
String clauseSignature = ErlangPsiImplUtil.createFunctionClausePresentation(clause);
String functionSignature = ErlangPsiImplUtil.createFunctionPresentation(function);
if (!functionSignature.equals(clauseSignature)) {
problemsHolder.registerProblem(clauseHead, "Head mismatch: should be '" + functionSignature + "'",
new LocalQuickFixBase("Rename clause head") {
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement oldHead = descriptor.getPsiElement();
if (oldHead instanceof ErlangQAtom) {
PsiElement newHead = ErlangElementFactory.createQAtomFromText(project, functionName);
PsiElement atom = ((ErlangQAtom) oldHead).getAtom();
if (atom != null) {
atom.replace(newHead);
}
}
}
});
}
}
}
}
}
|
diff --git a/src/main/java/org/basex/http/restxq/RestXqResponse.java b/src/main/java/org/basex/http/restxq/RestXqResponse.java
index 5de056c78..e8d9965da 100644
--- a/src/main/java/org/basex/http/restxq/RestXqResponse.java
+++ b/src/main/java/org/basex/http/restxq/RestXqResponse.java
@@ -1,162 +1,164 @@
package org.basex.http.restxq;
import static org.basex.http.restxq.RestXqText.*;
import static org.basex.util.Token.*;
import java.io.*;
import java.util.Map.*;
import org.basex.http.*;
import org.basex.io.*;
import org.basex.io.serial.*;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.path.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.type.*;
import org.basex.query.value.type.SeqType.Occ;
/**
* This class creates a new HTTP response.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
final class RestXqResponse {
/** Serializer node test. */
private static final ExtTest OUTPUT_SERIAL = new ExtTest(NodeType.ELM,
FuncParams.Q_SPARAM);
/** HTTP Response test. */
private static final ExtTest HTTP_RESPONSE = new ExtTest(NodeType.ELM,
new QNm(RESPONSE, QueryText.HTTPURI));
/** REST Response test. */
private static final ExtTest REST_RESPONSE = new ExtTest(NodeType.ELM,
new QNm(RESPONSE, QueryText.RESTXQURI));
/** HTTP Response test. */
private static final ExtTest HTTP_HEADER = new ExtTest(NodeType.ELM,
new QNm(HEADER, QueryText.HTTPURI));
/** Function to be evaluated. */
private final RestXqFunction function;
/** Query context. */
private final QueryContext qc;
/** HTTP context. */
private final HTTPContext http;
/**
* Constructor.
* @param rxf function to be evaluated
* @param ctx query context
* @param hc HTTP context
*/
RestXqResponse(final RestXqFunction rxf, final QueryContext ctx, final HTTPContext hc) {
function = rxf;
qc = ctx;
http = hc;
qc.http = hc;
}
/**
* Evaluates the specified function and creates a response.
* @throws QueryException query exception
* @throws IOException I/O exception
*/
void create() throws QueryException, IOException {
// wrap function with a function call
final UserFunc uf = function.function;
final BaseFuncCall bfc = new BaseFuncCall(null, uf.name, uf.args);
bfc.init(uf);
// bind variables
function.bind(http);
// temporarily set database values (size check added for better performance)
if(!qc.dbOptions.isEmpty()) {
for(final Entry<String, String> e : qc.dbOptions.entrySet()) {
qc.context.prop.set(e.getKey(), e.getValue());
}
}
// compile and evaluate function
try {
+ qc.context.register(qc);
Value result = qc.value(bfc.compile(qc));
final Value update = qc.update();
if(update != null) result = update;
final int rs = (int) result.size();
final Item item = rs > 0 ? result.itemAt(0) : null;
final SeqType st = SeqType.get(REST_RESPONSE.type, Occ.ONE, REST_RESPONSE);
final ANode response = item != null && st.instance(item) ? (ANode) item : null;
// HEAD method may only return a single response element
if(function.methods.size() == 1 && function.methods.contains(HTTPMethod.HEAD)) {
if(rs != 1 || response == null) function.error(HEAD_METHOD);
}
// process rest:response element and set serializer
SerializerProp sp = response != null ? process(response) : null;
if(sp == null) sp = function.output;
// initialize response and serialize result
http.initResponse(sp);
final Serializer ser = Serializer.get(http.res.getOutputStream(), sp);
for(int v = response != null ? 1 : 0; v < rs; v++) {
ser.serialize(result.itemAt(v));
}
ser.close();
} finally {
qc.close();
+ qc.context.unregister(qc);
}
}
/**
* Processes the response element and creates the serialization parameters.
* @param response response element
* @return serialization properties
* @throws QueryException query exception
* @throws IOException I/O exception
*/
private SerializerProp process(final ANode response)
throws QueryException, IOException {
SerializerProp sp = null;
String cType = null;
for(final ANode n : response.children()) {
// process http:response element
if(HTTP_RESPONSE.eq(n)) {
final byte[] sta = n.attribute(new QNm(STATUS));
if(sta != null) {
final byte[] msg = n.attribute(new QNm(REASON));
http.status(toInt(sta), msg != null ? string(msg) : "");
}
for(final ANode c : n.children()) {
// process http:header element
if(HTTP_HEADER.eq(c)) {
final byte[] nam = c.attribute(new QNm(NAME));
final byte[] val = c.attribute(new QNm(VALUE));
if(nam != null && val != null) {
final String key = string(nam);
if(key.equals(MimeTypes.CONTENT_TYPE)) {
cType = string(val);
} else {
http.res.setHeader(key, string(val));
}
}
}
}
}
// process output:serialization-parameters
if(OUTPUT_SERIAL.eq(n)) sp = FuncParams.serializerProp(n);
}
// set content type
if(cType != null) {
if(sp == null) sp = new SerializerProp(function.output.toString());
sp.set(SerializerProp.S_MEDIA_TYPE, cType);
}
return sp;
}
}
| false | true | void create() throws QueryException, IOException {
// wrap function with a function call
final UserFunc uf = function.function;
final BaseFuncCall bfc = new BaseFuncCall(null, uf.name, uf.args);
bfc.init(uf);
// bind variables
function.bind(http);
// temporarily set database values (size check added for better performance)
if(!qc.dbOptions.isEmpty()) {
for(final Entry<String, String> e : qc.dbOptions.entrySet()) {
qc.context.prop.set(e.getKey(), e.getValue());
}
}
// compile and evaluate function
try {
Value result = qc.value(bfc.compile(qc));
final Value update = qc.update();
if(update != null) result = update;
final int rs = (int) result.size();
final Item item = rs > 0 ? result.itemAt(0) : null;
final SeqType st = SeqType.get(REST_RESPONSE.type, Occ.ONE, REST_RESPONSE);
final ANode response = item != null && st.instance(item) ? (ANode) item : null;
// HEAD method may only return a single response element
if(function.methods.size() == 1 && function.methods.contains(HTTPMethod.HEAD)) {
if(rs != 1 || response == null) function.error(HEAD_METHOD);
}
// process rest:response element and set serializer
SerializerProp sp = response != null ? process(response) : null;
if(sp == null) sp = function.output;
// initialize response and serialize result
http.initResponse(sp);
final Serializer ser = Serializer.get(http.res.getOutputStream(), sp);
for(int v = response != null ? 1 : 0; v < rs; v++) {
ser.serialize(result.itemAt(v));
}
ser.close();
} finally {
qc.close();
}
}
| void create() throws QueryException, IOException {
// wrap function with a function call
final UserFunc uf = function.function;
final BaseFuncCall bfc = new BaseFuncCall(null, uf.name, uf.args);
bfc.init(uf);
// bind variables
function.bind(http);
// temporarily set database values (size check added for better performance)
if(!qc.dbOptions.isEmpty()) {
for(final Entry<String, String> e : qc.dbOptions.entrySet()) {
qc.context.prop.set(e.getKey(), e.getValue());
}
}
// compile and evaluate function
try {
qc.context.register(qc);
Value result = qc.value(bfc.compile(qc));
final Value update = qc.update();
if(update != null) result = update;
final int rs = (int) result.size();
final Item item = rs > 0 ? result.itemAt(0) : null;
final SeqType st = SeqType.get(REST_RESPONSE.type, Occ.ONE, REST_RESPONSE);
final ANode response = item != null && st.instance(item) ? (ANode) item : null;
// HEAD method may only return a single response element
if(function.methods.size() == 1 && function.methods.contains(HTTPMethod.HEAD)) {
if(rs != 1 || response == null) function.error(HEAD_METHOD);
}
// process rest:response element and set serializer
SerializerProp sp = response != null ? process(response) : null;
if(sp == null) sp = function.output;
// initialize response and serialize result
http.initResponse(sp);
final Serializer ser = Serializer.get(http.res.getOutputStream(), sp);
for(int v = response != null ? 1 : 0; v < rs; v++) {
ser.serialize(result.itemAt(v));
}
ser.close();
} finally {
qc.close();
qc.context.unregister(qc);
}
}
|
diff --git a/src/net/esper/tacos/ircbot/CommandProcessor.java b/src/net/esper/tacos/ircbot/CommandProcessor.java
index 8f3a38d..765080e 100644
--- a/src/net/esper/tacos/ircbot/CommandProcessor.java
+++ b/src/net/esper/tacos/ircbot/CommandProcessor.java
@@ -1,117 +1,109 @@
package net.esper.tacos.ircbot;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.events.PrivateMessageEvent;
public class CommandProcessor {
private static ProcessThread PROC_THREAD;
public static List<MessageEvent> events = new CopyOnWriteArrayList<MessageEvent>();
private static Object PROC = new Object();
private static boolean ASLEEP = false;
public static void init() {
PROC_THREAD = new ProcessThread();
PROC_THREAD.start();
}
public static void process(MessageEvent<?> event) {
events.add(event);
if (ASLEEP) {
synchronized (PROC) {
PROC.notify();
}
}
}
public static class ProcessThread extends Thread {
@SuppressWarnings("unchecked")
public void run() {
while (true) {
- if (events.size() == 0) {
+ if (events.size() < 1) {
ASLEEP = true;
try {
synchronized (PROC) {
PROC.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ASLEEP = false;
- // I have no idea why I'm adding this check
- // So I'm adding this check, even though I have no idea why we need this
- // Except the bot is constantly crashing for some reason
- if (events.size() < 1) {
- return;
- }
- // Somebody else good at logic pls help
- // pls
MessageEvent<?> ev = events.remove(events.size() - 1);
if (ev.getMessage().startsWith(TacoBot.PREFIX) && !ev.getMessage().startsWith(TacoBot.PREFIX + "/")) {
// Ok attempt to use reflection!
ICommand cmd = null;
try {
Class<ICommand> clazz = (Class<ICommand>) Class.forName("net.esper.tacos.ircbot.commands." + ev.getMessage().split(" ")[0].substring(1));
cmd = clazz.newInstance();
} catch (Exception e) {} finally {
if (cmd == null) continue;
String message = ev.getMessage();
String[] args = ev.getMessage().split(" ");
User user = ev.getUser();
// Let's check permissions!
if (cmd.getRank() != null && cmd.getRank() != Rank.PEASANT && !Rank.canUse(Rank.getRank(user), cmd.getRank())) {
if (cmd.getNoAccessMessage() != null) {
TacoBot.sendMessage(user, cmd.getNoAccessMessage());
}
continue;
}
try {
cmd.exec(message, args, user);
} catch (Exception e) {
e.printStackTrace();
TacoBot.sendMessage(user, "An exception had occured and was printed to console.");
}
}
} else if (ev.getMessage().startsWith("s/") && ev.getUser().getChannelsOpIn().contains(TacoBot.CHAN_OBJ)) {
String[] torepl = ev.getMessage().split("/"); // s/g/r [0]/[1]/[2]
if (torepl.length < 3) {
return;
}
// search
String vic = null;
for (String msg : TacoBot.getMsgs()) {
if (msg.contains(torepl[1])) {
vic = msg;
break;
}
}
if (vic == null) {
return;
}
String repl = vic.replace(torepl[1], torepl[2]);
TacoBot.sendMessage(repl);
}
}
}
}
public static void process(PrivateMessageEvent<?> event) {
events.add(new MessageEvent<PircBotX>(TacoBot.bot, TacoBot.CHAN_OBJ, event.getUser(), event.getMessage()));
if (ASLEEP) {
synchronized (PROC) {
PROC.notify();
}
}
}
}
| false | true | public void run() {
while (true) {
if (events.size() == 0) {
ASLEEP = true;
try {
synchronized (PROC) {
PROC.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ASLEEP = false;
// I have no idea why I'm adding this check
// So I'm adding this check, even though I have no idea why we need this
// Except the bot is constantly crashing for some reason
if (events.size() < 1) {
return;
}
// Somebody else good at logic pls help
// pls
MessageEvent<?> ev = events.remove(events.size() - 1);
if (ev.getMessage().startsWith(TacoBot.PREFIX) && !ev.getMessage().startsWith(TacoBot.PREFIX + "/")) {
// Ok attempt to use reflection!
ICommand cmd = null;
try {
Class<ICommand> clazz = (Class<ICommand>) Class.forName("net.esper.tacos.ircbot.commands." + ev.getMessage().split(" ")[0].substring(1));
cmd = clazz.newInstance();
} catch (Exception e) {} finally {
if (cmd == null) continue;
String message = ev.getMessage();
String[] args = ev.getMessage().split(" ");
User user = ev.getUser();
// Let's check permissions!
if (cmd.getRank() != null && cmd.getRank() != Rank.PEASANT && !Rank.canUse(Rank.getRank(user), cmd.getRank())) {
if (cmd.getNoAccessMessage() != null) {
TacoBot.sendMessage(user, cmd.getNoAccessMessage());
}
continue;
}
try {
cmd.exec(message, args, user);
} catch (Exception e) {
e.printStackTrace();
TacoBot.sendMessage(user, "An exception had occured and was printed to console.");
}
}
} else if (ev.getMessage().startsWith("s/") && ev.getUser().getChannelsOpIn().contains(TacoBot.CHAN_OBJ)) {
String[] torepl = ev.getMessage().split("/"); // s/g/r [0]/[1]/[2]
if (torepl.length < 3) {
return;
}
// search
String vic = null;
for (String msg : TacoBot.getMsgs()) {
if (msg.contains(torepl[1])) {
vic = msg;
break;
}
}
if (vic == null) {
return;
}
String repl = vic.replace(torepl[1], torepl[2]);
TacoBot.sendMessage(repl);
}
}
}
| public void run() {
while (true) {
if (events.size() < 1) {
ASLEEP = true;
try {
synchronized (PROC) {
PROC.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ASLEEP = false;
MessageEvent<?> ev = events.remove(events.size() - 1);
if (ev.getMessage().startsWith(TacoBot.PREFIX) && !ev.getMessage().startsWith(TacoBot.PREFIX + "/")) {
// Ok attempt to use reflection!
ICommand cmd = null;
try {
Class<ICommand> clazz = (Class<ICommand>) Class.forName("net.esper.tacos.ircbot.commands." + ev.getMessage().split(" ")[0].substring(1));
cmd = clazz.newInstance();
} catch (Exception e) {} finally {
if (cmd == null) continue;
String message = ev.getMessage();
String[] args = ev.getMessage().split(" ");
User user = ev.getUser();
// Let's check permissions!
if (cmd.getRank() != null && cmd.getRank() != Rank.PEASANT && !Rank.canUse(Rank.getRank(user), cmd.getRank())) {
if (cmd.getNoAccessMessage() != null) {
TacoBot.sendMessage(user, cmd.getNoAccessMessage());
}
continue;
}
try {
cmd.exec(message, args, user);
} catch (Exception e) {
e.printStackTrace();
TacoBot.sendMessage(user, "An exception had occured and was printed to console.");
}
}
} else if (ev.getMessage().startsWith("s/") && ev.getUser().getChannelsOpIn().contains(TacoBot.CHAN_OBJ)) {
String[] torepl = ev.getMessage().split("/"); // s/g/r [0]/[1]/[2]
if (torepl.length < 3) {
return;
}
// search
String vic = null;
for (String msg : TacoBot.getMsgs()) {
if (msg.contains(torepl[1])) {
vic = msg;
break;
}
}
if (vic == null) {
return;
}
String repl = vic.replace(torepl[1], torepl[2]);
TacoBot.sendMessage(repl);
}
}
}
|
diff --git a/src/test/java/ScreeFlowTest.java b/src/test/java/ScreeFlowTest.java
index 8f23d34..70be38c 100644
--- a/src/test/java/ScreeFlowTest.java
+++ b/src/test/java/ScreeFlowTest.java
@@ -1,76 +1,76 @@
import com.seleniumscreenflow.Grid;
import com.seleniumscreenflow.ScreenshotFlow;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
/**
* Author: Sun4Android
* Date: 09.12.12
* Time: 15:39
*/
public class ScreeFlowTest {
private static final String CHROME_DRIVER_PATH = ".\\bin\\chromedriver.exe";
private static final String OUTPUT_PATH = ".\\target\\out.png";
private WebDriver driver;
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_PATH);
driver = new ChromeDriver();
}
@AfterTest
public void afterTest() {
if(driver != null) {
driver.quit();
}
}
@Test
public void questionTest() {
String question = "2 + 2";
ScreenshotFlow flow = new ScreenshotFlow(driver);
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get("http://www.wolframalpha.com/");
// Using By
flow.takeScreenshot(By.id("calculate"), "Looking at form");
// Using WebElement
WebElement input = wait.until(visibilityOfElementLocated(By.id("i")));
input.sendKeys(question);
flow.takeScreenshot(input, "Looking at question");
flow.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("imath"))), "Looking at suggestions");
WebElement equals = driver.findElement(By.id("equal"));
equals.click();
flow.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 1 section of answers")
- .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 2 section of answers")
- .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 3 section of answers")
- .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 4 section of answers")
- .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 5 section of answers")
- .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 6 section of answers");
+ .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0200"))), "Looking at 2 section of answers")
+ .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0300"))), "Looking at 3 section of answers")
+ .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0400"))), "Looking at 4 section of answers")
+ .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0500"))), "Looking at 5 section of answers")
+ .takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0600"))), "Looking at 6 section of answers");
try {
flow.toFile(new File(OUTPUT_PATH), new Grid(), 1920, 1080);
} catch (IOException e) {
//ignore
} finally {
flow.clear();
}
}
}
| true | true | public void questionTest() {
String question = "2 + 2";
ScreenshotFlow flow = new ScreenshotFlow(driver);
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get("http://www.wolframalpha.com/");
// Using By
flow.takeScreenshot(By.id("calculate"), "Looking at form");
// Using WebElement
WebElement input = wait.until(visibilityOfElementLocated(By.id("i")));
input.sendKeys(question);
flow.takeScreenshot(input, "Looking at question");
flow.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("imath"))), "Looking at suggestions");
WebElement equals = driver.findElement(By.id("equal"));
equals.click();
flow.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 1 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 2 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 3 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 4 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 5 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 6 section of answers");
try {
flow.toFile(new File(OUTPUT_PATH), new Grid(), 1920, 1080);
} catch (IOException e) {
//ignore
} finally {
flow.clear();
}
}
| public void questionTest() {
String question = "2 + 2";
ScreenshotFlow flow = new ScreenshotFlow(driver);
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get("http://www.wolframalpha.com/");
// Using By
flow.takeScreenshot(By.id("calculate"), "Looking at form");
// Using WebElement
WebElement input = wait.until(visibilityOfElementLocated(By.id("i")));
input.sendKeys(question);
flow.takeScreenshot(input, "Looking at question");
flow.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("imath"))), "Looking at suggestions");
WebElement equals = driver.findElement(By.id("equal"));
equals.click();
flow.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0100"))), "Looking at 1 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0200"))), "Looking at 2 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0300"))), "Looking at 3 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0400"))), "Looking at 4 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0500"))), "Looking at 5 section of answers")
.takeScreenshot(wait.until(visibilityOfElementLocated(By.id("pod_0600"))), "Looking at 6 section of answers");
try {
flow.toFile(new File(OUTPUT_PATH), new Grid(), 1920, 1080);
} catch (IOException e) {
//ignore
} finally {
flow.clear();
}
}
|
diff --git a/src/main/java/cc/kune/core/server/manager/impl/GroupManagerDefault.java b/src/main/java/cc/kune/core/server/manager/impl/GroupManagerDefault.java
index 7d085e78c..2008f42f1 100644
--- a/src/main/java/cc/kune/core/server/manager/impl/GroupManagerDefault.java
+++ b/src/main/java/cc/kune/core/server/manager/impl/GroupManagerDefault.java
@@ -1,397 +1,397 @@
/*
*
* Copyright (C) 2007-2011 The kune development team (see CREDITS for details)
* This file is part of kune.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.kune.core.server.manager.impl;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceException;
import org.apache.lucene.queryParser.QueryParser;
import org.hibernate.exception.ConstraintViolationException;
import cc.kune.common.shared.i18n.I18nTranslationService;
import cc.kune.core.client.errors.AccessViolationException;
import cc.kune.core.client.errors.DefaultException;
import cc.kune.core.client.errors.EmailAddressInUseException;
import cc.kune.core.client.errors.GroupLongNameInUseException;
import cc.kune.core.client.errors.GroupShortNameInUseException;
import cc.kune.core.client.errors.ToolIsDefaultException;
import cc.kune.core.client.errors.UserMustBeLoggedException;
import cc.kune.core.server.manager.FileManager;
import cc.kune.core.server.manager.GroupManager;
import cc.kune.core.server.manager.LicenseManager;
import cc.kune.core.server.manager.SearchResult;
import cc.kune.core.server.manager.file.FileUtils;
import cc.kune.core.server.persist.DataSourceKune;
import cc.kune.core.server.persist.KuneTransactional;
import cc.kune.core.server.properties.KuneBasicProperties;
import cc.kune.core.server.properties.KuneProperties;
import cc.kune.core.server.tool.ServerTool;
import cc.kune.core.server.tool.ServerToolRegistry;
import cc.kune.core.shared.SearcherConstants;
import cc.kune.core.shared.domain.AdmissionType;
import cc.kune.core.shared.domain.GroupListMode;
import cc.kune.core.shared.domain.SocialNetworkVisibility;
import cc.kune.core.shared.dto.GroupDTO;
import cc.kune.core.shared.dto.GroupType;
import cc.kune.domain.AccessLists;
import cc.kune.domain.Content;
import cc.kune.domain.Group;
import cc.kune.domain.License;
import cc.kune.domain.SocialNetwork;
import cc.kune.domain.ToolConfiguration;
import cc.kune.domain.User;
import cc.kune.domain.finders.GroupFinder;
import cc.kune.domain.finders.LicenseFinder;
import cc.kune.domain.finders.UserFinder;
import cc.kune.trash.server.TrashServerTool;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
@Singleton
public class GroupManagerDefault extends DefaultManager<Group, Long> implements GroupManager {
private final FileManager fileManager;
private final GroupFinder finder;
private final I18nTranslationService i18n;
private final KuneProperties kuneProperties;
private final LicenseFinder licenseFinder;
private final LicenseManager licenseManager;
private final KuneBasicProperties properties;
private final ServerToolRegistry serverToolRegistry;
private final SocialNetworkCache snCache;
private final Provider<TrashServerTool> trashTool;
private final UserFinder userFinder;
@Inject
public GroupManagerDefault(@DataSourceKune final Provider<EntityManager> provider,
final GroupFinder finder, final UserFinder userFinder, final KuneProperties kuneProperties,
final KuneBasicProperties properties, final LicenseManager licenseManager,
final LicenseFinder licenseFinder, final FileManager fileManager,
final ServerToolRegistry serverToolRegistry, final Provider<TrashServerTool> trashTool,
final I18nTranslationService i18n, final SocialNetworkCache snCache) {
super(provider, Group.class);
this.finder = finder;
this.userFinder = userFinder;
this.kuneProperties = kuneProperties;
this.properties = properties;
this.licenseManager = licenseManager;
this.licenseFinder = licenseFinder;
this.fileManager = fileManager;
this.serverToolRegistry = serverToolRegistry;
this.trashTool = trashTool;
this.i18n = i18n;
this.snCache = snCache;
}
@Override
public void changeDefLicense(final User user, final Group group, final String licName) {
final License license = licenseFinder.findByShortName(licName);
if (license == null) {
throw new ServerManagerException("Unknown license");
}
group.setDefaultLicense(license);
}
@Override
public void changeWsTheme(final User user, final Group group, final String theme)
throws AccessViolationException {
// TODO: check theme
group.setWorkspaceTheme(theme);
}
@Override
public void checkIfLongNameAreInUse(final String longName) {
if (finder.countByLongName(longName) != 0) {
throw new GroupLongNameInUseException();
}
}
@Override
public void checkIfShortNameAreInUse(final String shortName) {
if (finder.countByShortName(shortName) != 0) {
throw new GroupShortNameInUseException();
}
}
@Override
public void clearGroupBackImage(final Group group) {
final String file = group.getBackgroundImage();
if (file != null) {
fileManager.rm(FileUtils.groupToDir(group.getShortName()), file);
}
group.setBackgroundImage(null);
group.setBackgroundMime(null);
}
@Override
@KuneTransactional
public int count() {
return super.size();
}
@Override
public Group createGroup(final Group group, final User user, final String publicDescrip)
throws GroupShortNameInUseException, GroupLongNameInUseException, UserMustBeLoggedException {
checkIfShortNameAreInUse(group.getShortName());
checkIfLongNameAreInUse(group.getLongName());
final String defaultSiteWorkspaceTheme = kuneProperties.get(KuneProperties.WS_THEMES_DEF);
if (User.isKnownUser(user)) {
setAdmissionType(group);
final String licName = group.getDefaultLicense().getShortName();
final License license = licenseFinder.findByShortName(licName);
group.setDefaultLicense(license);
group.setWorkspaceTheme(defaultSiteWorkspaceTheme);
final boolean isClosed = group.getGroupType().equals(GroupType.CLOSED);
initSocialNetwork(group, user.getUserGroup(), getDefGroupMode(isClosed),
getDefSNVisibility(isClosed));
final String title = i18n.t("About [%s]", group.getLongName());
initGroup(user, group, serverToolRegistry.getToolsRegisEnabledForGroups(), title, publicDescrip);
snCache.expire(user.getUserGroup());
return group;
} else {
throw new UserMustBeLoggedException();
}
}
@Override
public Group createUserGroup(final User user) throws GroupShortNameInUseException,
EmailAddressInUseException {
return createUserGroup(user, true);
}
@Override
public Group createUserGroup(final User user, final boolean wantPersonalHomepage)
throws GroupShortNameInUseException, EmailAddressInUseException {
final String defaultSiteWorkspaceTheme = kuneProperties.get(KuneProperties.WS_THEMES_DEF);
final License licenseDef = licenseManager.getDefLicense();
final Group userGroup = new Group(user.getShortName(), user.getName(), licenseDef,
GroupType.PERSONAL);
User userSameEmail = null;
try {
userSameEmail = userFinder.findByEmail(user.getEmail());
} catch (final NoResultException e) {
// Ok, no more with this email
}
if (userSameEmail != null) {
throw new EmailAddressInUseException();
}
userGroup.setAdmissionType(AdmissionType.Closed);
userGroup.setWorkspaceTheme(defaultSiteWorkspaceTheme);
userGroup.setDefaultContent(null);
user.setUserGroup(userGroup);
initSocialNetwork(userGroup, userGroup, GroupListMode.EVERYONE, SocialNetworkVisibility.anyone);
final String title = i18n.t("[%s] Bio", user.getName());
- final String body = i18n.t("This user has not written its biography yet. Please, edit this document and write here whatever public description of yourself you want others to see.");
+ final String body = i18n.t("This is [%s]'s bio, currently empty", user.getName());
try {
initGroup(user, userGroup,
wantPersonalHomepage ? serverToolRegistry.getToolsRegisEnabledForUsers()
: ServerToolRegistry.emptyToolList, title, body);
super.persist(user, User.class);
} catch (final PersistenceException e) {
if (e.getCause() instanceof ConstraintViolationException) {
throw new GroupShortNameInUseException();
}
throw e;
}
return userGroup;
}
@Override
public Set<Group> findAdminInGroups(final Long groupId) {
return finder.findAdminInGroups(groupId);
}
@Override
public Group findByShortName(final String shortName) {
return finder.findByShortName(shortName);
}
@Override
public Set<Group> findCollabInGroups(final Long groupId) {
return finder.findCollabInGroups(groupId);
}
@Override
public List<String> findEnabledTools(final Long id) {
return finder.findEnabledTools(id);
}
private GroupListMode getDefGroupMode(final boolean isClosed) {
return isClosed ? GroupListMode.NORMAL : GroupListMode.EVERYONE;
}
private SocialNetworkVisibility getDefSNVisibility(final boolean isClosed) {
return isClosed ? SocialNetworkVisibility.onlymembers : SocialNetworkVisibility.anyone;
}
@Override
public Group getGroupOfUserWithId(final Long userId) {
return userId != null ? find(User.class, userId).getUserGroup() : null;
}
@Override
public Group getSiteDefaultGroup() {
final String shortName = properties.getDefaultSiteShortName();
return findByShortName(shortName);
}
private void initGroup(final User user, final Group group, final List<String> toolsToEnable,
final Object... vars) throws GroupShortNameInUseException {
try {
persist(group);
} catch (final IllegalStateException e) {
e.printStackTrace();
} catch (final PersistenceException e) {
if (e.getCause() instanceof ConstraintViolationException) {
throw new GroupShortNameInUseException();
}
throw e;
}
for (final ServerTool tool : serverToolRegistry.all()) {
if (toolsToEnable.contains(tool.getName())) {
tool.initGroup(user, group, vars);
}
}
// Init always the trash
initTrash(group);
}
private void initSocialNetwork(final Group group, final Group userGroup,
final GroupListMode publicVisibility, final SocialNetworkVisibility snVisibility) {
final SocialNetwork network = setSocialNetwork(group, publicVisibility, snVisibility);
if (!group.getGroupType().equals(GroupType.ORPHANED_PROJECT)) {
network.addAdmin(userGroup);
network.getAccessLists().getEditors().setMode(GroupListMode.NOBODY);
}
}
@Override
public void initTrash(final Group group) {
trashTool.get().initGroup(group);
}
@Override
public SearchResult<Group> search(final String search) {
return this.search(search, null, null);
}
@Override
public SearchResult<Group> search(final String search, final Integer firstResult,
final Integer maxResults) {
final String escapedQuery = QueryParser.escape(search) + SearcherConstants.WILDCARD;
return super.search(new String[] { escapedQuery, escapedQuery, escapedQuery }, new String[] {
"longName", "shortName", "publicDesc" }, firstResult, maxResults);
}
private void setAdmissionType(final Group group) {
final GroupType groupType = group.getGroupType();
if (groupType.equals(GroupType.COMMUNITY)) {
group.setAdmissionType(AdmissionType.Open);
} else {
if (groupType.equals(GroupType.CLOSED)) {
group.setAdmissionType(AdmissionType.Closed);
} else if (groupType.equals(GroupType.ORGANIZATION)) {
group.setAdmissionType(AdmissionType.Moderated);
} else if (groupType.equals(GroupType.PROJECT)) {
group.setAdmissionType(AdmissionType.Moderated);
} else if (groupType.equals(GroupType.ORPHANED_PROJECT)) {
group.setAdmissionType(AdmissionType.Open);
}
}
}
@Override
public void setDefaultContent(final String groupShortName, final Content content) {
final Group group = findByShortName(groupShortName);
group.setDefaultContent(content);
}
@Override
public void setGroupBackgroundImage(final Group group, final String backgroundFileName,
final String mime) {
clearGroupBackImage(group);
group.setBackgroundImage(backgroundFileName);
group.setBackgroundMime(mime);
}
private SocialNetwork setSocialNetwork(final Group group, final GroupListMode publicVisibility,
final SocialNetworkVisibility snVisibility) {
final SocialNetwork network = group.getSocialNetwork();
final AccessLists lists = network.getAccessLists();
lists.getViewers().setMode(publicVisibility);
network.setVisibility(snVisibility);
return network;
}
@Override
public void setToolEnabled(final User userLogged, final String groupShortName, final String tool,
final boolean enabled) throws ToolIsDefaultException {
final Group group = findByShortName(groupShortName);
if (group.getDefaultContent().getStateToken().getTool().equals(tool) && !enabled) {
throw new ToolIsDefaultException();
}
ToolConfiguration toolConfiguration = group.getToolConfiguration(tool);
if (toolConfiguration == null) {
toolConfiguration = serverToolRegistry.get(tool).initGroup(userLogged, group).getToolConfiguration(
tool);
}
toolConfiguration.setEnabled(enabled);
}
@Override
public Group update(final Long groupId, final GroupDTO groupDTO) {
final Group group = find(groupId);
final String shortName = groupDTO.getShortName();
final String longName = groupDTO.getLongName();
if (!longName.equals(group.getLongName())) {
checkIfLongNameAreInUse(longName);
group.setLongName(longName);
}
if (!shortName.equals(group.getShortName())) {
checkIfShortNameAreInUse(shortName);
final String oldDir = kuneProperties.get(KuneProperties.UPLOAD_LOCATION)
+ FileUtils.groupToDir(group.getShortName());
final String newDir = kuneProperties.get(KuneProperties.UPLOAD_LOCATION)
+ FileUtils.groupToDir(shortName);
if (fileManager.exists(oldDir)) {
if (fileManager.exists(newDir)) {
throw new DefaultException("Destination group directory exists");
}
fileManager.mv(oldDir, newDir);
}
group.setShortName(shortName);
}
group.setGroupType(groupDTO.getGroupType());
setAdmissionType(group);
final boolean isClosed = group.getGroupType().equals(GroupType.CLOSED);
setSocialNetwork(group, getDefGroupMode(isClosed), getDefSNVisibility(isClosed));
persist(group);
snCache.expire(group);
return group;
}
}
| true | true | public Group createUserGroup(final User user, final boolean wantPersonalHomepage)
throws GroupShortNameInUseException, EmailAddressInUseException {
final String defaultSiteWorkspaceTheme = kuneProperties.get(KuneProperties.WS_THEMES_DEF);
final License licenseDef = licenseManager.getDefLicense();
final Group userGroup = new Group(user.getShortName(), user.getName(), licenseDef,
GroupType.PERSONAL);
User userSameEmail = null;
try {
userSameEmail = userFinder.findByEmail(user.getEmail());
} catch (final NoResultException e) {
// Ok, no more with this email
}
if (userSameEmail != null) {
throw new EmailAddressInUseException();
}
userGroup.setAdmissionType(AdmissionType.Closed);
userGroup.setWorkspaceTheme(defaultSiteWorkspaceTheme);
userGroup.setDefaultContent(null);
user.setUserGroup(userGroup);
initSocialNetwork(userGroup, userGroup, GroupListMode.EVERYONE, SocialNetworkVisibility.anyone);
final String title = i18n.t("[%s] Bio", user.getName());
final String body = i18n.t("This user has not written its biography yet. Please, edit this document and write here whatever public description of yourself you want others to see.");
try {
initGroup(user, userGroup,
wantPersonalHomepage ? serverToolRegistry.getToolsRegisEnabledForUsers()
: ServerToolRegistry.emptyToolList, title, body);
super.persist(user, User.class);
} catch (final PersistenceException e) {
if (e.getCause() instanceof ConstraintViolationException) {
throw new GroupShortNameInUseException();
}
throw e;
}
return userGroup;
}
| public Group createUserGroup(final User user, final boolean wantPersonalHomepage)
throws GroupShortNameInUseException, EmailAddressInUseException {
final String defaultSiteWorkspaceTheme = kuneProperties.get(KuneProperties.WS_THEMES_DEF);
final License licenseDef = licenseManager.getDefLicense();
final Group userGroup = new Group(user.getShortName(), user.getName(), licenseDef,
GroupType.PERSONAL);
User userSameEmail = null;
try {
userSameEmail = userFinder.findByEmail(user.getEmail());
} catch (final NoResultException e) {
// Ok, no more with this email
}
if (userSameEmail != null) {
throw new EmailAddressInUseException();
}
userGroup.setAdmissionType(AdmissionType.Closed);
userGroup.setWorkspaceTheme(defaultSiteWorkspaceTheme);
userGroup.setDefaultContent(null);
user.setUserGroup(userGroup);
initSocialNetwork(userGroup, userGroup, GroupListMode.EVERYONE, SocialNetworkVisibility.anyone);
final String title = i18n.t("[%s] Bio", user.getName());
final String body = i18n.t("This is [%s]'s bio, currently empty", user.getName());
try {
initGroup(user, userGroup,
wantPersonalHomepage ? serverToolRegistry.getToolsRegisEnabledForUsers()
: ServerToolRegistry.emptyToolList, title, body);
super.persist(user, User.class);
} catch (final PersistenceException e) {
if (e.getCause() instanceof ConstraintViolationException) {
throw new GroupShortNameInUseException();
}
throw e;
}
return userGroup;
}
|
diff --git a/sip-servlets-jboss5/src/main/java/org/mobicents/servlet/sip/core/timers/SipApplicationSessionTaskFactory.java b/sip-servlets-jboss5/src/main/java/org/mobicents/servlet/sip/core/timers/SipApplicationSessionTaskFactory.java
index 4b35fba19..a9f934f44 100644
--- a/sip-servlets-jboss5/src/main/java/org/mobicents/servlet/sip/core/timers/SipApplicationSessionTaskFactory.java
+++ b/sip-servlets-jboss5/src/main/java/org/mobicents/servlet/sip/core/timers/SipApplicationSessionTaskFactory.java
@@ -1,76 +1,76 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* 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.mobicents.servlet.sip.core.timers;
import org.apache.log4j.Logger;
import org.jboss.web.tomcat.service.session.ClusteredSipManager;
import org.jboss.web.tomcat.service.session.distributedcache.spi.OutgoingDistributableSessionData;
import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.startup.SipContext;
import org.mobicents.timers.TimerTask;
import org.mobicents.timers.TimerTaskData;
import org.mobicents.timers.TimerTaskFactory;
/**
* Allow to recreate a sip application session timer task upon failover
*
* @author [email protected]
*
*/
public class SipApplicationSessionTaskFactory implements TimerTaskFactory {
private static final Logger logger = Logger.getLogger(SipApplicationSessionTaskFactory.class);
private ClusteredSipManager<? extends OutgoingDistributableSessionData> sipManager;
public SipApplicationSessionTaskFactory(ClusteredSipManager<? extends OutgoingDistributableSessionData> sipManager) {
this.sipManager = sipManager;
}
/* (non-Javadoc)
* @see org.mobicents.timers.TimerTaskFactory#newTimerTask(org.mobicents.timers.TimerTaskData)
*/
public TimerTask newTimerTask(TimerTaskData data) {
SipApplicationSessionTaskData sasData = (SipApplicationSessionTaskData)data;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sasData.getKey(), false);
- if(sipApplicationSession.getExpirationTimerTask() == null) {
- if(((SipContext)sipManager.getContainer()).getConcurrencyControlMode() != ConcurrencyControlMode.SipApplicationSession) {
- if(logger.isDebugEnabled()) {
- if(sipApplicationSession == null) {
- logger.debug("sip application session for key " + sasData.getKey() + " was not found neither locally or in the cache, sas expiration timer recreation will be problematic");
- } else {
- logger.debug("sip application session for key " + sasData.getKey() + " was found");
+ if(sipApplicationSession != null) {
+ if(sipApplicationSession.getExpirationTimerTask() == null) {
+ if(((SipContext)sipManager.getContainer()).getConcurrencyControlMode() != ConcurrencyControlMode.SipApplicationSession) {
+ if(logger.isDebugEnabled()) {
+ logger.debug("sip application session for key " + sasData.getKey() + " was found");
}
- }
- FaultTolerantSasTimerTask faultTolerantSasTimerTask = new FaultTolerantSasTimerTask(sipApplicationSession, sasData);
- if(sipApplicationSession != null) {
- sipApplicationSession.setExpirationTimerTask(faultTolerantSasTimerTask);
- }
- return faultTolerantSasTimerTask;
- }
+ FaultTolerantSasTimerTask faultTolerantSasTimerTask = new FaultTolerantSasTimerTask(sipApplicationSession, sasData);
+ if(sipApplicationSession != null) {
+ sipApplicationSession.setExpirationTimerTask(faultTolerantSasTimerTask);
+ }
+ return faultTolerantSasTimerTask;
+ }
+ }
+ } else {
+ logger.debug("sip application session for key " + sasData.getKey() + " was not found neither locally or in the cache, not recovering the sas timer task");
}
// returning null to avoid recovery since it was already recovered above
return null;
}
}
| false | true | public TimerTask newTimerTask(TimerTaskData data) {
SipApplicationSessionTaskData sasData = (SipApplicationSessionTaskData)data;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sasData.getKey(), false);
if(sipApplicationSession.getExpirationTimerTask() == null) {
if(((SipContext)sipManager.getContainer()).getConcurrencyControlMode() != ConcurrencyControlMode.SipApplicationSession) {
if(logger.isDebugEnabled()) {
if(sipApplicationSession == null) {
logger.debug("sip application session for key " + sasData.getKey() + " was not found neither locally or in the cache, sas expiration timer recreation will be problematic");
} else {
logger.debug("sip application session for key " + sasData.getKey() + " was found");
}
}
FaultTolerantSasTimerTask faultTolerantSasTimerTask = new FaultTolerantSasTimerTask(sipApplicationSession, sasData);
if(sipApplicationSession != null) {
sipApplicationSession.setExpirationTimerTask(faultTolerantSasTimerTask);
}
return faultTolerantSasTimerTask;
}
}
// returning null to avoid recovery since it was already recovered above
return null;
}
| public TimerTask newTimerTask(TimerTaskData data) {
SipApplicationSessionTaskData sasData = (SipApplicationSessionTaskData)data;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sasData.getKey(), false);
if(sipApplicationSession != null) {
if(sipApplicationSession.getExpirationTimerTask() == null) {
if(((SipContext)sipManager.getContainer()).getConcurrencyControlMode() != ConcurrencyControlMode.SipApplicationSession) {
if(logger.isDebugEnabled()) {
logger.debug("sip application session for key " + sasData.getKey() + " was found");
}
FaultTolerantSasTimerTask faultTolerantSasTimerTask = new FaultTolerantSasTimerTask(sipApplicationSession, sasData);
if(sipApplicationSession != null) {
sipApplicationSession.setExpirationTimerTask(faultTolerantSasTimerTask);
}
return faultTolerantSasTimerTask;
}
}
} else {
logger.debug("sip application session for key " + sasData.getKey() + " was not found neither locally or in the cache, not recovering the sas timer task");
}
// returning null to avoid recovery since it was already recovered above
return null;
}
|
diff --git a/src/org/ietf/uri/event/ProgressEvent.java b/src/org/ietf/uri/event/ProgressEvent.java
index bfbc9ca..a95706e 100644
--- a/src/org/ietf/uri/event/ProgressEvent.java
+++ b/src/org/ietf/uri/event/ProgressEvent.java
@@ -1,200 +1,200 @@
/*****************************************************************************
* The Virtual Light Company Copyright (c) 1999
* Java Source
*
* This code is licensed under the GNU Library GPL. Please read license.txt
* for the full details. A copy of the LGPL may be found at
*
* http://www.gnu.org/copyleft/lgpl.html
*
* Project: URI Class libs
*
* Version History
* Date TR/IWOR Version Programmer
* ---------- ------- ------- ------------------------------------------
*
****************************************************************************/
package org.ietf.uri.event;
import org.ietf.uri.ResourceConnection;
/**
* An event used to inform the client of the progress of a particular download.
* <P>
*
* The event starts by issuing a <CODE>DOWNLOAD_START</CODE>. This indicates
* that the stream has been established and that there is content to read.
* Depending on the stream and length, an <CODE>UPDATE</CODE> event is sent
* that indicates the number of bytes read so far and any message that may be
* of relevance. Once the reading and conversion is complete, a
* <CODE>DOWNLOAD_END</CODE> event is issued.
* <P>
*
* It is possible, that for some connections that only start and end events
* are generated. If the event does not need the value, it should be set to
* a negative value.
* <P>
*
* If some error has occurred, a <CODE>DOWNLOAD_ERROR</CODE> event is
* generated. The value contains some error code (either those provided here
* of connection specific) and a message string. Errors that occur through
* this event should be considered terminal to the download progress. That is,
* the <CODE>getContent()</CODE> method of the
* {@link org.ietf.uri.ResourceConnection} class may return <CODE>null</CODE>
* of a value with incomplete results. That is dependent on the underlying
* content handlers.
* <P>
*
* Events are also available for the setup part of establishing connections.
* These events may or may not be generated depending on the underlying
* protocol. For example, the connection established event is pointless when
* reading from a local file, but perfect for a HTTP connection.
* <P>
*
* For details on URIs see the IETF working group:
* <A HREF="http://www.ietf.org/html.charters/urn-charter.html">URN</A>
* <P>
*
* This softare is released under the
* <A HREF="http://www.gnu.org/copyleft/lgpl.html">GNU LGPL</A>
* <P>
*
* DISCLAIMER:<BR>
* This software is the under development, incomplete, and is
* known to contain bugs. This software is made available for
* review purposes only. Do not rely on this software for
* production-quality applications or for mission-critical
* applications.
* <P>
*
* Portions of the APIs for some new features have not
* been finalized and APIs may change. Some features are
* not fully implemented in this release. Use at your own risk.
* <P>
*
* @author Justin Couch
* @version 0.7 (27 August 1999)
*/
public class ProgressEvent
{
// Event types
/**
* The connection has been established to the resource, but information
* download has not yet commenced - ie, it is looking at fetching the
* headers and other useful stuff.
*/
public static final int CONNECTION_ESTABLISHED = 1;
/** The header information is being downloaded and processed. The real
* data has not got there yet.
*/
public static final int HANDSHAKE_IN_PROGRESS = 2;
/** The download has started */
public static final int DOWNLOAD_START = 3;
/** The download has finished */
public static final int DOWNLOAD_END = 4;
/** An update on the download progress */
public static final int DOWNLOAD_UPDATE = 5;
/** An error has occurred during the download */
public static final int DOWNLOAD_ERROR = 6;
// Error types
/**
* Connection terminated prematurely. Either the server closed the
* connection or the network died. If used when referencing a file
* that means the file didn't contain all the data it was supposed to.
*/
public static final int CONNECTION_TERMINATED = 1;
/**
* The data is corrupted or not of a format that the content handler knows
* about.
*/
public static final int DATA_CORRUPTED = 2;
/** No handlers can be found for the data type specified by the connection.*/
public static final int NO_HANDLER = 3;
// Variables etc
/** The connection that was the source of this event */
protected ResourceConnection source;
/**
* The value of the current event. If this is an update event, this is the
* number of bytes that have been downloaded from the source. If it is an
* error event, then this is the error value
*/
protected int value;
/** A message to go with the event. May be <CODE>null</CODE> if not set */
protected String msg = null;
/** The event type */
protected int type;
/**
* Create a new progress event that is used to inform the listeners of an
* update by the data source.
*
* @param src The resource connection that is generating the events
* @param type The type of event to generate
* @param msg The message to send with the event. May be <CODE>null</CODE>
* @param val The value of the event.
*/
public ProgressEvent(ResourceConnection src, int type, String msg, int val)
{
this.source = src;
this.msg = msg;
- this.value = value;
+ this.value = val;
this.type = type;
}
/**
* Get the source (resource connection, not the content handler) of this
* event
*
* @return The ResourceConnection source
*/
public ResourceConnection getSource()
{
return source;
}
/**
* Fetch the value associated with this event.
*
* @return The value set for this event
*/
public int getValue()
{
return value;
}
/**
* Fetch the message associated with this event. There may not have been a
* message set, so it may return <CODE>null</CODE>.
*
* @return The message string
*/
public String getMessage()
{
return msg;
}
/**
* Get the type of event that was generated
*
* @return The type ID of the event
*/
public int getType()
{
return type;
}
}
| true | true | public ProgressEvent(ResourceConnection src, int type, String msg, int val)
{
this.source = src;
this.msg = msg;
this.value = value;
this.type = type;
}
| public ProgressEvent(ResourceConnection src, int type, String msg, int val)
{
this.source = src;
this.msg = msg;
this.value = val;
this.type = type;
}
|
diff --git a/webui/core/src/main/java/org/exoplatform/webui/form/UIFormDateTimeInput.java b/webui/core/src/main/java/org/exoplatform/webui/form/UIFormDateTimeInput.java
index acaef9b..de53fc4 100644
--- a/webui/core/src/main/java/org/exoplatform/webui/form/UIFormDateTimeInput.java
+++ b/webui/core/src/main/java/org/exoplatform/webui/form/UIFormDateTimeInput.java
@@ -1,239 +1,239 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* 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.exoplatform.webui.form;
import org.exoplatform.webui.application.WebuiRequestContext;
import java.io.Writer;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* Created by The eXo Platform SARL
* Author : Tran The Trong
* [email protected]
* Jul 14, 2006
*
* A date picker element
*/
public class UIFormDateTimeInput extends UIFormInputBase<String>
{
/**
* The DateFormat
*/
private DateFormat dateFormat_;
/**
* Whether to display the full time (with hours, minutes and seconds), not only the date
*/
private boolean isDisplayTime_;
/**
* The Date Pattern. Ex: dd/mm/yyyy
*/
private String datePattern_;
/**
* The date
*/
private Date date;
/**
* List of month's name
*/
private String[] months_;
public UIFormDateTimeInput(String name, String bindField, Date date, boolean isDisplayTime)
{
super(name, bindField, String.class);
this.date = date;
setDisplayTime(isDisplayTime);
WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();
formatPattern(requestContext.getLocale());
}
public UIFormDateTimeInput(String name, String bindField, Date date)
{
this(name, bindField, date, true);
}
/**
* By default, creates a date of format Month/Day/Year
* If isDisplayTime is true, adds the time of format Hours:Minutes:Seconds
* TODO : Display time depending on the locale of the client.
* @param isDisplayTime
*/
public void setDisplayTime(boolean isDisplayTime)
{
isDisplayTime_ = isDisplayTime;
}
public void setCalendar(Calendar date)
{
WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();
formatPattern(requestContext.getLocale());
if (date != null)
{
this.date = date.getTime();
value_ = dateFormat_.format(date.getTime());
}
else
{
this.date = null;
value_ = null;
}
}
public Calendar getCalendar()
{
try
{
Calendar calendar = new GregorianCalendar();
calendar.setTime(dateFormat_.parse(value_ + " 0:0:0"));
return calendar;
}
catch (ParseException e)
{
return null;
}
}
private void setDatePattern_(String datePattern_)
{
this.datePattern_ = datePattern_;
}
public String getDatePattern_()
{
return datePattern_;
}
private void formatPattern(Locale locale)
{
if (isDisplayTime_)
{
dateFormat_ = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
}
else
{
dateFormat_ = SimpleDateFormat.getDateInstance(DateFormat.SHORT, locale);
}
// convert to unique pattern
setDatePattern_(((SimpleDateFormat)dateFormat_).toPattern());
if (!getDatePattern_().contains("yy"))
{
setDatePattern_(getDatePattern_().replaceAll("y", "yy"));
}
if (!getDatePattern_().contains("yyyy"))
{
setDatePattern_(getDatePattern_().replaceAll("yy", "yyyy"));
}
if (!getDatePattern_().contains("dd"))
{
setDatePattern_(getDatePattern_().replaceAll("d", "dd"));
}
if (!getDatePattern_().contains("MM"))
{
setDatePattern_(getDatePattern_().replaceAll("M", "MM"));
}
setDatePattern_(getDatePattern_().replaceAll("h", "H"));
if (!getDatePattern_().contains("HH"))
{
setDatePattern_(getDatePattern_().replaceAll("H", "HH"));
}
if (getDatePattern_().contains("a"))
{
setDatePattern_(getDatePattern_().replaceAll("a", ""));
}
dateFormat_ = new SimpleDateFormat(getDatePattern_());
DateFormatSymbols symbols = new DateFormatSymbols(locale);
months_ = symbols.getMonths();
}
@SuppressWarnings("unused")
public void decode(Object input, WebuiRequestContext context) throws Exception
{
if (input != null)
value_ = ((String)input).trim();
}
public void processRender(WebuiRequestContext context) throws Exception
{
WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();
formatPattern(requestContext.getLocale());
String monthNames_ = "";
for (String month : months_)
{
// remove empty element
if (!month.equals(""))
{
monthNames_ += month + ",";
}
}
if (date != null)
{
value_ = dateFormat_.format(date);
}
else if (value_ == null)
{
value_ = "";
}
context.getJavascriptManager().importJavascript("eXo.webui.UICalendar");
Writer w = context.getWriter();
w.write("<input type='text' onfocus='eXo.webui.UICalendar.init(this,");
w.write(String.valueOf(isDisplayTime_));
w.write(",\"");
w.write(getDatePattern_());
w.write("\"");
w.write(",\"");
w.write(value_.toString());
w.write("\"");
w.write(",\"");
w.write(monthNames_);
w.write("\"");
w.write(");' onkeyup='eXo.webui.UICalendar.show();' name='");
w.write(getName());
w.write('\'');
if (value_ != null && value_.length() > 0)
{
w.write(" value='");
w.write(value_.toString());
w.write('\'');
}
- w.write(" onmousedown='event.cancelBubble = true' />");
+ w.write(" onclick='event.cancelBubble = true'/>");
}
}
| true | true | public void processRender(WebuiRequestContext context) throws Exception
{
WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();
formatPattern(requestContext.getLocale());
String monthNames_ = "";
for (String month : months_)
{
// remove empty element
if (!month.equals(""))
{
monthNames_ += month + ",";
}
}
if (date != null)
{
value_ = dateFormat_.format(date);
}
else if (value_ == null)
{
value_ = "";
}
context.getJavascriptManager().importJavascript("eXo.webui.UICalendar");
Writer w = context.getWriter();
w.write("<input type='text' onfocus='eXo.webui.UICalendar.init(this,");
w.write(String.valueOf(isDisplayTime_));
w.write(",\"");
w.write(getDatePattern_());
w.write("\"");
w.write(",\"");
w.write(value_.toString());
w.write("\"");
w.write(",\"");
w.write(monthNames_);
w.write("\"");
w.write(");' onkeyup='eXo.webui.UICalendar.show();' name='");
w.write(getName());
w.write('\'');
if (value_ != null && value_.length() > 0)
{
w.write(" value='");
w.write(value_.toString());
w.write('\'');
}
w.write(" onmousedown='event.cancelBubble = true' />");
}
| public void processRender(WebuiRequestContext context) throws Exception
{
WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();
formatPattern(requestContext.getLocale());
String monthNames_ = "";
for (String month : months_)
{
// remove empty element
if (!month.equals(""))
{
monthNames_ += month + ",";
}
}
if (date != null)
{
value_ = dateFormat_.format(date);
}
else if (value_ == null)
{
value_ = "";
}
context.getJavascriptManager().importJavascript("eXo.webui.UICalendar");
Writer w = context.getWriter();
w.write("<input type='text' onfocus='eXo.webui.UICalendar.init(this,");
w.write(String.valueOf(isDisplayTime_));
w.write(",\"");
w.write(getDatePattern_());
w.write("\"");
w.write(",\"");
w.write(value_.toString());
w.write("\"");
w.write(",\"");
w.write(monthNames_);
w.write("\"");
w.write(");' onkeyup='eXo.webui.UICalendar.show();' name='");
w.write(getName());
w.write('\'');
if (value_ != null && value_.length() > 0)
{
w.write(" value='");
w.write(value_.toString());
w.write('\'');
}
w.write(" onclick='event.cancelBubble = true'/>");
}
|
diff --git a/src/org/e2k/CIS3650.java b/src/org/e2k/CIS3650.java
index f7a69b8..d412fab 100644
--- a/src/org/e2k/CIS3650.java
+++ b/src/org/e2k/CIS3650.java
@@ -1,443 +1,442 @@
package org.e2k;
import java.util.Arrays;
import javax.swing.JOptionPane;
// From info received (which I'm very grateful for) it appears CIS36-50 (BEE) messages have the following format
// 44 bit sync sequence made up so if these bits 21 are true and 23 false
// 70 bit session key made up of 7 bit blocks of which 3 bits are true and 4 bits false
// same 70 bit session key is then repeated
// followed by the message which is made up of encrypted ITA-3 characters (so again 3 bits true and 4 false)
// the end of the message is signalled with the binary sequence 1110111 1110111 1110111
public class CIS3650 extends FSK {
private int state=0;
private double samplesPerSymbol50;
private double samplesPerSymbol36;
private Rivet theApp;
public long sampleCount=0;
private long symbolCounter=0;
public StringBuffer lineBuffer=new StringBuffer();
private int highTone;
private int lowTone;
private int centre;
private int syncState;
private int buffer7=0;
private int buffer21=0;
private int characterCount;
private int startCount;
private int keyCount;
private int key1[]=new int[10];
private int key2[]=new int[10];
private boolean syncBuffer[]=new boolean[44];
private int syncBufferCounter=0;
private final int ITA3VALS[]={26,25,76,28,56,19,97,82,112,35,11,98,97,84,70,74,13,100,42,69,50,73,37,22,21,49,67,88,14,38,104,7,52,41,44,81};
private final String ITA3LETS[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","<cr>","<lf>","<let>","<fig>"," ","<unperf>","<Request>","<Idle a>","<Idle b>","<0x51>"};
private int totalCharacterCount=0;
private int totalErrorCount=0;
public CIS3650 (Rivet tapp) {
theApp=tapp;
}
// The main decode routine
public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()>11025.0) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nCIS 36-50 recordings must have\nbeen recorded at a sample rate\nof 11.025 KHz or less.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
samplesPerSymbol36=samplesPerSymbol(36.0,waveData.getSampleRate());
samplesPerSymbol50=samplesPerSymbol(50.0,waveData.getSampleRate());
state=1;
lineBuffer.delete(0,lineBuffer.length());
syncState=0;
buffer7=0;
buffer21=0;
characterCount=0;
syncBufferCounter=0;
return null;
}
// Look for a 36 baud or a 50 baud alternating sequence
if (state==1) {
sampleCount++;
if (sampleCount<0) return null;
// Look for a 36 baud alternating sync sequence
if ((syncState==0)&&(detect36Sync(circBuf,waveData)==true)) {
outLines[0]=theApp.getTimeStamp()+" CIS 36-50 36 baud sync sequence found";
syncState=1;
return outLines;
}
// Look for a 50 baud alternating sync sequence
if (detect50Sync(circBuf,waveData)==true) {
outLines[0]=theApp.getTimeStamp()+" CIS 36-50 50 baud sync sequence found";
// Jump the next stage to acquire symbol timing
state=3;
totalErrorCount=0;
totalCharacterCount=0;
syncState=1;
return outLines;
}
}
// Read in symbols
if (state==3) {
// Only demodulate a bit every samplesPerSymbol50 samples
if (symbolCounter>=(long)samplesPerSymbol50) {
// Get the early/late gate difference value
double gateDif=gateEarlyLate(circBuf,(int)samplesPerSymbol50);
// Adjust the symbol counter as required to obtain symbol sync
- if ((gateDif<-15)||(gateDif>15)) symbolCounter=(int)gateDif/3;
- else symbolCounter=0;
+ symbolCounter=(int)gateDif/3;
// Demodulate a single bit
boolean bit=getSymbolBit(circBuf,waveData,0);
if (theApp.isDebug()==false) {
if (syncState==1) {
addToSyncBuffer(bit);
// Check if the sync buffer holds a valid sync word
if (syncValidCheck()==true) {
syncState=2;
outLines[0]="Message Start";
long header=syncBufferAsLong();
outLines[1]="Sync 0x"+Long.toHexString(header);
buffer21=0;
buffer7=0;
keyCount=0;
startCount=0;
totalCharacterCount=0;
}
}
// Once we have the 44 bit sync sequence get the two 70 bit keys
else if (syncState==2) {
addToBuffer7(bit);
startCount++;
if (startCount==7) {
if (keyCount<10) key1[keyCount]=buffer7;
else key2[keyCount-10]=buffer7;
if (keyCount==19) {
syncState=3;
outLines[0]="Session Key is ";
int a;
for (a=0;a<10;a++) {
// Check the session key is made up of valid ITA3 numbers
if (checkITA3Char(key1[a])==true) {
int c=retITA3Val(key1[a]);
outLines[0]=outLines[0]+"0x"+Integer.toHexString(c)+" ";
}
else {
outLines[0]=outLines[0]+"<ERROR> ";
}
}
// Both keys should be the same
if (!Arrays.equals(key1,key2)) outLines[0]=outLines[0]+" (ERROR SESSION KEY MISMATCH)";
}
else keyCount++;
startCount=0;
}
}
// Read in and display the main body of the message
else if (syncState==3) {
addToBuffer7(bit);
addToBuffer21(bit);
startCount++;
// Look for the end of message sequence
if (buffer21==0x1DFBF7) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
syncState=4;
}
// Every 7 bits we should have an ITA-3 character
if (startCount==7) {
if (checkITA3Char(buffer7)==true) {
int c=retITA3Val(buffer7);
lineBuffer.append(ITA3LETS[c]);
}
else {
// Display 0x77 characters as signalling the end of a message
if (buffer7==0x77) {
lineBuffer.append("<EOM>");
}
else {
lineBuffer.append("<ERROR ");
lineBuffer.append(Integer.toString(buffer7));
lineBuffer.append("> ");
totalErrorCount++;
}
}
startCount=0;
buffer7=0;
characterCount++;
// Keep a count of the total number of characters in a message
totalCharacterCount++;
// If a message has gone on for 5000 characters there must be a problem so force an end
if (totalCharacterCount>5000) syncState=4;
}
// Display 50 characters on a line
if (characterCount==50) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
}
// The message must have ended
else if (syncState==4) {
double err=((double)totalErrorCount/(double)totalCharacterCount)*100.0;
outLines[0]="End of Message ("+Integer.toString(totalCharacterCount)+" characters in this message "+Double.toString(err)+"% of these contained errors)";
syncBufferCounter=0;
state=1;
}
}
else {
// Debug mode so just display raw binary
if (bit==true) lineBuffer.append("1");
else lineBuffer.append("0");
if (characterCount==60) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
else characterCount++;
}
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
public void setState(int state) {
this.state = state;
}
public int getState() {
return state;
}
// Get the frequency at a certain symbol
private int getSymbolFreq (CircularDataBuffer circBuf,WaveData waveData,int start) {
int fr=do64FFT(circBuf,waveData,start);
return fr;
}
// Return the bit value for a certain symbol
private boolean getSymbolBit (CircularDataBuffer circBuf,WaveData waveData,int start) {
int f=getSymbolFreq(circBuf,waveData,start);
boolean bit=freqDecision(f,centre,theApp.isInvertSignal());
return bit;
}
// Add a bit to the 7 bit buffer
private void addToBuffer7(boolean bit) {
buffer7<<=1;
buffer7=buffer7&0x7F;
if (bit==true) buffer7++;
}
// Add a bit to the 21 bit buffer
private void addToBuffer21(boolean bit) {
buffer21<<=1;
buffer21=buffer21&0x1FFFFF;
if (bit==true) buffer21++;
}
// See if the buffer holds a 36 baud alternating sequence
private boolean detect36Sync(CircularDataBuffer circBuf,WaveData waveData) {
int pos=0;
int f0=getSymbolFreq(circBuf,waveData,pos);
// Check this first tone isn't just noise the highest bin must make up 10% of the total
if (getPercentageOfTotal()<10.0) return false;
pos=(int)samplesPerSymbol36*1;
int f1=getSymbolFreq(circBuf,waveData,pos);
if (f0==f1) return false;
pos=(int)samplesPerSymbol36*2;
int f2=getSymbolFreq(circBuf,waveData,pos);
pos=(int)samplesPerSymbol36*3;
int f3=getSymbolFreq(circBuf,waveData,pos);
if (f3!=9999) return false;
// Look for a 36 baud alternating sequence
if ((f0==f2)&&(f1==f3)&&(f0!=f1)&&(f2!=f3)) {
if (f0>f1) {
highTone=f0;
lowTone=f1;
}
else {
highTone=f1;
lowTone=f0;
}
centre=(highTone+lowTone)/2;
int shift=highTone-lowTone;
// Check for an incorrect shift
if ((shift>300)||(shift<150)) return false;
return true;
}
return false;
}
// See if the buffer holds a 50 baud alternating sequence
private boolean detect50Sync(CircularDataBuffer circBuf,WaveData waveData) {
int pos=0,b0,b1,b2,b3;
int f0=getSymbolFreq(circBuf,waveData,pos);
b0=getFreqBin();
// Check this first tone isn't just noise the highest bin must make up 10% of the total
if (getPercentageOfTotal()<10.0) return false;
pos=(int)samplesPerSymbol50*1;
int f1=getSymbolFreq(circBuf,waveData,pos);
b1=getFreqBin();
if (f0==f1) return false;
pos=(int)samplesPerSymbol50*2;
int f2=getSymbolFreq(circBuf,waveData,pos);
b2=getFreqBin();
if (f1==f2) return false;
pos=(int)samplesPerSymbol50*3;
int f3=getSymbolFreq(circBuf,waveData,pos);
b3=getFreqBin();
// Look for a 50 baud alternating sequence
if ((f0==f2)&&(f1==f3)&&(f0!=f1)&&(f2!=f3)) {
if (f0>f1) {
highTone=f0;
lowTone=f1;
}
else {
highTone=f1;
lowTone=f0;
}
pos=(int)samplesPerSymbol50*4;
int f4=getSymbolFreq(circBuf,waveData,pos);
pos=(int)samplesPerSymbol50*5;
int f5=getSymbolFreq(circBuf,waveData,pos);
if ((f3!=f5)||(f2!=f4)) return false;
centre=(highTone+lowTone)/2;
int shift=highTone-lowTone;
// Check for an incorrect shift
if ((shift>300)||(shift<150)) return false;
return true;
}
return false;
}
// Add a bit to the 44 bit sync buffer
private void addToSyncBuffer (boolean bit) {
int a;
// Move all bits one bit to the left
for (a=1;a<syncBuffer.length;a++) {
syncBuffer[a-1]=syncBuffer[a];
}
int last=syncBuffer.length-1;
syncBuffer[last]=bit;
syncBufferCounter++;
}
// Return true if this appears to be a valid sync word
private boolean syncValidCheck () {
int a,count=0;
if (syncBufferCounter<(syncBuffer.length-1)) return false;
for (a=0;a<syncBuffer.length;a++) {
if (syncBuffer[a]==true) count++;
}
//int mid=syncBufferMiddleAsInt();
//if ((mid!=0xeb)&&(mid!=14)) return false;
// If count is 23 and the first three bits are true this OK but we are inverted
if ((count==23)&&(syncBuffer[0]==true)&&(syncBuffer[1]==true)&&(syncBuffer[2]==true)) {
// Change the invert setting
theApp.changeInvertSetting();
// Invert the complete sync buffer to reflect the change
syncBufferInvert();
int mid=syncBufferMiddleAsInt();
if (mid!=235) return false;
return true;
}
// If the count is 21 and the first three bits are false then we are all OK
else if ((count==21)&&(syncBuffer[0]==false)&&(syncBuffer[1]==false)&&(syncBuffer[2]==false)) {
int mid=syncBufferMiddleAsInt();
if (mid!=235) return false;
return true;
}
// No match
else return false;
}
// Return the sync buffer a long
private long syncBufferAsLong () {
int a,bc=0;
long r=0;
for (a=(syncBuffer.length-1);a>=0;a--) {
if (syncBuffer[a]==true) r=r+(long)Math.pow(2.0,bc);
bc++;
}
return r;
}
// Invert the sync buffer
private void syncBufferInvert () {
int a;
for (a=0;a<syncBuffer.length;a++) {
if (syncBuffer[a]==true) syncBuffer[a]=false;
else syncBuffer[a]=true;
}
}
private int syncBufferMiddleAsInt () {
int a,bc=7,r=0;
for (a=20;a<28;a++) {
if (syncBuffer[a]==true) r=r+(int)Math.pow(2.0,bc);
bc--;
}
return r;
}
// Check if a number if a valid ITA-3 character
private boolean checkITA3Char (int c) {
int a;
for (a=0;a<ITA3VALS.length;a++) {
if (c==ITA3VALS[a]) return true;
}
return false;
}
// Return a ITA-3 character
private int retITA3Val (int c) {
int a;
for (a=0;a<ITA3VALS.length;a++) {
if (c==ITA3VALS[a]) return a;
}
return 0;
}
}
| true | true | public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()>11025.0) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nCIS 36-50 recordings must have\nbeen recorded at a sample rate\nof 11.025 KHz or less.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
samplesPerSymbol36=samplesPerSymbol(36.0,waveData.getSampleRate());
samplesPerSymbol50=samplesPerSymbol(50.0,waveData.getSampleRate());
state=1;
lineBuffer.delete(0,lineBuffer.length());
syncState=0;
buffer7=0;
buffer21=0;
characterCount=0;
syncBufferCounter=0;
return null;
}
// Look for a 36 baud or a 50 baud alternating sequence
if (state==1) {
sampleCount++;
if (sampleCount<0) return null;
// Look for a 36 baud alternating sync sequence
if ((syncState==0)&&(detect36Sync(circBuf,waveData)==true)) {
outLines[0]=theApp.getTimeStamp()+" CIS 36-50 36 baud sync sequence found";
syncState=1;
return outLines;
}
// Look for a 50 baud alternating sync sequence
if (detect50Sync(circBuf,waveData)==true) {
outLines[0]=theApp.getTimeStamp()+" CIS 36-50 50 baud sync sequence found";
// Jump the next stage to acquire symbol timing
state=3;
totalErrorCount=0;
totalCharacterCount=0;
syncState=1;
return outLines;
}
}
// Read in symbols
if (state==3) {
// Only demodulate a bit every samplesPerSymbol50 samples
if (symbolCounter>=(long)samplesPerSymbol50) {
// Get the early/late gate difference value
double gateDif=gateEarlyLate(circBuf,(int)samplesPerSymbol50);
// Adjust the symbol counter as required to obtain symbol sync
if ((gateDif<-15)||(gateDif>15)) symbolCounter=(int)gateDif/3;
else symbolCounter=0;
// Demodulate a single bit
boolean bit=getSymbolBit(circBuf,waveData,0);
if (theApp.isDebug()==false) {
if (syncState==1) {
addToSyncBuffer(bit);
// Check if the sync buffer holds a valid sync word
if (syncValidCheck()==true) {
syncState=2;
outLines[0]="Message Start";
long header=syncBufferAsLong();
outLines[1]="Sync 0x"+Long.toHexString(header);
buffer21=0;
buffer7=0;
keyCount=0;
startCount=0;
totalCharacterCount=0;
}
}
// Once we have the 44 bit sync sequence get the two 70 bit keys
else if (syncState==2) {
addToBuffer7(bit);
startCount++;
if (startCount==7) {
if (keyCount<10) key1[keyCount]=buffer7;
else key2[keyCount-10]=buffer7;
if (keyCount==19) {
syncState=3;
outLines[0]="Session Key is ";
int a;
for (a=0;a<10;a++) {
// Check the session key is made up of valid ITA3 numbers
if (checkITA3Char(key1[a])==true) {
int c=retITA3Val(key1[a]);
outLines[0]=outLines[0]+"0x"+Integer.toHexString(c)+" ";
}
else {
outLines[0]=outLines[0]+"<ERROR> ";
}
}
// Both keys should be the same
if (!Arrays.equals(key1,key2)) outLines[0]=outLines[0]+" (ERROR SESSION KEY MISMATCH)";
}
else keyCount++;
startCount=0;
}
}
// Read in and display the main body of the message
else if (syncState==3) {
addToBuffer7(bit);
addToBuffer21(bit);
startCount++;
// Look for the end of message sequence
if (buffer21==0x1DFBF7) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
syncState=4;
}
// Every 7 bits we should have an ITA-3 character
if (startCount==7) {
if (checkITA3Char(buffer7)==true) {
int c=retITA3Val(buffer7);
lineBuffer.append(ITA3LETS[c]);
}
else {
// Display 0x77 characters as signalling the end of a message
if (buffer7==0x77) {
lineBuffer.append("<EOM>");
}
else {
lineBuffer.append("<ERROR ");
lineBuffer.append(Integer.toString(buffer7));
lineBuffer.append("> ");
totalErrorCount++;
}
}
startCount=0;
buffer7=0;
characterCount++;
// Keep a count of the total number of characters in a message
totalCharacterCount++;
// If a message has gone on for 5000 characters there must be a problem so force an end
if (totalCharacterCount>5000) syncState=4;
}
// Display 50 characters on a line
if (characterCount==50) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
}
// The message must have ended
else if (syncState==4) {
double err=((double)totalErrorCount/(double)totalCharacterCount)*100.0;
outLines[0]="End of Message ("+Integer.toString(totalCharacterCount)+" characters in this message "+Double.toString(err)+"% of these contained errors)";
syncBufferCounter=0;
state=1;
}
}
else {
// Debug mode so just display raw binary
if (bit==true) lineBuffer.append("1");
else lineBuffer.append("0");
if (characterCount==60) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
else characterCount++;
}
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
| public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()>11025.0) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nCIS 36-50 recordings must have\nbeen recorded at a sample rate\nof 11.025 KHz or less.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
samplesPerSymbol36=samplesPerSymbol(36.0,waveData.getSampleRate());
samplesPerSymbol50=samplesPerSymbol(50.0,waveData.getSampleRate());
state=1;
lineBuffer.delete(0,lineBuffer.length());
syncState=0;
buffer7=0;
buffer21=0;
characterCount=0;
syncBufferCounter=0;
return null;
}
// Look for a 36 baud or a 50 baud alternating sequence
if (state==1) {
sampleCount++;
if (sampleCount<0) return null;
// Look for a 36 baud alternating sync sequence
if ((syncState==0)&&(detect36Sync(circBuf,waveData)==true)) {
outLines[0]=theApp.getTimeStamp()+" CIS 36-50 36 baud sync sequence found";
syncState=1;
return outLines;
}
// Look for a 50 baud alternating sync sequence
if (detect50Sync(circBuf,waveData)==true) {
outLines[0]=theApp.getTimeStamp()+" CIS 36-50 50 baud sync sequence found";
// Jump the next stage to acquire symbol timing
state=3;
totalErrorCount=0;
totalCharacterCount=0;
syncState=1;
return outLines;
}
}
// Read in symbols
if (state==3) {
// Only demodulate a bit every samplesPerSymbol50 samples
if (symbolCounter>=(long)samplesPerSymbol50) {
// Get the early/late gate difference value
double gateDif=gateEarlyLate(circBuf,(int)samplesPerSymbol50);
// Adjust the symbol counter as required to obtain symbol sync
symbolCounter=(int)gateDif/3;
// Demodulate a single bit
boolean bit=getSymbolBit(circBuf,waveData,0);
if (theApp.isDebug()==false) {
if (syncState==1) {
addToSyncBuffer(bit);
// Check if the sync buffer holds a valid sync word
if (syncValidCheck()==true) {
syncState=2;
outLines[0]="Message Start";
long header=syncBufferAsLong();
outLines[1]="Sync 0x"+Long.toHexString(header);
buffer21=0;
buffer7=0;
keyCount=0;
startCount=0;
totalCharacterCount=0;
}
}
// Once we have the 44 bit sync sequence get the two 70 bit keys
else if (syncState==2) {
addToBuffer7(bit);
startCount++;
if (startCount==7) {
if (keyCount<10) key1[keyCount]=buffer7;
else key2[keyCount-10]=buffer7;
if (keyCount==19) {
syncState=3;
outLines[0]="Session Key is ";
int a;
for (a=0;a<10;a++) {
// Check the session key is made up of valid ITA3 numbers
if (checkITA3Char(key1[a])==true) {
int c=retITA3Val(key1[a]);
outLines[0]=outLines[0]+"0x"+Integer.toHexString(c)+" ";
}
else {
outLines[0]=outLines[0]+"<ERROR> ";
}
}
// Both keys should be the same
if (!Arrays.equals(key1,key2)) outLines[0]=outLines[0]+" (ERROR SESSION KEY MISMATCH)";
}
else keyCount++;
startCount=0;
}
}
// Read in and display the main body of the message
else if (syncState==3) {
addToBuffer7(bit);
addToBuffer21(bit);
startCount++;
// Look for the end of message sequence
if (buffer21==0x1DFBF7) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
syncState=4;
}
// Every 7 bits we should have an ITA-3 character
if (startCount==7) {
if (checkITA3Char(buffer7)==true) {
int c=retITA3Val(buffer7);
lineBuffer.append(ITA3LETS[c]);
}
else {
// Display 0x77 characters as signalling the end of a message
if (buffer7==0x77) {
lineBuffer.append("<EOM>");
}
else {
lineBuffer.append("<ERROR ");
lineBuffer.append(Integer.toString(buffer7));
lineBuffer.append("> ");
totalErrorCount++;
}
}
startCount=0;
buffer7=0;
characterCount++;
// Keep a count of the total number of characters in a message
totalCharacterCount++;
// If a message has gone on for 5000 characters there must be a problem so force an end
if (totalCharacterCount>5000) syncState=4;
}
// Display 50 characters on a line
if (characterCount==50) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
}
// The message must have ended
else if (syncState==4) {
double err=((double)totalErrorCount/(double)totalCharacterCount)*100.0;
outLines[0]="End of Message ("+Integer.toString(totalCharacterCount)+" characters in this message "+Double.toString(err)+"% of these contained errors)";
syncBufferCounter=0;
state=1;
}
}
else {
// Debug mode so just display raw binary
if (bit==true) lineBuffer.append("1");
else lineBuffer.append("0");
if (characterCount==60) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
characterCount=0;
}
else characterCount++;
}
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
|
diff --git a/src/main/java/com/softartisans/timberwolf/exchange/GetItemIterator.java b/src/main/java/com/softartisans/timberwolf/exchange/GetItemIterator.java
index e8c9bf0..f0d4038 100644
--- a/src/main/java/com/softartisans/timberwolf/exchange/GetItemIterator.java
+++ b/src/main/java/com/softartisans/timberwolf/exchange/GetItemIterator.java
@@ -1,58 +1,58 @@
package com.softartisans.timberwolf.exchange;
import com.softartisans.timberwolf.MailboxItem;
import java.util.Iterator;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An iterator that calls getItem to get a list of the actual items for
* the given list of ids.
*
* This class pages the calls to getItems.
*/
public class GetItemIterator extends BaseChainIterator<MailboxItem>
{
private static final Logger LOG = LoggerFactory.getLogger(GetItemIterator.class);
private ExchangeService service;
private Vector<String> ids;
private int currentStart;
private int pageSize;
public GetItemIterator(final ExchangeService exchangeService, final Vector<String> messageIds,
final int itemsPageSize)
{
service = exchangeService;
ids = messageIds;
pageSize = itemsPageSize;
currentStart = 0;
}
@Override
protected Iterator<MailboxItem> createIterator()
{
if (currentStart > ids.size())
{
return null;
}
try
{
Vector<MailboxItem> ret = GetItemHelper.getItems(pageSize, currentStart, ids, service);
LOG.debug("Got {} email ids.", ret.size());
currentStart += pageSize;
return ret.iterator();
}
catch (ServiceCallException e)
{
- LOG.error("Failed to find item ids.", e);
- throw new ExchangeRuntimeException("Failed to find item ids.", e);
+ LOG.error("Failed to get emails.", e);
+ throw new ExchangeRuntimeException("Failed to get emails.", e);
}
catch (HttpErrorException e)
{
- LOG.error("Failed to find item ids.", e);
- throw new ExchangeRuntimeException("Failed to find item ids.", e);
+ LOG.error("Failed to get emails.", e);
+ throw new ExchangeRuntimeException("Failed to get emails.", e);
}
}
}
| false | true | protected Iterator<MailboxItem> createIterator()
{
if (currentStart > ids.size())
{
return null;
}
try
{
Vector<MailboxItem> ret = GetItemHelper.getItems(pageSize, currentStart, ids, service);
LOG.debug("Got {} email ids.", ret.size());
currentStart += pageSize;
return ret.iterator();
}
catch (ServiceCallException e)
{
LOG.error("Failed to find item ids.", e);
throw new ExchangeRuntimeException("Failed to find item ids.", e);
}
catch (HttpErrorException e)
{
LOG.error("Failed to find item ids.", e);
throw new ExchangeRuntimeException("Failed to find item ids.", e);
}
}
| protected Iterator<MailboxItem> createIterator()
{
if (currentStart > ids.size())
{
return null;
}
try
{
Vector<MailboxItem> ret = GetItemHelper.getItems(pageSize, currentStart, ids, service);
LOG.debug("Got {} email ids.", ret.size());
currentStart += pageSize;
return ret.iterator();
}
catch (ServiceCallException e)
{
LOG.error("Failed to get emails.", e);
throw new ExchangeRuntimeException("Failed to get emails.", e);
}
catch (HttpErrorException e)
{
LOG.error("Failed to get emails.", e);
throw new ExchangeRuntimeException("Failed to get emails.", e);
}
}
|
diff --git a/src/r/builtins/C.java b/src/r/builtins/C.java
index c83ccfc..3c04549 100644
--- a/src/r/builtins/C.java
+++ b/src/r/builtins/C.java
@@ -1,433 +1,433 @@
package r.builtins;
import com.oracle.truffle.api.frame.*;
import com.oracle.truffle.api.nodes.*;
import r.*;
import r.data.*;
import r.data.internal.*;
import r.nodes.*;
import r.nodes.truffle.*;
/**
* "c"
*
* <pre>
* ... -- objects to be concatenated.
* recursive -- logical. If recursive = TRUE, the function recursively descends through lists
* (and pairlists) combining all their elements into a vector.
* </pre>
*/
// FIXME: the set of specializations already implemented is biased by the binarytrees benchmark
// TODO: do more specializations, obvious opportunities include: vectors of same type, same result type, perhaps something for lists as well
// TODO: implement "recursive" argument and note that once this is done, the code will become even closer to that of unlist (refactor)
final class C extends CallFactory {
static final CallFactory _ = new C("c", new String[]{"...", "recursive"}, new String[]{});
private C(String name, String[] parameters, String[] required) {
super(name, parameters, required);
}
// only supports a vector of integers, doubles, or logical
@Override public RNode create(ASTNode call, RSymbol[] names, RNode[] exprs) {
RSymbol[] collapsedNames = collapseEmptyNames(names);
if (exprs.length == 0) { return new Builtin.Builtin0(call, collapsedNames, exprs) {
@Override public RAny doBuiltIn(Frame frame) {
return RNull.getNull();
}
}; }
return Specialized.createUninitialized(call, collapsedNames, exprs);
}
private static <T extends RArray, U extends T> int fillIn(U result, T input, int offset) {
int len = input.size();
for (int i = 0; i < len; i++) {
result.set(offset + i, input.get(i));
}
return offset + len;
}
public static RAny genericCombine(RSymbol[] paramNames, RAny[] params) {
return genericCombine(paramNames, params, false);
}
// drop names (only used from unlist, in combine always false)
public static RAny genericCombine(RSymbol[] paramNames, RAny[] params, boolean dropNames) {
int len = 0;
boolean hasNames = (paramNames != null);
boolean hasNull = false;
boolean hasRaw = false;
boolean hasLogical = false;
boolean hasInt = false;
boolean hasList = false;
boolean hasDouble = false;
boolean hasComplex = false;
boolean hasString = false;
for (int i = 0; i < params.length; i++) { // FIXME: maybe could refactor using the code in Unlist?
RAny v = params[i];
if (v instanceof RNull) {
hasNull = true;
continue;
} else if (v instanceof RList) {
hasList = true;
} else if (v instanceof RString) {
hasString = true;
} else if (v instanceof RComplex) {
hasComplex = true;
} else if (v instanceof RDouble) {
hasDouble = true;
} else if (v instanceof RInt) {
hasInt = true;
} else if (v instanceof RLogical) {
hasLogical = true;
} else if (v instanceof RRaw) {
hasRaw = true;
} else {
throw Utils.nyi("unsupported type");
}
RArray a = (RArray) v;
len += a.size();
if (!dropNames && a.names() != null) {
hasNames = true;
}
}
int offset = 0;
RArray.Names newNames = null;
if (!dropNames && hasNames) {
RSymbol[] names = new RSymbol[len];
int j = 0;
for (int i = 0; i < params.length; i++) {
RAny v = params[i];
if (v instanceof RNull) {
continue;
}
RArray a = (RArray) v;
int asize = a.size();
RArray.Names aNamesPacked = a.names();
RSymbol[] aNames = aNamesPacked == null ? null : aNamesPacked.sequence();
if (aNames == null) {
if (paramNames == null || paramNames[i] == null) {
for (int k = 0; k < asize; k++) {
names[j++] = RSymbol.EMPTY_SYMBOL;
}
continue;
}
if (asize == 1) {
names[j++] = paramNames[i];
continue;
}
if (asize == 0) {
continue;
}
String prefix = paramNames[i].pretty();
for (int k = 0; k < asize; k++) {
String n = prefix + (k + 1);
names[j++] = RSymbol.getSymbol(n);
}
continue;
}
// aNames != null
if (paramNames == null || paramNames[i] == RSymbol.EMPTY_SYMBOL || paramNames[i] == null) {
for (int k = 0; k < asize; k++) {
names[j++] = aNames[k];
}
continue;
}
String eprefix = paramNames[i].pretty();
String prefix = eprefix + ".";
for (int k = 0; k < asize; k++) {
RSymbol ksymbol = aNames[k];
if (ksymbol == RSymbol.EMPTY_SYMBOL) {
if (asize == 1) {
names[j++] = paramNames[i];
} else {
names[j++] = RSymbol.getSymbol(eprefix + (k + 1));
}
} else {
- String n = prefix + Convert.prettyNA(aNames[k].pretty());
+ String n = prefix + Convert.prettyNA(ksymbol.pretty());
names[j++] = RSymbol.getSymbol(n);
}
}
}
newNames = RArray.Names.create(names);
}
if (hasList) {
ListImpl res = RList.RListFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
RArray a = (RArray) v;
int asize = a.size();
if (v instanceof RList) {
RList l = (RList) v;
for (int i = 0; i < asize; i++) { // shallow copy
RAny ll = l.getRAnyRef(i);
res.set(offset + i, ll);
}
} else {
for (int i = 0; i < asize; i++) {
res.set(offset + i, a.boxedGet(i));
}
}
offset += asize;
}
return res.setNames(newNames);
}
if (hasString) {
RString res = RString.RStringFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RString ? (RString) v : v.asString(), offset);
}
return res.setNames(newNames);
}
if (hasComplex) {
RComplex res = RComplex.RComplexFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RComplex ? (RComplex) v : v.asComplex(), offset);
}
return res.setNames(newNames);
}
if (hasDouble) {
RDouble res = RDouble.RDoubleFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RDouble ? (RDouble) v : v.asDouble(), offset);
}
return res.setNames(newNames);
}
if (hasInt) {
RInt res = RInt.RIntFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RInt ? (RInt) v : v.asInt(), offset);
}
return res.setNames(newNames);
}
if (hasLogical) {
RLogical res = RLogical.RLogicalFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RLogical ? (RLogical) v : v.asLogical(), offset);
}
return res.setNames(newNames);
}
if (hasRaw) {
RRaw res = RRaw.RRawFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RRaw ? (RRaw) v : v.asRaw(), offset);
}
return res.setNames(newNames);
}
if (hasNull) { return RNull.getNull(); }
throw Utils.nyi("Unreacheable");
}
public static Builtin createGeneric(ASTNode ast, final RSymbol[] names, RNode[] exprs) {
return new Builtin(ast, names, exprs) {
@Override public RAny doBuiltIn(Frame frame, RAny[] params) {
return genericCombine(names, params);
}
};
}
enum Transition {
SIMPLE_SCALARS, CASTING_SCALARS, SIMPLE_VECTORS, GENERIC
}
public abstract static class CombineAction {
public abstract RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException;
}
public static class Specialized extends Builtin {
CombineAction combine;
public Specialized(ASTNode orig, RSymbol[] argNames, RNode[] argExprs, CombineAction combine) {
super(orig, argNames, argExprs);
this.combine = combine;
}
public static Specialized createUninitialized(ASTNode ast, RSymbol[] names, RNode[] exprs) {
return createTransition(ast, names, exprs, Transition.SIMPLE_SCALARS);
}
public static Specialized createTransition(ASTNode ast, RSymbol[] names, RNode[] exprs, final Transition t) {
CombineAction a = new CombineAction() {
@Override public final RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException {
throw new UnexpectedResultException(t);
}
};
return new Specialized(ast, names, exprs, a);
}
public static Specialized createSimpleScalars(ASTNode ast, RSymbol[] names, RNode[] exprs, RAny typeTemplate) {
if (names != null) { return createTransition(ast, names, exprs, Transition.GENERIC); }
if (typeTemplate instanceof ScalarStringImpl) {
CombineAction a = new CombineAction() {
@Override public final RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException {
int size = params.length;
String[] content = new String[size];
for (int i = 0; i < size; i++) {
RAny v = params[i];
if (!(v instanceof ScalarStringImpl)) { throw new UnexpectedResultException(Transition.CASTING_SCALARS); }
content[i] = ((ScalarStringImpl) v).getString();
}
return RString.RStringFactory.getFor(content);
}
};
return new Specialized(ast, names, exprs, a);
}
if (typeTemplate instanceof ScalarDoubleImpl) {
CombineAction a = new CombineAction() {
@Override public final RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException {
int size = params.length;
double[] content = new double[size];
for (int i = 0; i < size; i++) {
RAny v = params[i];
if (!(v instanceof ScalarDoubleImpl)) { throw new UnexpectedResultException(Transition.CASTING_SCALARS); }
content[i] = ((ScalarDoubleImpl) v).getDouble();
}
return RDouble.RDoubleFactory.getFor(content);
}
};
return new Specialized(ast, names, exprs, a);
}
if (typeTemplate instanceof ScalarIntImpl) {
CombineAction a = new CombineAction() {
@Override public final RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException {
int size = params.length;
int[] content = new int[size];
for (int i = 0; i < size; i++) {
RAny v = params[i];
if (!(v instanceof ScalarIntImpl)) { throw new UnexpectedResultException(Transition.CASTING_SCALARS); }
content[i] = ((ScalarIntImpl) v).getInt();
}
return RInt.RIntFactory.getFor(content);
}
};
return new Specialized(ast, names, exprs, a);
}
if (typeTemplate instanceof ScalarLogicalImpl) {
CombineAction a = new CombineAction() {
@Override public final RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException {
int size = params.length;
int[] content = new int[size];
for (int i = 0; i < size; i++) {
RAny v = params[i];
if (!(v instanceof ScalarLogicalImpl)) { throw new UnexpectedResultException(Transition.CASTING_SCALARS); }
content[i] = ((ScalarLogicalImpl) v).getLogical();
}
return RLogical.RLogicalFactory.getFor(content);
}
};
return new Specialized(ast, names, exprs, a);
}
// FIXME: add support for strings
return createTransition(ast, names, exprs, Transition.GENERIC);
}
public static Specialized createCastingScalars(ASTNode ast, RSymbol[] names, RNode[] exprs, RAny typeTemplate) {
if (names != null) { return createTransition(ast, names, exprs, Transition.GENERIC); }
if (typeTemplate instanceof RDouble) {
CombineAction a = new CombineAction() {
@Override public final RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException {
int size = params.length;
double[] content = new double[size];
for (int i = 0; i < size; i++) {
RAny v = params[i];
if (v instanceof ScalarDoubleImpl) {
content[i] = ((ScalarDoubleImpl) v).getDouble();
continue;
}
if (v instanceof ScalarIntImpl) {
content[i] = Convert.int2double(((ScalarIntImpl) v).getInt());
continue;
}
if (v instanceof ScalarLogicalImpl) {
content[i] = Convert.logical2double(((ScalarLogicalImpl) v).getLogical());
continue;
}
throw new UnexpectedResultException(Transition.GENERIC);
}
return RDouble.RDoubleFactory.getFor(content);
}
};
return new Specialized(ast, names, exprs, a);
}
if (typeTemplate instanceof RInt) {
CombineAction a = new CombineAction() {
@Override public final RAny combine(Frame frame, RAny[] params) throws UnexpectedResultException {
int size = params.length;
int[] content = new int[size];
for (int i = 0; i < size; i++) {
RAny v = params[i];
if (v instanceof ScalarIntImpl) {
content[i] = ((ScalarIntImpl) v).getInt();
continue;
}
if (v instanceof ScalarLogicalImpl) {
content[i] = Convert.logical2int(((ScalarLogicalImpl) v).getLogical());
continue;
}
throw new UnexpectedResultException(Transition.GENERIC);
}
return RInt.RIntFactory.getFor(content);
}
};
return new Specialized(ast, names, exprs, a);
}
return createTransition(ast, names, exprs, Transition.GENERIC);
}
@Override public final RAny doBuiltIn(Frame frame, RAny[] params) {
try {
return combine.combine(frame, params);
} catch (UnexpectedResultException e) {
Transition t = (Transition) e.getResult();
Specialized s = null;
switch (t) {
case SIMPLE_SCALARS:
s = createSimpleScalars(ast, argNames, argExprs, params[0]);
replace(s, "install SimpleScalars in Combine.Specialized");
return s.doBuiltIn(frame, params);
case CASTING_SCALARS:
RAny res = genericCombine(argNames, params);
s = createCastingScalars(ast, argNames, argExprs, res);
replace(s, "install CastingScalars in Combine.Specialized");
return res;
case GENERIC:
default:
replace(createGeneric(ast, argNames, argExprs), "install Generic in Combine.Specialized");
return genericCombine(argNames, params);
}
}
}
}
public static RSymbol[] collapseEmptyNames(RSymbol[] names) {
if (names == null) { return names; }
for (RSymbol s : names) {
if (s != null) { return names; }
}
return null;
}
}
| true | true | public static RAny genericCombine(RSymbol[] paramNames, RAny[] params, boolean dropNames) {
int len = 0;
boolean hasNames = (paramNames != null);
boolean hasNull = false;
boolean hasRaw = false;
boolean hasLogical = false;
boolean hasInt = false;
boolean hasList = false;
boolean hasDouble = false;
boolean hasComplex = false;
boolean hasString = false;
for (int i = 0; i < params.length; i++) { // FIXME: maybe could refactor using the code in Unlist?
RAny v = params[i];
if (v instanceof RNull) {
hasNull = true;
continue;
} else if (v instanceof RList) {
hasList = true;
} else if (v instanceof RString) {
hasString = true;
} else if (v instanceof RComplex) {
hasComplex = true;
} else if (v instanceof RDouble) {
hasDouble = true;
} else if (v instanceof RInt) {
hasInt = true;
} else if (v instanceof RLogical) {
hasLogical = true;
} else if (v instanceof RRaw) {
hasRaw = true;
} else {
throw Utils.nyi("unsupported type");
}
RArray a = (RArray) v;
len += a.size();
if (!dropNames && a.names() != null) {
hasNames = true;
}
}
int offset = 0;
RArray.Names newNames = null;
if (!dropNames && hasNames) {
RSymbol[] names = new RSymbol[len];
int j = 0;
for (int i = 0; i < params.length; i++) {
RAny v = params[i];
if (v instanceof RNull) {
continue;
}
RArray a = (RArray) v;
int asize = a.size();
RArray.Names aNamesPacked = a.names();
RSymbol[] aNames = aNamesPacked == null ? null : aNamesPacked.sequence();
if (aNames == null) {
if (paramNames == null || paramNames[i] == null) {
for (int k = 0; k < asize; k++) {
names[j++] = RSymbol.EMPTY_SYMBOL;
}
continue;
}
if (asize == 1) {
names[j++] = paramNames[i];
continue;
}
if (asize == 0) {
continue;
}
String prefix = paramNames[i].pretty();
for (int k = 0; k < asize; k++) {
String n = prefix + (k + 1);
names[j++] = RSymbol.getSymbol(n);
}
continue;
}
// aNames != null
if (paramNames == null || paramNames[i] == RSymbol.EMPTY_SYMBOL || paramNames[i] == null) {
for (int k = 0; k < asize; k++) {
names[j++] = aNames[k];
}
continue;
}
String eprefix = paramNames[i].pretty();
String prefix = eprefix + ".";
for (int k = 0; k < asize; k++) {
RSymbol ksymbol = aNames[k];
if (ksymbol == RSymbol.EMPTY_SYMBOL) {
if (asize == 1) {
names[j++] = paramNames[i];
} else {
names[j++] = RSymbol.getSymbol(eprefix + (k + 1));
}
} else {
String n = prefix + Convert.prettyNA(aNames[k].pretty());
names[j++] = RSymbol.getSymbol(n);
}
}
}
newNames = RArray.Names.create(names);
}
if (hasList) {
ListImpl res = RList.RListFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
RArray a = (RArray) v;
int asize = a.size();
if (v instanceof RList) {
RList l = (RList) v;
for (int i = 0; i < asize; i++) { // shallow copy
RAny ll = l.getRAnyRef(i);
res.set(offset + i, ll);
}
} else {
for (int i = 0; i < asize; i++) {
res.set(offset + i, a.boxedGet(i));
}
}
offset += asize;
}
return res.setNames(newNames);
}
if (hasString) {
RString res = RString.RStringFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RString ? (RString) v : v.asString(), offset);
}
return res.setNames(newNames);
}
if (hasComplex) {
RComplex res = RComplex.RComplexFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RComplex ? (RComplex) v : v.asComplex(), offset);
}
return res.setNames(newNames);
}
if (hasDouble) {
RDouble res = RDouble.RDoubleFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RDouble ? (RDouble) v : v.asDouble(), offset);
}
return res.setNames(newNames);
}
if (hasInt) {
RInt res = RInt.RIntFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RInt ? (RInt) v : v.asInt(), offset);
}
return res.setNames(newNames);
}
if (hasLogical) {
RLogical res = RLogical.RLogicalFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RLogical ? (RLogical) v : v.asLogical(), offset);
}
return res.setNames(newNames);
}
if (hasRaw) {
RRaw res = RRaw.RRawFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RRaw ? (RRaw) v : v.asRaw(), offset);
}
return res.setNames(newNames);
}
if (hasNull) { return RNull.getNull(); }
throw Utils.nyi("Unreacheable");
}
| public static RAny genericCombine(RSymbol[] paramNames, RAny[] params, boolean dropNames) {
int len = 0;
boolean hasNames = (paramNames != null);
boolean hasNull = false;
boolean hasRaw = false;
boolean hasLogical = false;
boolean hasInt = false;
boolean hasList = false;
boolean hasDouble = false;
boolean hasComplex = false;
boolean hasString = false;
for (int i = 0; i < params.length; i++) { // FIXME: maybe could refactor using the code in Unlist?
RAny v = params[i];
if (v instanceof RNull) {
hasNull = true;
continue;
} else if (v instanceof RList) {
hasList = true;
} else if (v instanceof RString) {
hasString = true;
} else if (v instanceof RComplex) {
hasComplex = true;
} else if (v instanceof RDouble) {
hasDouble = true;
} else if (v instanceof RInt) {
hasInt = true;
} else if (v instanceof RLogical) {
hasLogical = true;
} else if (v instanceof RRaw) {
hasRaw = true;
} else {
throw Utils.nyi("unsupported type");
}
RArray a = (RArray) v;
len += a.size();
if (!dropNames && a.names() != null) {
hasNames = true;
}
}
int offset = 0;
RArray.Names newNames = null;
if (!dropNames && hasNames) {
RSymbol[] names = new RSymbol[len];
int j = 0;
for (int i = 0; i < params.length; i++) {
RAny v = params[i];
if (v instanceof RNull) {
continue;
}
RArray a = (RArray) v;
int asize = a.size();
RArray.Names aNamesPacked = a.names();
RSymbol[] aNames = aNamesPacked == null ? null : aNamesPacked.sequence();
if (aNames == null) {
if (paramNames == null || paramNames[i] == null) {
for (int k = 0; k < asize; k++) {
names[j++] = RSymbol.EMPTY_SYMBOL;
}
continue;
}
if (asize == 1) {
names[j++] = paramNames[i];
continue;
}
if (asize == 0) {
continue;
}
String prefix = paramNames[i].pretty();
for (int k = 0; k < asize; k++) {
String n = prefix + (k + 1);
names[j++] = RSymbol.getSymbol(n);
}
continue;
}
// aNames != null
if (paramNames == null || paramNames[i] == RSymbol.EMPTY_SYMBOL || paramNames[i] == null) {
for (int k = 0; k < asize; k++) {
names[j++] = aNames[k];
}
continue;
}
String eprefix = paramNames[i].pretty();
String prefix = eprefix + ".";
for (int k = 0; k < asize; k++) {
RSymbol ksymbol = aNames[k];
if (ksymbol == RSymbol.EMPTY_SYMBOL) {
if (asize == 1) {
names[j++] = paramNames[i];
} else {
names[j++] = RSymbol.getSymbol(eprefix + (k + 1));
}
} else {
String n = prefix + Convert.prettyNA(ksymbol.pretty());
names[j++] = RSymbol.getSymbol(n);
}
}
}
newNames = RArray.Names.create(names);
}
if (hasList) {
ListImpl res = RList.RListFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
RArray a = (RArray) v;
int asize = a.size();
if (v instanceof RList) {
RList l = (RList) v;
for (int i = 0; i < asize; i++) { // shallow copy
RAny ll = l.getRAnyRef(i);
res.set(offset + i, ll);
}
} else {
for (int i = 0; i < asize; i++) {
res.set(offset + i, a.boxedGet(i));
}
}
offset += asize;
}
return res.setNames(newNames);
}
if (hasString) {
RString res = RString.RStringFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RString ? (RString) v : v.asString(), offset);
}
return res.setNames(newNames);
}
if (hasComplex) {
RComplex res = RComplex.RComplexFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RComplex ? (RComplex) v : v.asComplex(), offset);
}
return res.setNames(newNames);
}
if (hasDouble) {
RDouble res = RDouble.RDoubleFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RDouble ? (RDouble) v : v.asDouble(), offset);
}
return res.setNames(newNames);
}
if (hasInt) {
RInt res = RInt.RIntFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RInt ? (RInt) v : v.asInt(), offset);
}
return res.setNames(newNames);
}
if (hasLogical) {
RLogical res = RLogical.RLogicalFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RLogical ? (RLogical) v : v.asLogical(), offset);
}
return res.setNames(newNames);
}
if (hasRaw) {
RRaw res = RRaw.RRawFactory.getUninitializedArray(len);
for (RAny v : params) {
if (v instanceof RNull) {
continue;
}
offset = fillIn(res, v instanceof RRaw ? (RRaw) v : v.asRaw(), offset);
}
return res.setNames(newNames);
}
if (hasNull) { return RNull.getNull(); }
throw Utils.nyi("Unreacheable");
}
|
diff --git a/src/org/apache/fop/fo/flow/Table.java b/src/org/apache/fop/fo/flow/Table.java
index 7ab0f488f..99f69e5f2 100644
--- a/src/org/apache/fop/fo/flow/Table.java
+++ b/src/org/apache/fop/fo/flow/Table.java
@@ -1,411 +1,412 @@
/*
* -- $Id$ --
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
// FOP
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.*;
import org.apache.fop.datatypes.*;
import org.apache.fop.apps.FOPException;
// Java
import java.util.Vector;
public class Table extends FObj {
public static class Maker extends FObj.Maker {
public FObj make(FObj parent,
PropertyList propertyList) throws FOPException {
return new Table(parent, propertyList);
}
}
public static FObj.Maker maker() {
return new Table.Maker();
}
int breakBefore;
int breakAfter;
int spaceBefore;
int spaceAfter;
ColorType backgroundColor;
int width;
int height;
String id;
TableHeader tableHeader = null;
TableFooter tableFooter = null;
boolean omitHeaderAtBreak = false;
boolean omitFooterAtBreak = false;
Vector columns = new Vector();
int currentColumnNumber = 0;
int bodyCount = 0;
AreaContainer areaContainer;
public Table(FObj parent, PropertyList propertyList) {
super(parent, propertyList);
this.name = "fo:table";
}
public Status layout(Area area) throws FOPException {
if (this.marker == BREAK_AFTER) {
return new Status(Status.OK);
}
if (this.marker == START) {
// Common Accessibility Properties
AccessibilityProps mAccProps = propMgr.getAccessibilityProps();
// Common Aural Properties
AuralProps mAurProps = propMgr.getAuralProps();
// Common Border, Padding, and Background Properties
BorderAndPadding bap = propMgr.getBorderAndPadding();
BackgroundProps bProps = propMgr.getBackgroundProps();
// Common Margin Properties-Block
MarginProps mProps = propMgr.getMarginProps();
// Common Relative Position Properties
RelativePositionProps mRelProps = propMgr.getRelativePositionProps();
// this.properties.get("block-progression-dimension");
// this.properties.get("border-after-precendence");
// this.properties.get("border-before-precedence");
// this.properties.get("border-collapse");
// this.properties.get("border-end-precendence");
// this.properties.get("border-separation");
// this.properties.get("border-start-precendence");
// this.properties.get("break-after");
// this.properties.get("break-before");
// this.properties.get("id");
// this.properties.get("inline-progression-dimension");
// this.properties.get("height");
// this.properties.get("keep-together");
// this.properties.get("keep-with-next");
// this.properties.get("keep-with-previous");
// this.properties.get("table-layout");
// this.properties.get("table-omit-footer-at-break");
// this.properties.get("table-omit-header-at-break");
// this.properties.get("width");
// this.properties.get("writing-mode");
this.breakBefore = this.properties.get("break-before").getEnum();
this.breakAfter = this.properties.get("break-after").getEnum();
this.spaceBefore =
this.properties.get("space-before.optimum").getLength().mvalue();
this.spaceAfter =
this.properties.get("space-after.optimum").getLength().mvalue();
this.backgroundColor =
this.properties.get("background-color").getColorType();
this.width = this.properties.get("width").getLength().mvalue();
this.height = this.properties.get("height").getLength().mvalue();
this.id = this.properties.get("id").getString();
this.omitHeaderAtBreak =
this.properties.get("table-omit-header-at-break").getEnum()
== TableOmitHeaderAtBreak.TRUE;
this.omitFooterAtBreak =
this.properties.get("table-omit-footer-at-break").getEnum()
== TableOmitFooterAtBreak.TRUE;
if (area instanceof BlockArea) {
area.end();
}
if (this.areaContainer
== null) { // check if anything was previously laid out
area.getIDReferences().createID(id);
}
this.marker = 0;
if (breakBefore == BreakBefore.PAGE) {
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakBefore == BreakBefore.ODD_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakBefore == BreakBefore.EVEN_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
}
if ((spaceBefore != 0) && (this.marker == 0)) {
area.addDisplaySpace(spaceBefore);
}
if (marker == 0 && areaContainer == null) {
// configure id
area.getIDReferences().configureID(id, area);
}
int spaceLeft = area.spaceLeft();
this.areaContainer =
new AreaContainer(propMgr.getFontState(area.getFontInfo()), 0, 0,
area.getAllocationWidth(), area.spaceLeft(),
Position.STATIC);
areaContainer.foCreator = this; // G Seshadri
areaContainer.setPage(area.getPage());
areaContainer.setBackgroundColor(backgroundColor);
areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
areaContainer.start();
areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
areaContainer.setIDReferences(area.getIDReferences());
// added by Eric Schaeffer
currentColumnNumber = 0;
int offset = 0;
boolean addedHeader = false;
boolean addedFooter = false;
int numChildren = this.children.size();
for (int i = 0; i < numChildren; i++) {
FONode fo = (FONode)children.elementAt(i);
if (fo instanceof TableColumn) {
TableColumn c = (TableColumn)fo;
c.doSetup(areaContainer);
int numColumnsRepeated = c.getNumColumnsRepeated();
// int currentColumnNumber = c.getColumnNumber();
for (int j = 0; j < numColumnsRepeated; j++) {
currentColumnNumber++;
if (currentColumnNumber > columns.size()) {
columns.setSize(currentColumnNumber);
}
columns.setElementAt(c, currentColumnNumber - 1);
c.setColumnOffset(offset);
c.layout(areaContainer);
offset += c.getColumnWidth();
}
}
}
areaContainer.setAllocationWidth(offset);
for (int i = this.marker; i < numChildren; i++) {
FONode fo = (FONode)children.elementAt(i);
if (fo instanceof TableHeader) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableHeader = (TableHeader)fo;
tableHeader.setColumns(columns);
} else if (fo instanceof TableFooter) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableFooter = (TableFooter)fo;
tableFooter.setColumns(columns);
} else if (fo instanceof TableBody) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
Status status;
if (tableHeader != null &&!addedHeader) {
if ((status =
tableHeader.layout(areaContainer)).isIncomplete()) {
+ tableHeader.resetMarker();
return new Status(Status.AREA_FULL_NONE);
}
addedHeader = true;
tableHeader.resetMarker();
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
}
if (tableFooter != null &&!this.omitFooterAtBreak
&&!addedFooter) {
if ((status =
tableFooter.layout(areaContainer)).isIncomplete()) {
return new Status(Status.AREA_FULL_NONE);
}
addedFooter = true;
tableFooter.resetMarker();
}
fo.setWidows(widows);
fo.setOrphans(orphans);
((TableBody)fo).setColumns(columns);
if ((status = fo.layout(areaContainer)).isIncomplete()) {
this.marker = i;
if (bodyCount == 0
&& status.getCode() == Status.AREA_FULL_NONE) {
if (tableHeader != null)
tableHeader.removeLayout(areaContainer);
if (tableFooter != null)
tableFooter.removeLayout(areaContainer);
resetMarker();
// status = new Status(Status.AREA_FULL_SOME);
}
// areaContainer.end();
if (areaContainer.getContentHeight() > 0) {
area.addChild(areaContainer);
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (this.omitHeaderAtBreak) {
// remove header, no longer needed
tableHeader = null;
}
if (tableFooter != null &&!this.omitFooterAtBreak) {
// move footer to bottom of area and move up body
((TableBody)fo).setYPosition(tableFooter.getYPosition());
tableFooter.setYPosition(tableFooter.getYPosition()
+ ((TableBody)fo).getHeight());
}
setupColumnHeights();
status = new Status(Status.AREA_FULL_SOME);
}
return status;
} else {
bodyCount++;
}
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
if (tableFooter != null &&!this.omitFooterAtBreak) {
// move footer to bottom of area and move up body
// space before and after footer will make this wrong
((TableBody)fo).setYPosition(tableFooter.getYPosition());
tableFooter.setYPosition(tableFooter.getYPosition()
+ ((TableBody)fo).getHeight());
}
}
}
if (tableFooter != null && this.omitFooterAtBreak) {
if (tableFooter.layout(areaContainer).isIncomplete()) {
// this is a problem since we need to remove a row
// from the last table body and place it on the
// next page so that it can have a footer at
// the end of the table.
log.warn("footer could not fit on page, moving last body row to next page");
area.addChild(areaContainer);
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (this.omitHeaderAtBreak) {
// remove header, no longer needed
tableHeader = null;
}
tableFooter.removeLayout(areaContainer);
tableFooter.resetMarker();
return new Status(Status.AREA_FULL_SOME);
}
}
if (height != 0)
areaContainer.setHeight(height);
setupColumnHeights();
areaContainer.end();
area.addChild(areaContainer);
/* should this be combined into above? */
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (spaceAfter != 0) {
area.addDisplaySpace(spaceAfter);
}
if (area instanceof BlockArea) {
area.start();
}
if (breakAfter == BreakAfter.PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakAfter == BreakAfter.ODD_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakAfter == BreakAfter.EVEN_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
return new Status(Status.OK);
}
protected void setupColumnHeights() {
int numChildren = this.children.size();
for (int i = 0; i < numChildren; i++) {
FONode fo = (FONode)children.elementAt(i);
if (fo instanceof TableColumn) {
((TableColumn)fo).setHeight(areaContainer.getContentHeight());
}
}
}
public int getAreaHeight() {
return areaContainer.getHeight();
}
/**
* Return the content width of the boxes generated by this table FO.
*/
public int getContentWidth() {
if (areaContainer != null)
return areaContainer.getContentWidth(); // getAllocationWidth()??
else
return 0; // not laid out yet
}
// /**
// * Return the last TableRow in the header or null if no header or
// * no header in non-first areas.
// * @param bForInitialArea If true, return the header row for the
// * initial table area, else for a continuation area, taking into
// * account the omit-header-at-break property.
// */
// TableRow getLastHeaderRow(boolean bForInitialArea) {
// // Check omit...
// if ((tableHeader != null) &&
// (bForInitialArea || omitHeaderAtBreak == false)) {
// return tableHeader.children.lastElement();
// }
// return null;
// }
// /**
// * Return the first TableRow in the footer or null if no footer or
// * no footer in non-last areas.
// * @param bForFinalArea If true, return the footer row for the
// * final table area, else for a non-final area, taking into
// * account the omit-footer-at-break property.
// */
// TableRow getLastFooterRow(boolean bForFinalArea) {
// if ((tableFooter != null) &&
// (bForFinalArea || omitFooterAtBreak == false)) {
// return tableFooter.children.firstElement();
// }
// return null;
// }
// /**
// * Return border information for the side (start/end) of the column
// * whose number is iColNumber (first column = 1).
// * ATTENTION: for now we assume columns are in order in the array!
// */
// BorderInfo getColumnBorder(BorderInfo.Side side, int iColNumber) {
// TableColumn col = (TableColumn)columns.elementAt(iColNumber);
// return col.getBorderInfo(side);
// }
}
| true | true | public Status layout(Area area) throws FOPException {
if (this.marker == BREAK_AFTER) {
return new Status(Status.OK);
}
if (this.marker == START) {
// Common Accessibility Properties
AccessibilityProps mAccProps = propMgr.getAccessibilityProps();
// Common Aural Properties
AuralProps mAurProps = propMgr.getAuralProps();
// Common Border, Padding, and Background Properties
BorderAndPadding bap = propMgr.getBorderAndPadding();
BackgroundProps bProps = propMgr.getBackgroundProps();
// Common Margin Properties-Block
MarginProps mProps = propMgr.getMarginProps();
// Common Relative Position Properties
RelativePositionProps mRelProps = propMgr.getRelativePositionProps();
// this.properties.get("block-progression-dimension");
// this.properties.get("border-after-precendence");
// this.properties.get("border-before-precedence");
// this.properties.get("border-collapse");
// this.properties.get("border-end-precendence");
// this.properties.get("border-separation");
// this.properties.get("border-start-precendence");
// this.properties.get("break-after");
// this.properties.get("break-before");
// this.properties.get("id");
// this.properties.get("inline-progression-dimension");
// this.properties.get("height");
// this.properties.get("keep-together");
// this.properties.get("keep-with-next");
// this.properties.get("keep-with-previous");
// this.properties.get("table-layout");
// this.properties.get("table-omit-footer-at-break");
// this.properties.get("table-omit-header-at-break");
// this.properties.get("width");
// this.properties.get("writing-mode");
this.breakBefore = this.properties.get("break-before").getEnum();
this.breakAfter = this.properties.get("break-after").getEnum();
this.spaceBefore =
this.properties.get("space-before.optimum").getLength().mvalue();
this.spaceAfter =
this.properties.get("space-after.optimum").getLength().mvalue();
this.backgroundColor =
this.properties.get("background-color").getColorType();
this.width = this.properties.get("width").getLength().mvalue();
this.height = this.properties.get("height").getLength().mvalue();
this.id = this.properties.get("id").getString();
this.omitHeaderAtBreak =
this.properties.get("table-omit-header-at-break").getEnum()
== TableOmitHeaderAtBreak.TRUE;
this.omitFooterAtBreak =
this.properties.get("table-omit-footer-at-break").getEnum()
== TableOmitFooterAtBreak.TRUE;
if (area instanceof BlockArea) {
area.end();
}
if (this.areaContainer
== null) { // check if anything was previously laid out
area.getIDReferences().createID(id);
}
this.marker = 0;
if (breakBefore == BreakBefore.PAGE) {
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakBefore == BreakBefore.ODD_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakBefore == BreakBefore.EVEN_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
}
if ((spaceBefore != 0) && (this.marker == 0)) {
area.addDisplaySpace(spaceBefore);
}
if (marker == 0 && areaContainer == null) {
// configure id
area.getIDReferences().configureID(id, area);
}
int spaceLeft = area.spaceLeft();
this.areaContainer =
new AreaContainer(propMgr.getFontState(area.getFontInfo()), 0, 0,
area.getAllocationWidth(), area.spaceLeft(),
Position.STATIC);
areaContainer.foCreator = this; // G Seshadri
areaContainer.setPage(area.getPage());
areaContainer.setBackgroundColor(backgroundColor);
areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
areaContainer.start();
areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
areaContainer.setIDReferences(area.getIDReferences());
// added by Eric Schaeffer
currentColumnNumber = 0;
int offset = 0;
boolean addedHeader = false;
boolean addedFooter = false;
int numChildren = this.children.size();
for (int i = 0; i < numChildren; i++) {
FONode fo = (FONode)children.elementAt(i);
if (fo instanceof TableColumn) {
TableColumn c = (TableColumn)fo;
c.doSetup(areaContainer);
int numColumnsRepeated = c.getNumColumnsRepeated();
// int currentColumnNumber = c.getColumnNumber();
for (int j = 0; j < numColumnsRepeated; j++) {
currentColumnNumber++;
if (currentColumnNumber > columns.size()) {
columns.setSize(currentColumnNumber);
}
columns.setElementAt(c, currentColumnNumber - 1);
c.setColumnOffset(offset);
c.layout(areaContainer);
offset += c.getColumnWidth();
}
}
}
areaContainer.setAllocationWidth(offset);
for (int i = this.marker; i < numChildren; i++) {
FONode fo = (FONode)children.elementAt(i);
if (fo instanceof TableHeader) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableHeader = (TableHeader)fo;
tableHeader.setColumns(columns);
} else if (fo instanceof TableFooter) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableFooter = (TableFooter)fo;
tableFooter.setColumns(columns);
} else if (fo instanceof TableBody) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
Status status;
if (tableHeader != null &&!addedHeader) {
if ((status =
tableHeader.layout(areaContainer)).isIncomplete()) {
return new Status(Status.AREA_FULL_NONE);
}
addedHeader = true;
tableHeader.resetMarker();
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
}
if (tableFooter != null &&!this.omitFooterAtBreak
&&!addedFooter) {
if ((status =
tableFooter.layout(areaContainer)).isIncomplete()) {
return new Status(Status.AREA_FULL_NONE);
}
addedFooter = true;
tableFooter.resetMarker();
}
fo.setWidows(widows);
fo.setOrphans(orphans);
((TableBody)fo).setColumns(columns);
if ((status = fo.layout(areaContainer)).isIncomplete()) {
this.marker = i;
if (bodyCount == 0
&& status.getCode() == Status.AREA_FULL_NONE) {
if (tableHeader != null)
tableHeader.removeLayout(areaContainer);
if (tableFooter != null)
tableFooter.removeLayout(areaContainer);
resetMarker();
// status = new Status(Status.AREA_FULL_SOME);
}
// areaContainer.end();
if (areaContainer.getContentHeight() > 0) {
area.addChild(areaContainer);
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (this.omitHeaderAtBreak) {
// remove header, no longer needed
tableHeader = null;
}
if (tableFooter != null &&!this.omitFooterAtBreak) {
// move footer to bottom of area and move up body
((TableBody)fo).setYPosition(tableFooter.getYPosition());
tableFooter.setYPosition(tableFooter.getYPosition()
+ ((TableBody)fo).getHeight());
}
setupColumnHeights();
status = new Status(Status.AREA_FULL_SOME);
}
return status;
} else {
bodyCount++;
}
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
if (tableFooter != null &&!this.omitFooterAtBreak) {
// move footer to bottom of area and move up body
// space before and after footer will make this wrong
((TableBody)fo).setYPosition(tableFooter.getYPosition());
tableFooter.setYPosition(tableFooter.getYPosition()
+ ((TableBody)fo).getHeight());
}
}
}
if (tableFooter != null && this.omitFooterAtBreak) {
if (tableFooter.layout(areaContainer).isIncomplete()) {
// this is a problem since we need to remove a row
// from the last table body and place it on the
// next page so that it can have a footer at
// the end of the table.
log.warn("footer could not fit on page, moving last body row to next page");
area.addChild(areaContainer);
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (this.omitHeaderAtBreak) {
// remove header, no longer needed
tableHeader = null;
}
tableFooter.removeLayout(areaContainer);
tableFooter.resetMarker();
return new Status(Status.AREA_FULL_SOME);
}
}
if (height != 0)
areaContainer.setHeight(height);
setupColumnHeights();
areaContainer.end();
area.addChild(areaContainer);
/* should this be combined into above? */
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (spaceAfter != 0) {
area.addDisplaySpace(spaceAfter);
}
if (area instanceof BlockArea) {
area.start();
}
if (breakAfter == BreakAfter.PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakAfter == BreakAfter.ODD_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakAfter == BreakAfter.EVEN_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
return new Status(Status.OK);
}
| public Status layout(Area area) throws FOPException {
if (this.marker == BREAK_AFTER) {
return new Status(Status.OK);
}
if (this.marker == START) {
// Common Accessibility Properties
AccessibilityProps mAccProps = propMgr.getAccessibilityProps();
// Common Aural Properties
AuralProps mAurProps = propMgr.getAuralProps();
// Common Border, Padding, and Background Properties
BorderAndPadding bap = propMgr.getBorderAndPadding();
BackgroundProps bProps = propMgr.getBackgroundProps();
// Common Margin Properties-Block
MarginProps mProps = propMgr.getMarginProps();
// Common Relative Position Properties
RelativePositionProps mRelProps = propMgr.getRelativePositionProps();
// this.properties.get("block-progression-dimension");
// this.properties.get("border-after-precendence");
// this.properties.get("border-before-precedence");
// this.properties.get("border-collapse");
// this.properties.get("border-end-precendence");
// this.properties.get("border-separation");
// this.properties.get("border-start-precendence");
// this.properties.get("break-after");
// this.properties.get("break-before");
// this.properties.get("id");
// this.properties.get("inline-progression-dimension");
// this.properties.get("height");
// this.properties.get("keep-together");
// this.properties.get("keep-with-next");
// this.properties.get("keep-with-previous");
// this.properties.get("table-layout");
// this.properties.get("table-omit-footer-at-break");
// this.properties.get("table-omit-header-at-break");
// this.properties.get("width");
// this.properties.get("writing-mode");
this.breakBefore = this.properties.get("break-before").getEnum();
this.breakAfter = this.properties.get("break-after").getEnum();
this.spaceBefore =
this.properties.get("space-before.optimum").getLength().mvalue();
this.spaceAfter =
this.properties.get("space-after.optimum").getLength().mvalue();
this.backgroundColor =
this.properties.get("background-color").getColorType();
this.width = this.properties.get("width").getLength().mvalue();
this.height = this.properties.get("height").getLength().mvalue();
this.id = this.properties.get("id").getString();
this.omitHeaderAtBreak =
this.properties.get("table-omit-header-at-break").getEnum()
== TableOmitHeaderAtBreak.TRUE;
this.omitFooterAtBreak =
this.properties.get("table-omit-footer-at-break").getEnum()
== TableOmitFooterAtBreak.TRUE;
if (area instanceof BlockArea) {
area.end();
}
if (this.areaContainer
== null) { // check if anything was previously laid out
area.getIDReferences().createID(id);
}
this.marker = 0;
if (breakBefore == BreakBefore.PAGE) {
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakBefore == BreakBefore.ODD_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakBefore == BreakBefore.EVEN_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
}
if ((spaceBefore != 0) && (this.marker == 0)) {
area.addDisplaySpace(spaceBefore);
}
if (marker == 0 && areaContainer == null) {
// configure id
area.getIDReferences().configureID(id, area);
}
int spaceLeft = area.spaceLeft();
this.areaContainer =
new AreaContainer(propMgr.getFontState(area.getFontInfo()), 0, 0,
area.getAllocationWidth(), area.spaceLeft(),
Position.STATIC);
areaContainer.foCreator = this; // G Seshadri
areaContainer.setPage(area.getPage());
areaContainer.setBackgroundColor(backgroundColor);
areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
areaContainer.start();
areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
areaContainer.setIDReferences(area.getIDReferences());
// added by Eric Schaeffer
currentColumnNumber = 0;
int offset = 0;
boolean addedHeader = false;
boolean addedFooter = false;
int numChildren = this.children.size();
for (int i = 0; i < numChildren; i++) {
FONode fo = (FONode)children.elementAt(i);
if (fo instanceof TableColumn) {
TableColumn c = (TableColumn)fo;
c.doSetup(areaContainer);
int numColumnsRepeated = c.getNumColumnsRepeated();
// int currentColumnNumber = c.getColumnNumber();
for (int j = 0; j < numColumnsRepeated; j++) {
currentColumnNumber++;
if (currentColumnNumber > columns.size()) {
columns.setSize(currentColumnNumber);
}
columns.setElementAt(c, currentColumnNumber - 1);
c.setColumnOffset(offset);
c.layout(areaContainer);
offset += c.getColumnWidth();
}
}
}
areaContainer.setAllocationWidth(offset);
for (int i = this.marker; i < numChildren; i++) {
FONode fo = (FONode)children.elementAt(i);
if (fo instanceof TableHeader) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableHeader = (TableHeader)fo;
tableHeader.setColumns(columns);
} else if (fo instanceof TableFooter) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableFooter = (TableFooter)fo;
tableFooter.setColumns(columns);
} else if (fo instanceof TableBody) {
if (columns.size() == 0) {
log.warn("current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
Status status;
if (tableHeader != null &&!addedHeader) {
if ((status =
tableHeader.layout(areaContainer)).isIncomplete()) {
tableHeader.resetMarker();
return new Status(Status.AREA_FULL_NONE);
}
addedHeader = true;
tableHeader.resetMarker();
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
}
if (tableFooter != null &&!this.omitFooterAtBreak
&&!addedFooter) {
if ((status =
tableFooter.layout(areaContainer)).isIncomplete()) {
return new Status(Status.AREA_FULL_NONE);
}
addedFooter = true;
tableFooter.resetMarker();
}
fo.setWidows(widows);
fo.setOrphans(orphans);
((TableBody)fo).setColumns(columns);
if ((status = fo.layout(areaContainer)).isIncomplete()) {
this.marker = i;
if (bodyCount == 0
&& status.getCode() == Status.AREA_FULL_NONE) {
if (tableHeader != null)
tableHeader.removeLayout(areaContainer);
if (tableFooter != null)
tableFooter.removeLayout(areaContainer);
resetMarker();
// status = new Status(Status.AREA_FULL_SOME);
}
// areaContainer.end();
if (areaContainer.getContentHeight() > 0) {
area.addChild(areaContainer);
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (this.omitHeaderAtBreak) {
// remove header, no longer needed
tableHeader = null;
}
if (tableFooter != null &&!this.omitFooterAtBreak) {
// move footer to bottom of area and move up body
((TableBody)fo).setYPosition(tableFooter.getYPosition());
tableFooter.setYPosition(tableFooter.getYPosition()
+ ((TableBody)fo).getHeight());
}
setupColumnHeights();
status = new Status(Status.AREA_FULL_SOME);
}
return status;
} else {
bodyCount++;
}
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
if (tableFooter != null &&!this.omitFooterAtBreak) {
// move footer to bottom of area and move up body
// space before and after footer will make this wrong
((TableBody)fo).setYPosition(tableFooter.getYPosition());
tableFooter.setYPosition(tableFooter.getYPosition()
+ ((TableBody)fo).getHeight());
}
}
}
if (tableFooter != null && this.omitFooterAtBreak) {
if (tableFooter.layout(areaContainer).isIncomplete()) {
// this is a problem since we need to remove a row
// from the last table body and place it on the
// next page so that it can have a footer at
// the end of the table.
log.warn("footer could not fit on page, moving last body row to next page");
area.addChild(areaContainer);
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (this.omitHeaderAtBreak) {
// remove header, no longer needed
tableHeader = null;
}
tableFooter.removeLayout(areaContainer);
tableFooter.resetMarker();
return new Status(Status.AREA_FULL_SOME);
}
}
if (height != 0)
areaContainer.setHeight(height);
setupColumnHeights();
areaContainer.end();
area.addChild(areaContainer);
/* should this be combined into above? */
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (spaceAfter != 0) {
area.addDisplaySpace(spaceAfter);
}
if (area instanceof BlockArea) {
area.start();
}
if (breakAfter == BreakAfter.PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakAfter == BreakAfter.ODD_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakAfter == BreakAfter.EVEN_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
return new Status(Status.OK);
}
|
diff --git a/logic/slave/src/main/java/no/difi/datahotel/logic/slave/ChunkEJB.java b/logic/slave/src/main/java/no/difi/datahotel/logic/slave/ChunkEJB.java
index dbc398a..e221140 100644
--- a/logic/slave/src/main/java/no/difi/datahotel/logic/slave/ChunkEJB.java
+++ b/logic/slave/src/main/java/no/difi/datahotel/logic/slave/ChunkEJB.java
@@ -1,117 +1,116 @@
package no.difi.datahotel.logic.slave;
import static no.difi.datahotel.util.shared.Filesystem.FOLDER_CHUNK;
import static no.difi.datahotel.util.shared.Filesystem.FOLDER_SHARED;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Singleton;
import no.difi.datahotel.util.bridge.Metadata;
import no.difi.datahotel.util.csv.CSVParser;
import no.difi.datahotel.util.csv.CSVParserFactory;
import no.difi.datahotel.util.csv.CSVWriter;
import no.difi.datahotel.util.shared.Filesystem;
import no.difi.datahotel.util.shared.Timestamp;
@Singleton
public class ChunkEJB {
private Map<String, Long> posts = new HashMap<String, Long>();
private Map<String, Long> pages = new HashMap<String, Long>();
private int size = 100;
public File getFullDataset(Metadata metadata) {
return Filesystem.getFileF(FOLDER_SHARED, metadata.getLocation(), Filesystem.DATASET_DATA);
}
public void update(Metadata metadata) {
Logger logger = metadata.getLogger();
File tsfile = Filesystem.getFileF(FOLDER_CHUNK, metadata.getLocation(), "timestamp");
if (metadata.getUpdated() == Timestamp.getTimestamp(tsfile)) {
logger.info("Chunk up to date.");
return;
}
logger.info("Building chunk.");
try {
String locationTmp = metadata.getLocation() + "-tmp." + System.currentTimeMillis();
CSVParser parser = CSVParserFactory.getCSVParser(getFullDataset(metadata));
CSVWriter writer = null;
long number = 0, counter = 0;
while (parser.hasNext()) {
counter++;
if (counter % size == 1) {
number++;
String filename = "dataset-" + number + ".csv";
writer = new CSVWriter(Filesystem.getFileF(FOLDER_CHUNK, locationTmp, filename));
writer.writeHeader(parser.getHeaders());
}
writer.write(parser.getNextLineArray());
if (counter % size == 0) {
writer.close();
writer = null;
}
}
if (writer != null)
writer.close();
File goal = Filesystem.getFolderPathF(FOLDER_CHUNK, metadata.getLocation());
- if (goal.exists())
- Filesystem.delete(FOLDER_CHUNK, metadata.getLocation());
+ Filesystem.delete(FOLDER_CHUNK, metadata.getLocation());
Filesystem.getFolderPathF(FOLDER_CHUNK, locationTmp).renameTo(goal);
posts.put(metadata.getLocation(), counter);
pages.put(metadata.getLocation(), number);
Timestamp.setTimestamp(tsfile, metadata.getUpdated());
} catch (Exception e) {
// TODO Start sending exceptions.
logger.log(Level.WARNING, e.getMessage(), e);
}
}
public ArrayList<Map<String, String>> get(Metadata metadata, int number) {
Logger logger = metadata.getLogger();
File source = Filesystem.getFileF(FOLDER_CHUNK, metadata.getLocation(), "dataset-" + number + ".csv");
ArrayList<Map<String, String>> result = new ArrayList<Map<String, String>>();
try {
CSVParser parser = CSVParserFactory.getCSVParser(source);
while (parser.hasNext())
result.add(parser.getNextLine());
parser.close();
return result;
} catch (Exception e) {
logger.log(Level.WARNING, e.getMessage());
}
return null;
}
public Long getPosts(String location) {
return posts.containsKey(location) ? posts.get(location) : 0;
}
public Long getPages(String location) {
return pages.containsKey(location) ? pages.get(location) : 0;
}
}
| true | true | public void update(Metadata metadata) {
Logger logger = metadata.getLogger();
File tsfile = Filesystem.getFileF(FOLDER_CHUNK, metadata.getLocation(), "timestamp");
if (metadata.getUpdated() == Timestamp.getTimestamp(tsfile)) {
logger.info("Chunk up to date.");
return;
}
logger.info("Building chunk.");
try {
String locationTmp = metadata.getLocation() + "-tmp." + System.currentTimeMillis();
CSVParser parser = CSVParserFactory.getCSVParser(getFullDataset(metadata));
CSVWriter writer = null;
long number = 0, counter = 0;
while (parser.hasNext()) {
counter++;
if (counter % size == 1) {
number++;
String filename = "dataset-" + number + ".csv";
writer = new CSVWriter(Filesystem.getFileF(FOLDER_CHUNK, locationTmp, filename));
writer.writeHeader(parser.getHeaders());
}
writer.write(parser.getNextLineArray());
if (counter % size == 0) {
writer.close();
writer = null;
}
}
if (writer != null)
writer.close();
File goal = Filesystem.getFolderPathF(FOLDER_CHUNK, metadata.getLocation());
if (goal.exists())
Filesystem.delete(FOLDER_CHUNK, metadata.getLocation());
Filesystem.getFolderPathF(FOLDER_CHUNK, locationTmp).renameTo(goal);
posts.put(metadata.getLocation(), counter);
pages.put(metadata.getLocation(), number);
Timestamp.setTimestamp(tsfile, metadata.getUpdated());
} catch (Exception e) {
// TODO Start sending exceptions.
logger.log(Level.WARNING, e.getMessage(), e);
}
}
| public void update(Metadata metadata) {
Logger logger = metadata.getLogger();
File tsfile = Filesystem.getFileF(FOLDER_CHUNK, metadata.getLocation(), "timestamp");
if (metadata.getUpdated() == Timestamp.getTimestamp(tsfile)) {
logger.info("Chunk up to date.");
return;
}
logger.info("Building chunk.");
try {
String locationTmp = metadata.getLocation() + "-tmp." + System.currentTimeMillis();
CSVParser parser = CSVParserFactory.getCSVParser(getFullDataset(metadata));
CSVWriter writer = null;
long number = 0, counter = 0;
while (parser.hasNext()) {
counter++;
if (counter % size == 1) {
number++;
String filename = "dataset-" + number + ".csv";
writer = new CSVWriter(Filesystem.getFileF(FOLDER_CHUNK, locationTmp, filename));
writer.writeHeader(parser.getHeaders());
}
writer.write(parser.getNextLineArray());
if (counter % size == 0) {
writer.close();
writer = null;
}
}
if (writer != null)
writer.close();
File goal = Filesystem.getFolderPathF(FOLDER_CHUNK, metadata.getLocation());
Filesystem.delete(FOLDER_CHUNK, metadata.getLocation());
Filesystem.getFolderPathF(FOLDER_CHUNK, locationTmp).renameTo(goal);
posts.put(metadata.getLocation(), counter);
pages.put(metadata.getLocation(), number);
Timestamp.setTimestamp(tsfile, metadata.getUpdated());
} catch (Exception e) {
// TODO Start sending exceptions.
logger.log(Level.WARNING, e.getMessage(), e);
}
}
|
diff --git a/remoting/src/test/java/hudson/remoting/DummyClassLoaderTest.java b/remoting/src/test/java/hudson/remoting/DummyClassLoaderTest.java
index 3daa2ab1c..930ab6f6f 100644
--- a/remoting/src/test/java/hudson/remoting/DummyClassLoaderTest.java
+++ b/remoting/src/test/java/hudson/remoting/DummyClassLoaderTest.java
@@ -1,16 +1,16 @@
package hudson.remoting;
import junit.framework.TestCase;
/**
* @author Kohsuke Kawaguchi
*/
public class DummyClassLoaderTest extends TestCase {
public void testLoad() throws Throwable {
DummyClassLoader cl = new DummyClassLoader(this.getClass().getClassLoader());
Callable c = (Callable) cl.loadClass("hudson.remoting.test.TestCallable").newInstance();
System.out.println(c.call());
// make sure that the returned class is loaded from the dummy classloader
- assertTrue(c.call().toString().startsWith(DummyClassLoader.class.getName()));
+ assertTrue(((Object[])c.call())[0].toString().startsWith(DummyClassLoader.class.getName()));
}
}
| true | true | public void testLoad() throws Throwable {
DummyClassLoader cl = new DummyClassLoader(this.getClass().getClassLoader());
Callable c = (Callable) cl.loadClass("hudson.remoting.test.TestCallable").newInstance();
System.out.println(c.call());
// make sure that the returned class is loaded from the dummy classloader
assertTrue(c.call().toString().startsWith(DummyClassLoader.class.getName()));
}
| public void testLoad() throws Throwable {
DummyClassLoader cl = new DummyClassLoader(this.getClass().getClassLoader());
Callable c = (Callable) cl.loadClass("hudson.remoting.test.TestCallable").newInstance();
System.out.println(c.call());
// make sure that the returned class is loaded from the dummy classloader
assertTrue(((Object[])c.call())[0].toString().startsWith(DummyClassLoader.class.getName()));
}
|
diff --git a/loci/formats/in/LIFReader.java b/loci/formats/in/LIFReader.java
index a65995d6f..979930b04 100644
--- a/loci/formats/in/LIFReader.java
+++ b/loci/formats/in/LIFReader.java
@@ -1,453 +1,453 @@
//
// LIFReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library 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 Library General Public License for more details.
You should have received a copy of the GNU Library 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.formats.in;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
import java.util.Vector;
import loci.formats.*;
/**
* LIFReader is the file format reader for Leica LIF files.
*
* @author Melissa Linkert linkert at cs.wisc.edu
*/
public class LIFReader extends FormatReader {
// -- Fields --
/** Current file. */
protected RandomAccessFile in;
/** Flag indicating whether current file is little endian. */
protected boolean littleEndian;
/** Number of image planes in the file. */
protected int numImages = 0;
/** Offsets to memory blocks, paired with their corresponding description. */
protected Vector offsets;
/**
* Dimension information for each image.
* The first index specifies the image number, and the second specifies
* the dimension from the following list:
* 0) width
* 1) height
* 2) Z
* 3) T
* 4) channels (1 or 3)
* 5) bits per pixel
* 6) extra dimensions
*/
protected int[][] dims;
private int width;
private int height;
private int c;
private int bpp;
// -- Constructor --
/** Constructs a new Leica LIF reader. */
public LIFReader() { super("Leica Image File Format", "lif"); }
// -- FormatReader API methods --
/** Checks if the given block is a valid header for a LIF file. */
public boolean isThisType(byte[] block) {
return block[0] == 0x70;
}
/** Determines the number of images in the given LIF file. */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
numImages = dims[series][2] * dims[series][3];
return (!isRGB(id) || !separated) ? numImages : dims[series][4] * numImages;
}
/** Checks if the images in the file are RGB. */
public boolean isRGB(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][4] > 1;
}
/** Get the size of the X dimension. */
public int getSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][0];
}
/** Get the size of the Y dimension. */
public int getSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][1];
}
/** Get the size of the Z dimension. */
public int getSizeZ(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][2];
}
/** Get the size of the C dimension. */
public int getSizeC(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
if (getImageCount(id) == 1 && dims[series][4] < 3) dims[series][4] = 1;
return dims[series][4];
}
/** Get the size of the T dimension. */
public int getSizeT(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][3];
}
/** Return true if the data is in little-endian format. */
public boolean isLittleEndian(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return littleEndian;
}
/**
* Return a five-character string representing the dimension order
* within the file.
*/
public String getDimensionOrder(String id)
throws FormatException, IOException
{
int sizeZ = getSizeZ(id);
int sizeT = getSizeT(id);
if (sizeZ > sizeT) return "XYCZT";
else return "XYCTZ";
}
/** Return the number of series in this file. */
public int getSeriesCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims.length;
}
/** Obtains the specified image from the given LIF file as a byte array. */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
if (no < 0 || no >= getImageCount(id)) {
throw new FormatException("Invalid image number: " + no);
}
// determine which dataset the plane is part of
int z = getSizeZ(id);
int t = getSizeT(id);
width = dims[series][0];
height = dims[series][1];
c = dims[series][4];
if (c == 2) c--;
bpp = dims[series][5];
while (bpp % 8 != 0) bpp++;
int bytesPerPixel = bpp / 8;
int offset = ((Long) offsets.get(series)).intValue();
// get the image number within this dataset
in.seek(offset + width * height * bytesPerPixel * no * c);
byte[] data = new byte[(int) (width * height * bytesPerPixel * c)];
in.read(data);
if (isRGB(id) && separated) {
return ImageTools.splitChannels(data, c, false, true)[no % c];
}
else {
return data;
}
}
/** Obtains the specified image from the given LIF file. */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
return ImageTools.makeImage(openBytes(id, no), width, height,
(!isRGB(id) || separated) ? 1 : c, false, bpp / 8, littleEndian);
}
/** Closes any open files. */
public void close() throws FormatException, IOException {
if (in != null) in.close();
in = null;
currentId = null;
}
/** Initializes the given LIF file. */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessFile(id, "r");
offsets = new Vector();
littleEndian = true;
// read the header
byte checkOne = (byte) in.read();
in.skipBytes(2);
byte checkTwo = (byte) in.read();
if (checkOne != 0x70 && checkTwo != 0x70) {
throw new FormatException(id + " is not a valid Leica LIF file");
}
in.skipBytes(4);
// read and parse the XML description
if (in.read() != 0x2a) {
throw new FormatException("Invalid XML description");
}
// number of Unicode characters in the XML block
int nc = DataTools.read4SignedBytes(in, littleEndian);
byte[] s = new byte[nc * 2];
in.read(s);
String xml = DataTools.stripString(new String(s));
while (in.getFilePointer() < in.length()) {
if (DataTools.read4SignedBytes(in, littleEndian) != 0x70) {
throw new FormatException("Invalid Memory Block");
}
in.skipBytes(4);
if (in.read() != 0x2a) {
throw new FormatException("Invalid Memory Description");
}
int blockLength = DataTools.read4SignedBytes(in, littleEndian);
if (in.read() != 0x2a) {
throw new FormatException("Invalid Memory Description");
}
int descrLength = DataTools.read4SignedBytes(in, littleEndian);
byte[] memDescr = new byte[2*descrLength];
in.read(memDescr);
if (blockLength > 0) {
offsets.add(new Long(in.getFilePointer()));
}
in.skipBytes(blockLength);
}
numImages = offsets.size();
initMetadata(xml);
}
// -- Helper methods --
/** Parses a string of XML and puts the values in a Hashtable. */
private void initMetadata(String xml) {
Vector elements = new Vector();
// first parse each element in the XML string
while (xml.length() > 2) {
String el = xml.substring(1, xml.indexOf(">"));
xml = xml.substring(xml.indexOf(">") + 1);
elements.add(el);
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
metadata.put(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
numImages = 0;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
String tmpToken = token;
if (token.indexOf("=") != -1) {
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
metadata.put(key, value);
}
}
token = tmpToken;
- if (token.startsWith("ElementName")) {
+ if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
- if (tmp.get("ChannelDescriptionDataType") != null) {
+ if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
}
}
- else if (tmp.get("DimensionDescriptionDimID") != null) {
+ else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
int id = Integer.parseInt((String)
- tmp.get("DimensionDescriptionDimID"));
+ tmp.get("DimensionDescription DimID"));
switch (id) {
case 1: widths.add(new Integer(w)); break;
case 2: heights.add(new Integer(w)); break;
case 3: zs.add(new Integer(w)); break;
case 4: ts.add(new Integer(w)); break;
default: extras *= w;
}
}
}
ndx++;
try {
token = (String) elements.get(ndx);
}
catch (Exception e) { break; }
}
extraDims.add(new Integer(extras));
channels.add(new Integer(numChannels));
if (zs.size() < channels.size()) zs.add(new Integer(1));
if (ts.size() < channels.size()) ts.add(new Integer(1));
}
ndx++;
}
numDatasets = widths.size();
dims = new int[numDatasets][7];
for (int i=0; i<numDatasets; i++) {
dims[i][0] = ((Integer) widths.get(i)).intValue();
dims[i][1] = ((Integer) heights.get(i)).intValue();
dims[i][2] = ((Integer) zs.get(i)).intValue();
dims[i][3] = ((Integer) ts.get(i)).intValue();
dims[i][4] = ((Integer) channels.get(i)).intValue();
dims[i][5] = ((Integer) bps.get(i)).intValue();
dims[i][6] = ((Integer) extraDims.get(i)).intValue();
if (dims[i][6] > 1) {
if (dims[i][2] == 1) dims[i][2] = dims[i][6];
else dims[i][3] *= dims[i][6];
dims[i][6] = 1;
}
numImages += (dims[i][2] * dims[i][3] * dims[i][6]);
}
// Populate metadata store
// The metadata store we're working with.
try {
MetadataStore store = getMetadataStore(currentId);
String type = "int8";
switch (dims[0][5]) {
case 12: type = "int16"; break;
case 16: type = "int16"; break;
case 32: type = "float"; break;
}
for (int i=0; i<numDatasets; i++) {
store.setPixels(
new Integer(dims[i][0]), // SizeX
new Integer(dims[i][1]), // SizeY
new Integer(dims[i][2]), // SizeZ
new Integer(dims[i][4]), // SizeC
new Integer(dims[i][3]), // SizeT
type, // PixelType
new Boolean(!littleEndian), // BigEndian
getDimensionOrder(currentId), // DimensionOrder
new Integer(i)); // Index
}
}
catch (Exception e) { }
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
new LIFReader().testRead(args);
}
}
| false | true | private void initMetadata(String xml) {
Vector elements = new Vector();
// first parse each element in the XML string
while (xml.length() > 2) {
String el = xml.substring(1, xml.indexOf(">"));
xml = xml.substring(xml.indexOf(">") + 1);
elements.add(el);
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
metadata.put(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
numImages = 0;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
String tmpToken = token;
if (token.indexOf("=") != -1) {
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
metadata.put(key, value);
}
}
token = tmpToken;
if (token.startsWith("ElementName")) {
// loop until we find "/ImageDescription"
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescriptionDataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
}
}
else if (tmp.get("DimensionDescriptionDimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescriptionDimID"));
switch (id) {
case 1: widths.add(new Integer(w)); break;
case 2: heights.add(new Integer(w)); break;
case 3: zs.add(new Integer(w)); break;
case 4: ts.add(new Integer(w)); break;
default: extras *= w;
}
}
}
ndx++;
try {
token = (String) elements.get(ndx);
}
catch (Exception e) { break; }
}
extraDims.add(new Integer(extras));
channels.add(new Integer(numChannels));
if (zs.size() < channels.size()) zs.add(new Integer(1));
if (ts.size() < channels.size()) ts.add(new Integer(1));
}
ndx++;
}
numDatasets = widths.size();
dims = new int[numDatasets][7];
for (int i=0; i<numDatasets; i++) {
dims[i][0] = ((Integer) widths.get(i)).intValue();
dims[i][1] = ((Integer) heights.get(i)).intValue();
dims[i][2] = ((Integer) zs.get(i)).intValue();
dims[i][3] = ((Integer) ts.get(i)).intValue();
dims[i][4] = ((Integer) channels.get(i)).intValue();
dims[i][5] = ((Integer) bps.get(i)).intValue();
dims[i][6] = ((Integer) extraDims.get(i)).intValue();
if (dims[i][6] > 1) {
if (dims[i][2] == 1) dims[i][2] = dims[i][6];
else dims[i][3] *= dims[i][6];
dims[i][6] = 1;
}
numImages += (dims[i][2] * dims[i][3] * dims[i][6]);
}
// Populate metadata store
// The metadata store we're working with.
try {
MetadataStore store = getMetadataStore(currentId);
String type = "int8";
switch (dims[0][5]) {
case 12: type = "int16"; break;
case 16: type = "int16"; break;
case 32: type = "float"; break;
}
for (int i=0; i<numDatasets; i++) {
store.setPixels(
new Integer(dims[i][0]), // SizeX
new Integer(dims[i][1]), // SizeY
new Integer(dims[i][2]), // SizeZ
new Integer(dims[i][4]), // SizeC
new Integer(dims[i][3]), // SizeT
type, // PixelType
new Boolean(!littleEndian), // BigEndian
getDimensionOrder(currentId), // DimensionOrder
new Integer(i)); // Index
}
}
catch (Exception e) { }
}
| private void initMetadata(String xml) {
Vector elements = new Vector();
// first parse each element in the XML string
while (xml.length() > 2) {
String el = xml.substring(1, xml.indexOf(">"));
xml = xml.substring(xml.indexOf(">") + 1);
elements.add(el);
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
metadata.put(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
numImages = 0;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
String tmpToken = token;
if (token.indexOf("=") != -1) {
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
metadata.put(key, value);
}
}
token = tmpToken;
if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
}
}
else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescription DimID"));
switch (id) {
case 1: widths.add(new Integer(w)); break;
case 2: heights.add(new Integer(w)); break;
case 3: zs.add(new Integer(w)); break;
case 4: ts.add(new Integer(w)); break;
default: extras *= w;
}
}
}
ndx++;
try {
token = (String) elements.get(ndx);
}
catch (Exception e) { break; }
}
extraDims.add(new Integer(extras));
channels.add(new Integer(numChannels));
if (zs.size() < channels.size()) zs.add(new Integer(1));
if (ts.size() < channels.size()) ts.add(new Integer(1));
}
ndx++;
}
numDatasets = widths.size();
dims = new int[numDatasets][7];
for (int i=0; i<numDatasets; i++) {
dims[i][0] = ((Integer) widths.get(i)).intValue();
dims[i][1] = ((Integer) heights.get(i)).intValue();
dims[i][2] = ((Integer) zs.get(i)).intValue();
dims[i][3] = ((Integer) ts.get(i)).intValue();
dims[i][4] = ((Integer) channels.get(i)).intValue();
dims[i][5] = ((Integer) bps.get(i)).intValue();
dims[i][6] = ((Integer) extraDims.get(i)).intValue();
if (dims[i][6] > 1) {
if (dims[i][2] == 1) dims[i][2] = dims[i][6];
else dims[i][3] *= dims[i][6];
dims[i][6] = 1;
}
numImages += (dims[i][2] * dims[i][3] * dims[i][6]);
}
// Populate metadata store
// The metadata store we're working with.
try {
MetadataStore store = getMetadataStore(currentId);
String type = "int8";
switch (dims[0][5]) {
case 12: type = "int16"; break;
case 16: type = "int16"; break;
case 32: type = "float"; break;
}
for (int i=0; i<numDatasets; i++) {
store.setPixels(
new Integer(dims[i][0]), // SizeX
new Integer(dims[i][1]), // SizeY
new Integer(dims[i][2]), // SizeZ
new Integer(dims[i][4]), // SizeC
new Integer(dims[i][3]), // SizeT
type, // PixelType
new Boolean(!littleEndian), // BigEndian
getDimensionOrder(currentId), // DimensionOrder
new Integer(i)); // Index
}
}
catch (Exception e) { }
}
|
diff --git a/Dugeon/src/map/factory/MapGenerator.java b/Dugeon/src/map/factory/MapGenerator.java
index 68d9571..df2bc16 100644
--- a/Dugeon/src/map/factory/MapGenerator.java
+++ b/Dugeon/src/map/factory/MapGenerator.java
@@ -1,272 +1,272 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package map.factory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import map.component.Cavern;
import map.component.Corridor;
import map.component.MapComponent;
import map.component.Maze;
import map.component.OvalRoom;
import map.component.RectangleRoom;
import model.Coordinate;
import objects.ViewablePixel;
import objects.Wall;
import objects.Way;
/**
*
* @author hoanggia
*/
public class MapGenerator {
private static final int MAX_SIDE_OF_COMPONENT = 52;
private static final int MIN_SIDE_OF_COMPONENT = 7;
private static final int MAX_DISTANCE_BETWEEN_MAP_COMPONENT = 5;
private Map<Coordinate, ViewablePixel> pixelsMap;
private List<MapComponent> mapComponents;
public MapGenerator() {
pixelsMap = new TreeMap<Coordinate, ViewablePixel>();
mapComponents = new ArrayList<MapComponent>();
}
public Map<Coordinate, ViewablePixel> generateMap() {
Random r = new Random();
- int numberOfComponent = r.nextInt(5);
+ int numberOfComponent = r.nextInt(5)+1;
for (int i = 0; i < numberOfComponent; i++) {
MapComponent component = getRandomMapComponent();
System.out.println(component.getClass().getName());
Coordinate c;
if (i != 0) {
System.out.println(component.getViewablePixels().keySet());
c = generateRandomCoordinateNextToComponent(mapComponents.get(i-1));
shiftAllCoordinateTo(component, c);
System.out.println(component.getViewablePixels().keySet());
System.out.println(pixelsMap.keySet());
Coordinate[] points = getNearestWayPoints(pixelsMap, component.getViewablePixels());
MapComponent corridor = new Corridor(points[0], points[1]);
System.out.println(points[0]+" " +points[1]);
pixelsMap.putAll(component.getViewablePixels());
pixelsMap.putAll(corridor.getViewablePixels());
} else {
pixelsMap.putAll(component.getViewablePixels());
}
mapComponents.add(component);
}
//generateWalls();
return pixelsMap;
}
private Coordinate generateRandomCoordinateNextToComponent(MapComponent component) {
Random r = new Random();
Coordinate maxCoordinate = getMaxCoordinateOfMapComponent(component);
Coordinate minCoordinate = getMinCoordinateOfMapComponent(component);
Coordinate c;
switch (r.nextInt(3)) {
case 0:
c = new Coordinate(maxCoordinate.getX() + r.nextInt(MAX_DISTANCE_BETWEEN_MAP_COMPONENT) + 2, minCoordinate.getY());
System.out.println("0");
break;
case 1:
c = new Coordinate(minCoordinate.getX(), maxCoordinate.getY() + r.nextInt(MAX_DISTANCE_BETWEEN_MAP_COMPONENT) + 2);
System.out.println("1");
break;
default:
c = new Coordinate(maxCoordinate.getX() + r.nextInt(MAX_DISTANCE_BETWEEN_MAP_COMPONENT) + 2, maxCoordinate.getY() + r.nextInt(MAX_DISTANCE_BETWEEN_MAP_COMPONENT) + 2);
System.out.println("2");
break;
}
System.out.println("random coordinate " + c);
return c;
}
private boolean isOverlap(Map<Coordinate, ViewablePixel> componetA, Map<Coordinate, ViewablePixel> componetB) {
for (Coordinate cA : componetA.keySet()) {
for (Coordinate cB : componetB.keySet()) {
if (cA.equals(cB)) {
return true;
}
}
}
return false;
}
private Coordinate[] getNearestWayPoints(Map<Coordinate, ViewablePixel> componentA, Map<Coordinate, ViewablePixel> componentB) {
int minDistance = Integer.MAX_VALUE;
List<Coordinate[]> l = new ArrayList<Coordinate[]>();
for (Coordinate cA : componentA.keySet()) {
for (Coordinate cB : componentB.keySet()) {
if (componentA.get(cA) instanceof Way && componentB.get(cB) instanceof Way && minDistance > cA.distanceTo(cB)) {
minDistance = cA.distanceTo(cB);
Coordinate[] points = new Coordinate[2];
points[0] = cA;
points[1] = cB;
l.clear();
l.add(points);
} else if (componentA.get(cA) instanceof Way && componentB.get(cB) instanceof Way && minDistance == cA.distanceTo(cB)) {
Coordinate[] points = new Coordinate[2];
points[0] = cA;
points[1] = cB;
l.add(points);
}
}
}
Random r=new Random();
return l.get(r.nextInt(l.size()));
}
private void generateWalls() {
Map<Coordinate, ViewablePixel> waysNow = new HashMap<Coordinate, ViewablePixel>(getWays());
for (ViewablePixel p : waysNow.values()) {
if (p instanceof Way) {
if (!pixelsMap.containsKey(new Coordinate(p.getCoordinate().getX() + 1, p.getCoordinate().getY()))) {
ViewablePixel wall = new Wall(new Coordinate(p.getCoordinate().getX() + 1, p.getCoordinate().getY()));
pixelsMap.put(wall.getCoordinate(), wall);
}
if (!pixelsMap.containsKey(new Coordinate(p.getCoordinate().getX(), p.getCoordinate().getY() + 1))) {
ViewablePixel wall = new Wall(new Coordinate(p.getCoordinate().getX(), p.getCoordinate().getY() + 1));
pixelsMap.put(wall.getCoordinate(), wall);
}
if (!pixelsMap.containsKey(new Coordinate(p.getCoordinate().getX() - 1, p.getCoordinate().getY()))) {
ViewablePixel wall = new Wall(new Coordinate(p.getCoordinate().getX() - 1, p.getCoordinate().getY()));
pixelsMap.put(wall.getCoordinate(), wall);
}
if (!pixelsMap.containsKey(new Coordinate(p.getCoordinate().getX(), p.getCoordinate().getY() - 1))) {
ViewablePixel wall = new Wall(new Coordinate(p.getCoordinate().getX(), p.getCoordinate().getY() - 1));
pixelsMap.put(wall.getCoordinate(), wall);
}
}
}
}
private Coordinate getMaxCoordinateOfMapComponent(MapComponent component) {
int maxX = 0;
int maxY = 0;
for (Coordinate c : component.getViewablePixels().keySet()) {
if (c.getX() > maxX) {
maxX = c.getX();
}
if (c.getY() > maxY) {
maxY = c.getY();
}
}
return new Coordinate(maxX, maxY);
}
private Coordinate getMinCoordinateOfMapComponent(MapComponent component) {
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
for (Coordinate c : component.getViewablePixels().keySet()) {
if (c.getX() < minX) {
minX = c.getX();
}
if (c.getY() < minY) {
minY = c.getY();
}
}
return new Coordinate(minX, minY);
}
private MapComponent getRandomMapComponent() {
Random r = new Random();
int randomIntForType = r.nextInt(4);
int randomIntForRadius = limitRangeForValue(MAX_SIDE_OF_COMPONENT / 2, MIN_SIDE_OF_COMPONENT, r.nextInt());
int randomIntForWidth = limitRangeForValue(MAX_SIDE_OF_COMPONENT, MIN_SIDE_OF_COMPONENT, r.nextInt());
int randomIntForHeight = limitRangeForValue(MAX_SIDE_OF_COMPONENT, MIN_SIDE_OF_COMPONENT, r.nextInt());
MapComponent component;
switch (randomIntForType) {
case 0:
component = new Cavern(randomIntForRadius);
break;
case 1:
component = new Maze(randomIntForWidth, randomIntForHeight);
break;
case 2:
component = new OvalRoom(randomIntForRadius);
break;
default:
component = new RectangleRoom(randomIntForWidth, randomIntForHeight);
break;
}
return component;
}
private int limitRangeForValue(int max, int min, int value) {
if (max < value) {
return max;
}
if (min > value) {
return min;
}
return value;
}
private Map<Coordinate, ViewablePixel> getWalls() {
Map<Coordinate, ViewablePixel> walls = new HashMap<Coordinate, ViewablePixel>();
for (ViewablePixel p : pixelsMap.values()) {
if (p instanceof Wall) {
walls.put(p.getCoordinate(), p);
}
}
return walls;
}
private Map<Coordinate, ViewablePixel> getOuterWalls() {
Map<Coordinate, ViewablePixel> outerWalls = new HashMap<Coordinate, ViewablePixel>();
for (ViewablePixel p : getWalls().values()) {
Coordinate n = new Coordinate(p.getCoordinate().getX(), p.getCoordinate().getY() - 1);
Coordinate e = new Coordinate(p.getCoordinate().getX() + 1, p.getCoordinate().getY());
Coordinate w = new Coordinate(p.getCoordinate().getX() - 1, p.getCoordinate().getY());
Coordinate s = new Coordinate(p.getCoordinate().getX(), p.getCoordinate().getY() + 1);
if (!pixelsMap.containsKey(n) || !pixelsMap.containsKey(e) || !pixelsMap.containsKey(w) || !pixelsMap.containsKey(s)) {
outerWalls.put(p.getCoordinate(), p);
}
}
return outerWalls;
}
private Map<Coordinate, ViewablePixel> getWays() {
Map<Coordinate, ViewablePixel> ways = new HashMap<Coordinate, ViewablePixel>();
for (ViewablePixel p : pixelsMap.values()) {
if (p instanceof Way) {
ways.put(p.getCoordinate(), p);
}
}
return ways;
}
private void shiftAllCoordinateTo(MapComponent component, Coordinate coordinate) {
Map<Coordinate,ViewablePixel> newViewablePixels=new HashMap<Coordinate, ViewablePixel>();
for (ViewablePixel p : component.getViewablePixels().values()) {
p.getCoordinate().shiftCoordinate(coordinate.getX(), coordinate.getY());
newViewablePixels.put(p.getCoordinate(), p);
}
component.getViewablePixels().clear();
component.getViewablePixels().putAll(newViewablePixels);
}
}
| true | true | public Map<Coordinate, ViewablePixel> generateMap() {
Random r = new Random();
int numberOfComponent = r.nextInt(5);
for (int i = 0; i < numberOfComponent; i++) {
MapComponent component = getRandomMapComponent();
System.out.println(component.getClass().getName());
Coordinate c;
if (i != 0) {
System.out.println(component.getViewablePixels().keySet());
c = generateRandomCoordinateNextToComponent(mapComponents.get(i-1));
shiftAllCoordinateTo(component, c);
System.out.println(component.getViewablePixels().keySet());
System.out.println(pixelsMap.keySet());
Coordinate[] points = getNearestWayPoints(pixelsMap, component.getViewablePixels());
MapComponent corridor = new Corridor(points[0], points[1]);
System.out.println(points[0]+" " +points[1]);
pixelsMap.putAll(component.getViewablePixels());
pixelsMap.putAll(corridor.getViewablePixels());
} else {
pixelsMap.putAll(component.getViewablePixels());
}
mapComponents.add(component);
}
//generateWalls();
return pixelsMap;
}
| public Map<Coordinate, ViewablePixel> generateMap() {
Random r = new Random();
int numberOfComponent = r.nextInt(5)+1;
for (int i = 0; i < numberOfComponent; i++) {
MapComponent component = getRandomMapComponent();
System.out.println(component.getClass().getName());
Coordinate c;
if (i != 0) {
System.out.println(component.getViewablePixels().keySet());
c = generateRandomCoordinateNextToComponent(mapComponents.get(i-1));
shiftAllCoordinateTo(component, c);
System.out.println(component.getViewablePixels().keySet());
System.out.println(pixelsMap.keySet());
Coordinate[] points = getNearestWayPoints(pixelsMap, component.getViewablePixels());
MapComponent corridor = new Corridor(points[0], points[1]);
System.out.println(points[0]+" " +points[1]);
pixelsMap.putAll(component.getViewablePixels());
pixelsMap.putAll(corridor.getViewablePixels());
} else {
pixelsMap.putAll(component.getViewablePixels());
}
mapComponents.add(component);
}
//generateWalls();
return pixelsMap;
}
|
diff --git a/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java b/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java
index 45e7eec74..60629d5d9 100644
--- a/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java
+++ b/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java
@@ -1,102 +1,101 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package com.gallatinsystems.framework.dataexport.applet;
import java.io.File;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import org.waterforpeople.mapping.dataexport.RawDataExporter;
/**
* simple applet to allow us to export data from google app engine
*
* @author Christopher Fagiani
*
*/
public class DataExportAppletImpl extends AbstractDataImportExportApplet {
private static final long serialVersionUID = 944163825066341210L;
private static final String EXPORT_TYPE_PARAM = "exportType";
private static final String OPTIONS_PARAM = "options";
private JLabel statusLabel;
private DataImportExportFactory dataExporterFactory;
private Boolean useTabFlag = false;
/**
* initializes the UI, constructs the exporter factory then invokes the
* export method.
*/
public void init() {
statusLabel = new JLabel();
getContentPane().add(statusLabel);
String type = getParameter(EXPORT_TYPE_PARAM);
dataExporterFactory = getDataImportExportFactory();
doExport(type, getConfigCriteria(), getServerBase(),
parseCriteria(getParameter(OPTIONS_PARAM)));
}
/**
* launches a JFileChooser to prompt the user to specify an output file. If
* the file is supplied, will then invoke the export method on the exporter
* returned from the factory..
*
* @param type
* @param criteriaMap
* @param serverBase
* @param options
*/
public void doExport(String type, Map<String, String> criteriaMap,
String serverBase, Map<String, String> options) {
final JFileChooser chooser = new JFileChooser();
final String surveyId = criteriaMap.containsKey("surveyId") ? criteriaMap
.get("surveyId") : null;
- String exportType = criteriaMap.get("exportType");
String ext = ".xlsx";
- if (exportType != null && exportType.equalsIgnoreCase("SURVEY_FORM")) {
+ if ("SURVEY_FORM".equalsIgnoreCase(type)) {
ext = ".xls";
}
final String fileName = type + (surveyId != null ? "-" + surveyId : "")
+ ext;
chooser.setSelectedFile(new File(fileName));
chooser.showSaveDialog(this);
if (chooser.getSelectedFile() != null) {
DataExporter exporter = dataExporterFactory.getExporter(type);
statusLabel.setText("Exporting...");
if (serverBase.trim().endsWith("/")) {
serverBase = serverBase.trim().substring(0,
serverBase.lastIndexOf("/"));
}
if(options.containsKey("generateTabFormat")){
if(options.get("generateTabFormat").trim()!=null && !options.get("generateTabFormat").trim().equalsIgnoreCase(""))
useTabFlag = Boolean.parseBoolean(options.get("generateTabFormat"));
}
if (type.equalsIgnoreCase("RAW_DATA")&&useTabFlag) {
RawDataExporter rde = new RawDataExporter();
rde.export(criteriaMap , chooser.getSelectedFile(), serverBase, options);
} else {
exporter.export(criteriaMap, chooser.getSelectedFile(),
serverBase, options);
}
statusLabel.setText("Export Complete");
}
}
}
| false | true | public void doExport(String type, Map<String, String> criteriaMap,
String serverBase, Map<String, String> options) {
final JFileChooser chooser = new JFileChooser();
final String surveyId = criteriaMap.containsKey("surveyId") ? criteriaMap
.get("surveyId") : null;
String exportType = criteriaMap.get("exportType");
String ext = ".xlsx";
if (exportType != null && exportType.equalsIgnoreCase("SURVEY_FORM")) {
ext = ".xls";
}
final String fileName = type + (surveyId != null ? "-" + surveyId : "")
+ ext;
chooser.setSelectedFile(new File(fileName));
chooser.showSaveDialog(this);
if (chooser.getSelectedFile() != null) {
DataExporter exporter = dataExporterFactory.getExporter(type);
statusLabel.setText("Exporting...");
if (serverBase.trim().endsWith("/")) {
serverBase = serverBase.trim().substring(0,
serverBase.lastIndexOf("/"));
}
if(options.containsKey("generateTabFormat")){
if(options.get("generateTabFormat").trim()!=null && !options.get("generateTabFormat").trim().equalsIgnoreCase(""))
useTabFlag = Boolean.parseBoolean(options.get("generateTabFormat"));
}
if (type.equalsIgnoreCase("RAW_DATA")&&useTabFlag) {
RawDataExporter rde = new RawDataExporter();
rde.export(criteriaMap , chooser.getSelectedFile(), serverBase, options);
} else {
exporter.export(criteriaMap, chooser.getSelectedFile(),
serverBase, options);
}
statusLabel.setText("Export Complete");
}
}
| public void doExport(String type, Map<String, String> criteriaMap,
String serverBase, Map<String, String> options) {
final JFileChooser chooser = new JFileChooser();
final String surveyId = criteriaMap.containsKey("surveyId") ? criteriaMap
.get("surveyId") : null;
String ext = ".xlsx";
if ("SURVEY_FORM".equalsIgnoreCase(type)) {
ext = ".xls";
}
final String fileName = type + (surveyId != null ? "-" + surveyId : "")
+ ext;
chooser.setSelectedFile(new File(fileName));
chooser.showSaveDialog(this);
if (chooser.getSelectedFile() != null) {
DataExporter exporter = dataExporterFactory.getExporter(type);
statusLabel.setText("Exporting...");
if (serverBase.trim().endsWith("/")) {
serverBase = serverBase.trim().substring(0,
serverBase.lastIndexOf("/"));
}
if(options.containsKey("generateTabFormat")){
if(options.get("generateTabFormat").trim()!=null && !options.get("generateTabFormat").trim().equalsIgnoreCase(""))
useTabFlag = Boolean.parseBoolean(options.get("generateTabFormat"));
}
if (type.equalsIgnoreCase("RAW_DATA")&&useTabFlag) {
RawDataExporter rde = new RawDataExporter();
rde.export(criteriaMap , chooser.getSelectedFile(), serverBase, options);
} else {
exporter.export(criteriaMap, chooser.getSelectedFile(),
serverBase, options);
}
statusLabel.setText("Export Complete");
}
}
|
diff --git a/map/map-impl/src/test/java/org/mobicents/protocols/ss7/map/service/mobility/subscriberManagement/BearerServiceCodeValueTest.java b/map/map-impl/src/test/java/org/mobicents/protocols/ss7/map/service/mobility/subscriberManagement/BearerServiceCodeValueTest.java
index f790aef03..72399097c 100644
--- a/map/map-impl/src/test/java/org/mobicents/protocols/ss7/map/service/mobility/subscriberManagement/BearerServiceCodeValueTest.java
+++ b/map/map-impl/src/test/java/org/mobicents/protocols/ss7/map/service/mobility/subscriberManagement/BearerServiceCodeValueTest.java
@@ -1,51 +1,51 @@
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.mobicents.protocols.ss7.map.service.mobility.subscriberManagement;
import org.mobicents.protocols.ss7.map.api.service.mobility.subscriberManagement.BearerServiceCodeValue;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* @author Amit Bhayani
*
*/
public class BearerServiceCodeValueTest {
/**
*
*/
public BearerServiceCodeValueTest() {
// TODO Auto-generated constructor stub
}
@Test(groups = { "functional.encode","primitives"})
public void test() throws Exception {
- int code = BearerServiceCodeValue.Asynchronous9_6kbps.getCode();
+ int code = BearerServiceCodeValue.Asynchronous9_6kbps.getBearerServiceCode();
BearerServiceCodeValue valueFromCode = BearerServiceCodeValue.getInstance(code);
assertEquals(valueFromCode, BearerServiceCodeValue.Asynchronous9_6kbps);
}
}
| true | true | public void test() throws Exception {
int code = BearerServiceCodeValue.Asynchronous9_6kbps.getCode();
BearerServiceCodeValue valueFromCode = BearerServiceCodeValue.getInstance(code);
assertEquals(valueFromCode, BearerServiceCodeValue.Asynchronous9_6kbps);
}
| public void test() throws Exception {
int code = BearerServiceCodeValue.Asynchronous9_6kbps.getBearerServiceCode();
BearerServiceCodeValue valueFromCode = BearerServiceCodeValue.getInstance(code);
assertEquals(valueFromCode, BearerServiceCodeValue.Asynchronous9_6kbps);
}
|
diff --git a/srcj/com/sun/electric/technology/Xml.java b/srcj/com/sun/electric/technology/Xml.java
index 521fe5db1..02f61e011 100644
--- a/srcj/com/sun/electric/technology/Xml.java
+++ b/srcj/com/sun/electric/technology/Xml.java
@@ -1,2465 +1,2469 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Xml.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.technology;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.EGraphics;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.technology.Technology.TechPoint;
import com.sun.electric.tool.Job;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
*/
public class Xml {
/** Default Logical effort gate capacitance. */ public static final double DEFAULT_LE_GATECAP = 0.4;
/** Default Logical effort wire ratio. */ public static final double DEFAULT_LE_WIRERATIO = 0.16;
/** Default Logical effort diff alpha. */ public static final double DEFAULT_LE_DIFFALPHA = 0.7;
public static class Technology implements Serializable {
public String techName;
public String className;
public String shortTechName;
public String description;
public final List<Version> versions = new ArrayList<Version>();
public int minNumMetals;
public int maxNumMetals;
public int defaultNumMetals;
public double scaleValue;
public double resolutionValue; // min resolution value allowed by the foundry
public boolean scaleRelevant;
public String defaultFoundry;
public double minResistance;
public double minCapacitance;
public double leGateCapacitance = DEFAULT_LE_GATECAP;
public double leWireRatio = DEFAULT_LE_WIRERATIO;
public double leDiffAlpha = DEFAULT_LE_DIFFALPHA;
public final List<Color> transparentLayers = new ArrayList<Color>();
public final List<Layer> layers = new ArrayList<Layer>();
public final List<ArcProto> arcs = new ArrayList<ArcProto>();
public final List<PrimitiveNodeGroup> nodeGroups = new ArrayList<PrimitiveNodeGroup>();
public final List<PrimitiveNode> pureLayerNodes = new ArrayList<PrimitiveNode>();
public final List<SpiceHeader> spiceHeaders = new ArrayList<SpiceHeader>();
public MenuPalette menuPalette;
public final List<Foundry> foundries = new ArrayList<Foundry>();
public Layer findLayer(String name) {
for (Layer layer: layers) {
if (layer.name.equals(name))
return layer;
}
return null;
}
public Collection<String> getLayerNames()
{
List<String> l = new ArrayList<String>();
for (Layer layer: layers)
l.add(layer.name);
return l;
}
public ArcProto findArc(String name) {
for (ArcProto arc: arcs) {
if (arc.name.equals(name))
return arc;
}
return null;
}
public PrimitiveNodeGroup findNodeGroup(String name) {
for (PrimitiveNodeGroup nodeGroup: nodeGroups) {
for (PrimitiveNode n: nodeGroup.nodes) {
if (n.name.equals(name))
return nodeGroup;
}
}
return null;
}
public PrimitiveNode findNode(String name) {
for (PrimitiveNodeGroup nodeGroup: nodeGroups) {
for (PrimitiveNode n: nodeGroup.nodes) {
if (n.name.equals(name))
return n;
}
}
for(PrimitiveNode n : pureLayerNodes) {
if (n.name.equals(name))
return n;
}
return null;
}
public Collection<String> getNodeNames() {
List<String> l = new ArrayList<String>();
for (PrimitiveNodeGroup nodeGroup: nodeGroups) {
for (PrimitiveNode n: nodeGroup.nodes) {
l.add(n.name);
}
}
return l;
}
/**
* Method to find the first PrimitiveNode which would have the given arc
*/
public PrimitiveNode findPinNode(String arc)
{
for (PrimitiveNodeGroup nodeGroup: nodeGroups)
{
boolean foundPort = false;
for (PrimitivePort p: nodeGroup.ports)
{
if(p.portArcs.contains(arc))
{
foundPort = true;
break;
}
}
if (foundPort) // now checking if there is a pin associated with the arc
{
for (PrimitiveNode n: nodeGroup.nodes)
{
if (n.function.isPin())
return n;
}
}
}
return null;
}
public void writeXml(String fileName) {
writeXml(fileName, true, null);
}
public void writeXml(String fileName, boolean includeDateAndVersion, String copyrightMessage) {
try {
PrintWriter out = new PrintWriter(fileName);
Writer writer = new Writer(out);
writer.writeTechnology(this, includeDateAndVersion, copyrightMessage);
out.close();
System.out.println("Wrote " + fileName);
System.out.println(" (Add this file to the 'Added Technologies' Project Preferences to install it in Electric)");
} catch (IOException e) {
System.out.println("Error creating " + fileName);
}
}
public Technology deepClone() {
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteStream);
out.writeObject(this);
out.flush();
byte[] serializedXml = byteStream.toByteArray();
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedXml));
Xml.Technology clone = (Xml.Technology)in.readObject();
in.close();
return clone;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public static class Version implements Serializable {
public int techVersion;
public com.sun.electric.database.text.Version electricVersion;
}
public static class Layer implements Serializable {
public String name;
public com.sun.electric.technology.Layer.Function function;
public int extraFunction;
public EGraphics desc;
public double thick3D;
public double height3D;
public String cif;
public String skill;
public double resistance;
public double capacitance;
public double edgeCapacitance;
public PureLayerNode pureLayerNode;
}
public static class PureLayerNode implements Serializable {
public String name;
public String oldName;
public Poly.Type style;
public String port;
public final Distance size = new Distance();
public final List<String> portArcs = new ArrayList<String>();
}
public static class ArcProto implements Serializable {
public String name;
public String oldName;
public com.sun.electric.technology.ArcProto.Function function;
public boolean wipable;
public boolean curvable;
public boolean special;
public boolean notUsed;
public boolean skipSizeInPalette;
public final Map<Integer,Double> diskOffset = new TreeMap<Integer,Double>();
public final Distance defaultWidth = new Distance();
public boolean extended;
public boolean fixedAngle;
public int angleIncrement;
public double antennaRatio;
public final List<ArcLayer> arcLayers = new ArrayList<ArcLayer>();
}
public static class ArcLayer implements Serializable {
public String layer;
public final Distance extend = new Distance();
public Poly.Type style;
}
public static class PrimitiveNode implements Serializable {
public String name;
public com.sun.electric.technology.PrimitiveNode.Function function;
public String oldName;
public boolean lowVt;
public boolean highVt;
public boolean nativeBit;
public boolean od18;
public boolean od25;
public boolean od33;
}
public static class PrimitiveNodeGroup implements Serializable {
public boolean isSingleton;
public final List<PrimitiveNode> nodes = new ArrayList<PrimitiveNode>();
public boolean shrinkArcs;
public boolean square;
public boolean canBeZeroSize;
public boolean wipes;
public boolean lockable;
public boolean edgeSelect;
public boolean skipSizeInPalette;
public boolean notUsed;
public final Map<Integer,EPoint> diskOffset = new TreeMap<Integer,EPoint>();
public final Distance defaultWidth = new Distance();
public final Distance defaultHeight = new Distance();
public final Distance baseLX = new Distance();
public final Distance baseHX = new Distance();
public final Distance baseLY = new Distance();
public final Distance baseHY = new Distance();
public ProtectionType protection;
public final List<NodeLayer> nodeLayers = new ArrayList<NodeLayer>();
public final List<PrimitivePort> ports = new ArrayList<PrimitivePort>();
public int specialType;
public double[] specialValues;
public NodeSizeRule nodeSizeRule;
public String spiceTemplate;
}
public enum ProtectionType {
both, left, right, none;
}
public static class NodeLayer implements Serializable {
public String layer;
public BitSet inNodes;
public Poly.Type style;
public int portNum;
public boolean inLayers;
public boolean inElectricalLayers;
public int representation;
public final Distance lx = new Distance();
public final Distance hx = new Distance();
public final Distance ly = new Distance();
public final Distance hy = new Distance();
public final List<TechPoint> techPoints = new ArrayList<TechPoint>();
public double sizex, sizey, sep1d, sep2d;
public double lWidth, rWidth, tExtent, bExtent;
}
public static class NodeSizeRule implements Serializable {
public double width;
public double height;
public String rule;
}
public static class PrimitivePort implements Serializable {
public String name;
public int portAngle;
public int portRange;
public int portTopology;
public final Distance lx = new Distance();
public final Distance hx = new Distance();
public final Distance ly = new Distance();
public final Distance hy = new Distance();
public final List<String> portArcs = new ArrayList<String>();
}
public static class SpiceHeader implements Serializable {
public int level;
public final List<String> spiceLines = new ArrayList<String>();
}
public static class MenuPalette implements Serializable {
public int numColumns;
public List<List<?>> menuBoxes = new ArrayList<List<?>>();
public String writeXml() {
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
Xml.OneLineWriter writer = new Xml.OneLineWriter(out);
writer.writeMenuPaletteXml(this);
out.close();
return sw.getBuffer().toString();
}
}
public static class MenuNodeInst implements Serializable {
/** the name of the prototype in the menu */ public String protoName;
/** the function of the prototype */ public com.sun.electric.technology.PrimitiveNode.Function function;
/** tech bits */ public int techBits;
/** label to draw in the menu entry (may be null) */ public String text;
/** the rotation of the node in the menu entry */ public int rotation;
}
public static class Distance implements Serializable {
public double k;
public double value;
public void addLambda(double lambdaValue) {
value += lambdaValue;
}
}
public static class Foundry implements Serializable {
public String name;
public final Map<String,String> layerGds = new LinkedHashMap<String,String>();
public final List<DRCTemplate> rules = new ArrayList<DRCTemplate>();
}
private Xml() {}
private static enum XmlKeyword {
technology,
shortName(true),
description(true),
version,
numMetals,
scale,
resolution,
defaultFoundry,
minResistance,
minCapacitance,
logicalEffort,
transparentLayer,
r(true),
g(true),
b(true),
layer,
transparentColor,
opaqueColor,
patternedOnDisplay(true),
patternedOnPrinter(true),
pattern(true),
outlined(true),
opacity(true),
foreground(true),
display3D,
cifLayer,
skillLayer,
parasitics,
pureLayerNode,
arcProto,
oldName(true),
wipable,
curvable,
special,
notUsed,
skipSizeInPalette,
extended(true),
fixedAngle(true),
angleIncrement(true),
antennaRatio(true),
diskOffset,
defaultWidth,
arcLayer,
primitiveNodeGroup,
inNodes,
primitiveNode,
//oldName(true),
shrinkArcs,
square,
canBeZeroSize,
wipes,
lockable,
edgeSelect,
// skipSizeInPalette,
// notUsed,
lowVt,
highVt,
nativeBit,
od18,
od25,
od33,
// defaultWidth,
defaultHeight,
nodeBase,
sizeOffset,
nodeLayer,
box,
multicutbox,
serpbox,
lambdaBox,
points,
techPoint,
primitivePort,
portAngle,
portTopology(true),
// techPoint,
portArc(true),
polygonal,
serpTrans,
specialValue(true),
// Protection layer for transistors
protection,
// location(true),
minSizeRule,
spiceTemplate,
spiceHeader,
spiceLine,
menuPalette,
menuBox,
menuArc(true),
menuNode(true),
menuText(true),
menuNodeInst,
menuNodeText,
lambda(true),
Foundry,
layerGds,
LayerRule,
LayersRule,
NodeLayersRule,
NodeRule;
private final boolean hasText;
private XmlKeyword() {
hasText = false;
};
private XmlKeyword(boolean hasText) {
this.hasText = hasText;
}
};
private static final Map<String,XmlKeyword> xmlKeywords = new HashMap<String,XmlKeyword>();
static {
for (XmlKeyword k: XmlKeyword.class.getEnumConstants())
xmlKeywords.put(k.name(), k);
}
private static Schema schema = null;
private static synchronized void loadTechnologySchema() throws SAXException {
if (schema != null) return;
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL technologySchemaUrl = Technology.class.getResource("Technology.xsd");
if (technologySchemaUrl != null)
schema = schemaFactory.newSchema(technologySchemaUrl);
else
{
System.err.println("Schema file Technology.xsd, working without XML schema");
System.out.println("Schema file Technology.xsd, working without XML schema");
}
}
public static Technology parseTechnology(URL fileURL) {
// System.out.println("Memory usage " + Main.getMemoryUsage() + " bytes");
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
try {
if (schema == null)
loadTechnologySchema();
factory.setSchema(schema);
// factory.setValidating(true);
// System.out.println("Memory usage " + Main.getMemoryUsage() + " bytes");
// create the parser
long startTime = System.currentTimeMillis();
SAXParser parser = factory.newSAXParser();
URLConnection urlCon = fileURL.openConnection();
InputStream inputStream = urlCon.getInputStream();
XMLReader handler = new XMLReader();
parser.parse(inputStream, handler);
if (Job.getDebug())
{
long stopTime = System.currentTimeMillis();
System.out.println("Loading technology " + fileURL + " ... " + (stopTime - startTime) + " msec");
}
return handler.tech;
} catch (SAXParseException e) {
String msg = "Error parsing Xml technology:\n" +
e.getMessage() + "\n" +
" Line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + fileURL;
msg = msg.replaceAll("\"http://electric.sun.com/Technology\":", "");
System.out.println(msg);
Job.getUserInterface().showErrorMessage(msg, "Error parsing Xml technology");
} catch (Exception e) {
String msg = "Error loading Xml technology " + fileURL + " :\n"
+ e.getMessage() + "\n";
System.out.println(msg);
Job.getUserInterface().showErrorMessage(msg, "Error loading Xml technology");
} catch (Error a)
{
String msg = "Assertion while loading Xml technology " + fileURL;
System.out.println(msg);
//Job.getUserInterface().showErrorMessage(msg, "Error loading Xml technology");
}
return null;
}
/**
* Method to parse a string of XML that describes the component menu in a Technology Editing context.
* Normal parsing of XML returns objects in the Xml class, but
* this method returns objects in a given Technology-Editor world.
* @param xml the XML string
* @param nodeGroups the PrimitiveNodeGroup objects describing nodes in the technology.
* @param arcs the ArcProto objects describing arcs in the technology.
* @param pureLayerNodes the PrimitiveNode objects describing pure-layer nodes in the technology.
* @return the MenuPalette describing the component menu.
*/
public static MenuPalette parseComponentMenuXMLTechEdit(String xml, List<PrimitiveNodeGroup> nodeGroups, List<ArcProto> arcs,
List<PrimitiveNode> pureLayerNodes)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
try
{
SAXParser parser = factory.newSAXParser();
InputSource is = new InputSource(new StringReader(xml));
XMLReader handler = new XMLReader(nodeGroups, arcs, pureLayerNodes);
parser.parse(is, handler);
return handler.tech.menuPalette;
} catch (Exception e)
{
System.out.println("Error parsing XML component menu data");
e.printStackTrace();
}
return null;
}
private static class XMLReader extends DefaultHandler {
private static boolean DEBUG = false;
private Locator locator;
private Xml.Technology tech = new Xml.Technology();
private int curTransparent = 0;
private int curR;
private int curG;
private int curB;
private Layer curLayer;
private boolean patternedOnDisplay;
private boolean patternedOnPrinter;
private final int[] pattern = new int[16];
private int curPatternIndex;
private EGraphics.Outline outline;
private double opacity;
private boolean foreground;
private EGraphics.J3DTransparencyOption transparencyMode;
private double transparencyFactor;
private ArcProto curArc;
private PrimitiveNodeGroup curNodeGroup;
private boolean curNodeGroupHasNodeBase;
private PrimitiveNode curNode;
private NodeLayer curNodeLayer;
private PrimitivePort curPort;
private int curSpecialValueIndex;
private ArrayList<Object> curMenuBox;
private MenuNodeInst curMenuNodeInst;
private Distance curDistance;
private SpiceHeader curSpiceHeader;
private Foundry curFoundry;
private Collection<String> curLayerNamesList;
private Collection<String> curNodeNamesList;
private boolean acceptCharacters;
private StringBuilder charBuffer = new StringBuilder();
private Attributes attributes;
XMLReader() {
}
XMLReader(List<PrimitiveNodeGroup> nodeGroups, List<ArcProto> arcs, List<PrimitiveNode> pureLayerNodes)
{
tech.arcs.addAll(arcs);
tech.nodeGroups.addAll(nodeGroups);
tech.pureLayerNodes.addAll(pureLayerNodes);
}
private void beginCharacters() {
assert !acceptCharacters;
acceptCharacters = true;
assert charBuffer.length() == 0;
}
private String endCharacters() {
assert acceptCharacters;
String s = charBuffer.toString();
charBuffer.setLength(0);
acceptCharacters = false;
return s;
}
////////////////////////////////////////////////////////////////////
// Default implementation of the EntityResolver interface.
////////////////////////////////////////////////////////////////////
/**
* Resolve an external entity.
*
* <p>Always return null, so that the parser will use the system
* identifier provided in the XML document. This method implements
* the SAX default behaviour: application writers can override it
* in a subclass to do special translations such as catalog lookups
* or URI redirection.</p>
*
* @param publicId The public identifier, or null if none is
* available.
* @param systemId The system identifier provided in the XML
* document.
* @return The new input source, or null to require the
* default behaviour.
* @exception java.io.IOException If there is an error setting
* up the new input source.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.EntityResolver#resolveEntity
*/
public InputSource resolveEntity(String publicId, String systemId)
throws IOException, SAXException {
return null;
}
////////////////////////////////////////////////////////////////////
// Default implementation of DTDHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive notification of a notation declaration.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass if they wish to keep track of the notations
* declared in a document.</p>
*
* @param name The notation name.
* @param publicId The notation public identifier, or null if not
* available.
* @param systemId The notation system identifier.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.DTDHandler#notationDecl
*/
public void notationDecl(String name, String publicId, String systemId)
throws SAXException {
// int x = 0;
}
/**
* Receive notification of an unparsed entity declaration.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to keep track of the unparsed entities
* declared in a document.</p>
*
* @param name The entity name.
* @param publicId The entity public identifier, or null if not
* available.
* @param systemId The entity system identifier.
* @param notationName The name of the associated notation.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notationName)
throws SAXException {
// int x = 0;
}
////////////////////////////////////////////////////////////////////
// Default implementation of ContentHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive a Locator object for document events.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass if they wish to store the locator for use
* with other document events.</p>
*
* @param locator A locator for all SAX document events.
* @see org.xml.sax.ContentHandler#setDocumentLocator
* @see org.xml.sax.Locator
*/
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
private void printLocator() {
System.out.println("publicId=" + locator.getPublicId() + " systemId=" + locator.getSystemId() +
" line=" + locator.getLineNumber() + " column=" + locator.getColumnNumber());
}
/**
* Receive notification of the beginning of the document.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the beginning
* of a document (such as allocating the root node of a tree or
* creating an output file).</p>
*
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startDocument
*/
public void startDocument()
throws SAXException {
if (DEBUG) {
System.out.println("startDocument");
}
}
/**
* Receive notification of the end of the document.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end
* of a document (such as finalising a tree or closing an output
* file).</p>
*
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endDocument
*/
public void endDocument()
throws SAXException {
if (DEBUG) {
System.out.println("endDocument");
}
}
/**
* Receive notification of the start of a Namespace mapping.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the start of
* each Namespace prefix scope (such as storing the prefix mapping).</p>
*
* @param prefix The Namespace prefix being declared.
* @param uri The Namespace URI mapped to the prefix.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startPrefixMapping
*/
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
if (DEBUG) {
System.out.println("startPrefixMapping prefix=" + prefix + " uri=" + uri);
}
}
/**
* Receive notification of the end of a Namespace mapping.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end of
* each prefix mapping.</p>
*
* @param prefix The Namespace prefix being declared.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endPrefixMapping
*/
public void endPrefixMapping(String prefix)
throws SAXException {
if (DEBUG) {
System.out.println("endPrefixMapping prefix=" + prefix);
}
}
/**
* Receive notification of the start of an element.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the start of
* each element (such as allocating a new tree node or writing
* output to a file).</p>
*
* @param uri The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace
* processing is not being performed.
* @param localName The local name (without prefix), or the
* empty string if Namespace processing is not being
* performed.
* @param qName The qualified name (with prefix), or the
* empty string if qualified names are not available.
* @param attributes The attributes attached to the element. If
* there are no attributes, it shall be an empty
* Attributes object.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startElement
*/
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
boolean dump = false;
XmlKeyword key = xmlKeywords.get(localName);
// System.out.print("<" + key.name());
this.attributes = attributes;
switch (key) {
case technology:
tech.techName = a("name");
tech.className = a_("class");
if (tech.className != null)
{
int index = tech.className.indexOf(".");
String realName = tech.className;
while (index != -1)
{
realName = realName.substring(index+1);
index = realName.indexOf(".");
}
if (!realName.toLowerCase().equals(tech.techName.toLowerCase()))
System.out.println("Mismatch between techName '" + tech.techName +
"' and className '" + realName + "' in the XML technology file.");
}
// dump = true;
break;
case version:
Version localVersion = new Version();
localVersion.techVersion = Integer.parseInt(a("tech"));
localVersion.electricVersion = com.sun.electric.database.text.Version.parseVersion(a("electric"));
tech.versions.add(localVersion);
break;
case numMetals:
tech.minNumMetals = Integer.parseInt(a("min"));
tech.maxNumMetals = Integer.parseInt(a("max"));
tech.defaultNumMetals = Integer.parseInt(a("default"));
break;
case scale:
tech.scaleValue = Double.parseDouble(a("value"));
tech.scaleRelevant = Boolean.parseBoolean(a("relevant"));
break;
case resolution:
tech.resolutionValue = Double.parseDouble(a("value")); // default is 0;
break;
case defaultFoundry:
tech.defaultFoundry = a("value");
break;
case minResistance:
tech.minResistance = Double.parseDouble(a("value"));
break;
case minCapacitance:
tech.minCapacitance = Double.parseDouble(a("value"));
break;
case logicalEffort:
tech.leGateCapacitance = Double.parseDouble(a("gateCapacitance"));
tech.leWireRatio = Double.parseDouble(a("wireRatio"));
tech.leDiffAlpha = Double.parseDouble(a("diffAlpha"));
break;
case transparentLayer:
curTransparent = Integer.parseInt(a("transparent"));
curR = curG = curB = 0;
break;
case layer:
curLayer = new Layer();
curLayer.name = a("name");
curLayer.function = com.sun.electric.technology.Layer.Function.valueOf(a("fun"));
String extraFunStr = a_("extraFun");
if (extraFunStr != null) {
if (extraFunStr.equals("depletion_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("depletion_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.LIGHT;
else if (extraFunStr.equals("enhancement_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("enhancement_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.LIGHT;
else
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.parseExtraName(extraFunStr);
}
curTransparent = 0;
curR = curG = curB = 0;
patternedOnDisplay = false;
patternedOnPrinter = false;
Arrays.fill(pattern, 0);
curPatternIndex = 0;
transparencyMode = EGraphics.DEFAULT_MODE;
transparencyFactor = EGraphics.DEFAULT_FACTOR;
// EGraphics.Outline outline = null;
break;
case transparentColor:
curTransparent = Integer.parseInt(a("transparent"));
if (curTransparent > 0) {
Color color = tech.transparentLayers.get(curTransparent - 1);
curR = color.getRed();
curG = color.getGreen();
curB = color.getBlue();
}
break;
case opaqueColor:
curR = Integer.parseInt(a("r"));
curG = Integer.parseInt(a("g"));
curB = Integer.parseInt(a("b"));
break;
case display3D:
curLayer.thick3D = Double.parseDouble(a("thick"));
curLayer.height3D = Double.parseDouble(a("height"));
String modeStr = a_("mode");
if (modeStr != null)
transparencyMode = EGraphics.J3DTransparencyOption.valueOf(modeStr);
String factorStr = a_("factor");
if (factorStr != null)
transparencyFactor = Double.parseDouble(factorStr);
break;
case cifLayer:
curLayer.cif = a("cif");
break;
case skillLayer:
curLayer.skill = a("skill");
break;
case parasitics:
curLayer.resistance = Double.parseDouble(a("resistance"));
curLayer.capacitance = Double.parseDouble(a("capacitance"));
curLayer.edgeCapacitance = Double.parseDouble(a("edgeCapacitance"));
break;
case pureLayerNode:
curLayer.pureLayerNode = new PureLayerNode();
curLayer.pureLayerNode.name = a("name");
String styleStr = a_("style");
curLayer.pureLayerNode.style = styleStr != null ? Poly.Type.valueOf(styleStr) : Poly.Type.FILLED;
curLayer.pureLayerNode.port = a("port");
curDistance = curLayer.pureLayerNode.size;
+ Xml.PrimitiveNode n = new Xml.PrimitiveNode();
+ n.name = curLayer.pureLayerNode.name;
+ n.function = com.sun.electric.technology.PrimitiveNode.Function.NODE;
+ tech.pureLayerNodes.add(n);
break;
case arcProto:
curArc = new ArcProto();
curArc.name = a("name");
curArc.function = com.sun.electric.technology.ArcProto.Function.valueOf(a("fun"));
break;
case wipable:
curArc.wipable = true;
break;
case curvable:
curArc.curvable = true;
break;
case special:
curArc.special = true;
break;
case notUsed:
if (curArc != null)
curArc.notUsed = true;
else if (curNodeGroup != null)
curNodeGroup.notUsed = true;
break;
case skipSizeInPalette:
if (curArc != null)
curArc.skipSizeInPalette = true;
else if (curNodeGroup != null)
curNodeGroup.skipSizeInPalette = true;
break;
case diskOffset:
if (curArc != null)
curArc.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
new Double(Double.parseDouble(a("width"))));
else if (curNodeGroup != null)
curNodeGroup.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
EPoint.fromLambda(Double.parseDouble(a("x")), Double.parseDouble(a("y"))));
break;
case defaultWidth:
if (curArc != null)
curDistance = curArc.defaultWidth;
else if (curNodeGroup != null)
curDistance = curNodeGroup.defaultWidth;
break;
case arcLayer:
ArcLayer arcLayer = new ArcLayer();
arcLayer.layer = a("layer");
curDistance = arcLayer.extend;
arcLayer.style = Poly.Type.valueOf(a("style"));
curArc.arcLayers.add(arcLayer);
break;
case primitiveNodeGroup:
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNode = null;
if (a_("name") != null)
System.out.println("Attribute 'name' in <primitiveNodeGroup> is deprecated");
if (a_("fun") != null)
System.out.println("Attribute 'fun' in <primitiveNodeGroup> is deprecated");
break;
case inNodes:
if (curNodeGroup.isSingleton)
throw new SAXException("<inNodes> can be used only inside <primitiveNodeGroup>");
curNodeLayer.inNodes = new BitSet();
break;
case primitiveNode:
if (curNodeLayer != null) {
assert !curNodeGroup.isSingleton && curNode == null;
String nodeName = a("name");
int i = 0;
while (i < curNodeGroup.nodes.size() && !curNodeGroup.nodes.get(i).name.equals(nodeName))
i++;
if (i >= curNodeGroup.nodes.size())
throw new SAXException("No node "+nodeName+" in group");
curNodeLayer.inNodes.set(i);
} else if (curNodeGroup != null) {
assert !curNodeGroup.isSingleton;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
} else {
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNodeGroup.isSingleton = true;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
}
break;
case shrinkArcs:
curNodeGroup.shrinkArcs = true;
break;
case square:
curNodeGroup.square = true;
break;
case canBeZeroSize:
curNodeGroup.canBeZeroSize = true;
break;
case wipes:
curNodeGroup.wipes = true;
break;
case lockable:
curNodeGroup.lockable = true;
break;
case edgeSelect:
curNodeGroup.edgeSelect = true;
break;
case lowVt:
curNode.lowVt = true;
break;
case highVt:
curNode.highVt = true;
break;
case nativeBit:
curNode.nativeBit = true;
break;
case od18:
curNode.od18 = true;
break;
case od25:
curNode.od25 = true;
break;
case od33:
curNode.od33 = true;
break;
case defaultHeight:
curDistance = curNodeGroup.defaultHeight;
break;
case nodeBase:
curNodeGroupHasNodeBase = true;
break;
case sizeOffset:
curNodeGroup.baseLX.value = Double.parseDouble(a("lx"));
curNodeGroup.baseHX.value = -Double.parseDouble(a("hx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("ly"));
curNodeGroup.baseHY.value = -Double.parseDouble(a("hy"));
break;
case protection:
curNodeGroup.protection = ProtectionType.valueOf(a("location"));
break;
case nodeLayer:
curNodeLayer = new NodeLayer();
curNodeLayer.layer = a("layer");
if (tech.findLayer(curNodeLayer.layer) == null)
{
throw new SAXException("Error: cannot find layer '" + curNodeLayer.layer + "' in primitive node '" +
curNode.name + "'. Skiping this NodeLayer");
}
else
{
curNodeLayer.style = Poly.Type.valueOf(a("style"));
String portNum = a_("portNum");
if (portNum != null)
curNodeLayer.portNum = Integer.parseInt(portNum);
String electrical = a_("electrical");
if (electrical != null) {
if (Boolean.parseBoolean(electrical))
curNodeLayer.inElectricalLayers = true;
else
curNodeLayer.inLayers = true;
} else {
curNodeLayer.inElectricalLayers = curNodeLayer.inLayers = true;
}
}
break;
case box:
if (curNodeLayer != null) {
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
} else if (curPort != null) {
curPort.lx.k = da_("klx", -1);
curPort.hx.k = da_("khx", 1);
curPort.ly.k = da_("kly", -1);
curPort.hy.k = da_("khy", 1);
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.k = curNodeGroup.baseLY.k = -1;
curNodeGroup.baseHX.k = curNodeGroup.baseHY.k = 1;
}
break;
case points:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.POINTS;
break;
case multicutbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.sizex = Double.parseDouble(a("sizex"));
curNodeLayer.sizey = Double.parseDouble(a("sizey"));
curNodeLayer.sep1d = Double.parseDouble(a("sep1d"));
curNodeLayer.sep2d = Double.parseDouble(a("sep2d"));
break;
case serpbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.lWidth = Double.parseDouble(a("lWidth"));
curNodeLayer.rWidth = Double.parseDouble(a("rWidth"));
curNodeLayer.tExtent = Double.parseDouble(a("tExtent"));
curNodeLayer.bExtent = Double.parseDouble(a("bExtent"));
break;
case lambdaBox:
if (curNodeLayer != null) {
curNodeLayer.lx.value = Double.parseDouble(a("klx"));
curNodeLayer.hx.value = Double.parseDouble(a("khx"));
curNodeLayer.ly.value = Double.parseDouble(a("kly"));
curNodeLayer.hy.value = Double.parseDouble(a("khy"));
} else if (curPort != null) {
curPort.lx.value = Double.parseDouble(a("klx"));
curPort.hx.value = Double.parseDouble(a("khx"));
curPort.ly.value = Double.parseDouble(a("kly"));
curPort.hy.value = Double.parseDouble(a("khy"));
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.value = Double.parseDouble(a("klx"));
curNodeGroup.baseHX.value = Double.parseDouble(a("khx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("kly"));
curNodeGroup.baseHY.value = Double.parseDouble(a("khy"));
}
break;
case techPoint:
double xm = Double.parseDouble(a("xm"));
double xa = Double.parseDouble(a("xa"));
double ym = Double.parseDouble(a("ym"));
double ya = Double.parseDouble(a("ya"));
TechPoint p = new TechPoint(new EdgeH(xm, xa), new EdgeV(ym, ya));
if (curNodeLayer != null)
curNodeLayer.techPoints.add(p);
break;
case primitivePort:
curPort = new PrimitivePort();
curPort.name = a("name");
break;
case portAngle:
curPort.portAngle = Integer.parseInt(a("primary"));
curPort.portRange = Integer.parseInt(a("range"));
break;
case polygonal:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.POLYGONAL;
break;
case serpTrans:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.SERPTRANS;
curNodeGroup.specialValues = new double[6];
curSpecialValueIndex = 0;
break;
case minSizeRule:
curNodeGroup.nodeSizeRule = new NodeSizeRule();
curNodeGroup.nodeSizeRule.width = Double.parseDouble(a("width"));
curNodeGroup.nodeSizeRule.height = Double.parseDouble(a("height"));
curNodeGroup.nodeSizeRule.rule = a("rule");
break;
case spiceTemplate:
curNodeGroup.spiceTemplate = a("value");
break;
case spiceHeader:
curSpiceHeader = new SpiceHeader();
curSpiceHeader.level = Integer.parseInt(a("level"));
tech.spiceHeaders.add(curSpiceHeader);
break;
case spiceLine:
curSpiceHeader.spiceLines.add(a("line"));
break;
case menuPalette:
tech.menuPalette = new MenuPalette();
tech.menuPalette.numColumns = Integer.parseInt(a("numColumns"));
break;
case menuBox:
curMenuBox = new ArrayList<Object>();
tech.menuPalette.menuBoxes.add(curMenuBox);
break;
case menuNodeInst:
curMenuNodeInst = new MenuNodeInst();
curMenuNodeInst.protoName = a("protoName");
if (tech.findNode(curMenuNodeInst.protoName) == null)
System.out.println("Warning: cannot find node '" + curMenuNodeInst.protoName + "' for component menu");
curMenuNodeInst.function = com.sun.electric.technology.PrimitiveNode.Function.findType(a("function"));
if (curMenuNodeInst.function == null)
System.out.println("Error: cannot find function '" + a("function") + "' for node '" +
a("protoName" + "'"));
String techBits = a_("techBits");
if (techBits != null)
curMenuNodeInst.techBits = Integer.parseInt(techBits);
String rotField = a_("rotation");
if (rotField != null) curMenuNodeInst.rotation = Integer.parseInt(rotField);
break;
case menuNodeText:
curMenuNodeInst.text = a("text");
// curMenuNodeInst.fontSize = Double.parseDouble(a("size"));
break;
case Foundry:
curFoundry = new Foundry();
curFoundry.name = a("name");
tech.foundries.add(curFoundry);
break;
case layerGds:
curFoundry.layerGds.put(a("layer"), a("gds"));
break;
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
if (curLayerNamesList == null)
curLayerNamesList = tech.getLayerNames();
if (curNodeNamesList == null)
curNodeNamesList = tech.getNodeNames();
if (!DRCTemplate.parseXmlElement(curFoundry.rules, curLayerNamesList, curNodeNamesList,
key.name(), attributes, localName))
System.out.println("Warning: cannot find layer name in DRC rule '" + key.name());
break;
default:
assert key.hasText;
beginCharacters();
// System.out.print(">");
return;
}
assert !key.hasText;
// System.out.println(">");
if (dump) {
System.out.println("startElement uri=" + uri + " localName=" + localName + " qName=" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println("\tattribute " + i + " uri=" + attributes.getURI(i) +
" localName=" + attributes.getLocalName(i) + " QName=" + attributes.getQName(i) +
" type=" + attributes.getType(i) + " value=<" + attributes.getValue(i) + ">");
}
}
}
private double da_(String attrName, double defaultValue) {
String s = a_(attrName);
return s != null ? Double.parseDouble(s) : defaultValue;
}
private String a(String attrName) {
String v = attributes.getValue(attrName);
// System.out.print(" " + attrName + "=\"" + v + "\"");
return v;
}
private String a_(String attrName) {
String v = attributes.getValue(attrName);
if (v == null) return null;
// System.out.print(" " + attrName + "=\"" + v + "\"");
return v;
}
/**
* Receive notification of the end of an element.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end of
* each element (such as finalising a tree node or writing
* output to a file).</p>
*
* @param uri The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace
* processing is not being performed.
* @param localName The local name (without prefix), or the
* empty string if Namespace processing is not being
* performed.
* @param qName The qualified name (with prefix), or the
* empty string if qualified names are not available.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endElement
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
XmlKeyword key = xmlKeywords.get(localName);
if (key.hasText) {
String text = endCharacters();
// System.out.println(text + "</" + localName + ">");
switch (key) {
case shortName:
tech.shortTechName = text;
break;
case description:
tech.description = text;
break;
case r:
curR = Integer.parseInt(text);
break;
case g:
curG = Integer.parseInt(text);
break;
case b:
curB = Integer.parseInt(text);
break;
case patternedOnDisplay:
patternedOnDisplay = Boolean.parseBoolean(text);
break;
case patternedOnPrinter:
patternedOnPrinter = Boolean.parseBoolean(text);
break;
case pattern:
int p = 0;
assert text.length() == 16;
for (int j = 0; j < text.length(); j++) {
if (text.charAt(text.length() - j - 1) != ' ')
p |= (1 << j);
}
pattern[curPatternIndex++] = p;
break;
case outlined:
outline = EGraphics.Outline.valueOf(text);
break;
case opacity:
opacity = Double.parseDouble(text);
break;
case foreground:
foreground = Boolean.parseBoolean(text);
break;
case oldName:
if (curLayer != null) {
curLayer.pureLayerNode.oldName = text;
} else if (curArc != null) {
curArc.oldName = text;
} else {
curNode.oldName = text;
}
break;
case extended:
curArc.extended = Boolean.parseBoolean(text);
break;
case fixedAngle:
curArc.fixedAngle = Boolean.parseBoolean(text);
break;
// case wipable:
// curArc.wipable = Boolean.parseBoolean(text);
// break;
case angleIncrement:
curArc.angleIncrement = Integer.parseInt(text);
break;
case antennaRatio:
curArc.antennaRatio = Double.parseDouble(text);
break;
case portTopology:
curPort.portTopology = Integer.parseInt(text);
break;
case portArc:
if (curLayer != null && curLayer.pureLayerNode != null)
curLayer.pureLayerNode.portArcs.add(text);
if (curPort != null)
curPort.portArcs.add(text);
break;
case specialValue:
curNodeGroup.specialValues[curSpecialValueIndex++] = Double.parseDouble(text);
break;
case menuArc:
ArcProto ap = tech.findArc(text);
if (ap == null) System.out.println("Warning: cannot find arc '" + text + "' for component menu"); else
curMenuBox.add(ap);
break;
case menuNode:
PrimitiveNode np = tech.findNode(text);
if (np == null)
System.out.println("Warning: cannot find node '" + text + "' for component menu"); else
curMenuBox.add(np);
break;
case menuText:
curMenuBox.add(text);
break;
case lambda:
curDistance.addLambda(Double.parseDouble(text));
break;
default:
assert false;
}
return;
}
// System.out.println("</" + localName + ">");
switch (key) {
case technology:
break;
case transparentLayer:
while (curTransparent > tech.transparentLayers.size())
tech.transparentLayers.add(null);
Color oldColor = tech.transparentLayers.set(curTransparent - 1, new Color(curR, curG, curB));
assert oldColor == null;
break;
case layer:
assert curPatternIndex == pattern.length;
curLayer.desc = new EGraphics(patternedOnDisplay, patternedOnPrinter, outline, curTransparent,
curR, curG, curB, opacity, foreground, pattern.clone(), transparencyMode, transparencyFactor);
assert tech.findLayer(curLayer.name) == null;
tech.layers.add(curLayer);
curLayer = null;
break;
case arcProto:
tech.arcs.add(curArc);
curArc = null;
break;
case primitiveNodeGroup:
fixNodeBase();
tech.nodeGroups.add(curNodeGroup);
curNodeGroup = null;
curNode = null;
break;
case primitiveNode:
if (curNodeGroup.isSingleton) {
fixNodeBase();
tech.nodeGroups.add(curNodeGroup);
curNodeGroup = null;
curNode = null;
} else if (curNodeLayer == null) {
assert !curNodeGroup.isSingleton;
curNode = null;
}
break;
case nodeLayer:
if (curNodeLayer != null)
{
curNodeGroup.nodeLayers.add(curNodeLayer);
curNodeLayer = null;
}
break;
case primitivePort:
curNodeGroup.ports.add(curPort);
curPort = null;
break;
case menuNodeInst:
curMenuBox.add(curMenuNodeInst);
curMenuNodeInst = null;
break;
case version:
case spiceHeader:
case numMetals:
case scale:
case resolution:
case defaultFoundry:
case minResistance:
case minCapacitance:
case logicalEffort:
case transparentColor:
case opaqueColor:
case display3D:
case cifLayer:
case skillLayer:
case parasitics:
case pureLayerNode:
case wipable:
case curvable:
case special:
case notUsed:
case skipSizeInPalette:
case diskOffset:
case defaultWidth:
case arcLayer:
case inNodes:
case shrinkArcs:
case square:
case canBeZeroSize:
case wipes:
case lockable:
case edgeSelect:
case lowVt:
case highVt:
case nativeBit:
case od18:
case od25:
case od33:
case defaultHeight:
case nodeBase:
case sizeOffset:
case protection:
case box:
case points:
case multicutbox:
case serpbox:
case lambdaBox:
case techPoint:
case portAngle:
case polygonal:
case serpTrans:
case minSizeRule:
case spiceLine:
case spiceTemplate:
case menuPalette:
case menuBox:
case menuNodeText:
case Foundry:
case layerGds:
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
break;
default:
assert false;
}
}
private void fixNodeBase() {
if (curNodeGroupHasNodeBase) return;
double lx, hx, ly, hy;
if (curNodeGroup.nodeSizeRule != null) {
hx = 0.5*curNodeGroup.nodeSizeRule.width;
lx = -hx;
hy = 0.5*curNodeGroup.nodeSizeRule.height;
ly = -hy;
} else {
lx = Double.POSITIVE_INFINITY;
hx = Double.NEGATIVE_INFINITY;
ly = Double.POSITIVE_INFINITY;
hy = Double.NEGATIVE_INFINITY;
for (int i = 0; i < curNodeGroup.nodeLayers.size(); i++) {
Xml.NodeLayer nl = curNodeGroup.nodeLayers.get(i);
double x, y;
if (nl.representation == com.sun.electric.technology.Technology.NodeLayer.BOX || nl.representation == com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX) {
x = nl.lx.value;
lx = Math.min(lx, x);
hx = Math.max(hx, x);
x = nl.hx.value;
lx = Math.min(lx, x);
hx = Math.max(hx, x);
y = nl.ly.value;
ly = Math.min(ly, y);
hy = Math.max(hy, y);
y = nl.hy.value;
ly = Math.min(ly, y);
hy = Math.max(hy, y);
} else {
for (com.sun.electric.technology.Technology.TechPoint p: nl.techPoints) {
x = p.getX().getAdder();
lx = Math.min(lx, x);
hx = Math.max(hx, x);
y = p.getY().getAdder();
ly = Math.min(ly, y);
hy = Math.max(hy, y);
}
}
}
}
curNodeGroup.baseLX.value = DBMath.round(lx + curNodeGroup.baseLX.value);
curNodeGroup.baseHX.value = DBMath.round(hx + curNodeGroup.baseHX.value);
curNodeGroup.baseLY.value = DBMath.round(ly + curNodeGroup.baseLY.value);
curNodeGroup.baseHY.value = DBMath.round(hy + curNodeGroup.baseHY.value);
}
/**
* Receive notification of character data inside an element.
*
* <p>By default, do nothing. Application writers may override this
* method to take specific actions for each chunk of character data
* (such as adding the data to a node or buffer, or printing it to
* a file).</p>
*
* @param ch The characters.
* @param start The start position in the character array.
* @param length The number of characters to use from the
* character array.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#characters
*/
public void characters(char ch[], int start, int length)
throws SAXException {
if (acceptCharacters) {
charBuffer.append(ch, start, length);
} else {
boolean nonBlank = false;
for (int i = 0; i < length; i++) {
char c = ch[start + i];
nonBlank = nonBlank || c != ' ' && c != '\n' && c != '\t';
}
if (nonBlank) {
System.out.print("characters size=" + ch.length + " start=" + start + " length=" + length + " {");
for (int i = 0; i < length; i++)
System.out.print(ch[start + i]);
System.out.println("}");
}
}
}
/**
* Receive notification of ignorable whitespace in element content.
*
* <p>By default, do nothing. Application writers may override this
* method to take specific actions for each chunk of ignorable
* whitespace (such as adding data to a node or buffer, or printing
* it to a file).</p>
*
* @param ch The whitespace characters.
* @param start The start position in the character array.
* @param length The number of characters to use from the
* character array.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#ignorableWhitespace
*/
public void ignorableWhitespace(char ch[], int start, int length)
throws SAXException {
// int x = 0;
}
/**
* Receive notification of a processing instruction.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions for each
* processing instruction, such as setting status variables or
* invoking other methods.</p>
*
* @param target The processing instruction target.
* @param data The processing instruction data, or null if
* none is supplied.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#processingInstruction
*/
public void processingInstruction(String target, String data)
throws SAXException {
// int x = 0;
}
/**
* Receive notification of a skipped entity.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions for each
* processing instruction, such as setting status variables or
* invoking other methods.</p>
*
* @param name The name of the skipped entity.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#processingInstruction
*/
public void skippedEntity(String name)
throws SAXException {
// int x = 0;
}
////////////////////////////////////////////////////////////////////
// Default implementation of the ErrorHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive notification of a parser warning.
*
* <p>The default implementation does nothing. Application writers
* may override this method in a subclass to take specific actions
* for each warning, such as inserting the message in a log file or
* printing it to the console.</p>
*
* @param e The warning information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#warning
* @see org.xml.sax.SAXParseException
*/
public void warning(SAXParseException e)
throws SAXException {
System.out.println("warning publicId=" + e.getPublicId() + " systemId=" + e.getSystemId() +
" line=" + e.getLineNumber() + " column=" + e.getColumnNumber() + " message=" + e.getMessage() + " exception=" + e.getException());
}
/**
* Receive notification of a recoverable parser error.
*
* <p>The default implementation does nothing. Application writers
* may override this method in a subclass to take specific actions
* for each error, such as inserting the message in a log file or
* printing it to the console.</p>
*
* @param e The error information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#warning
* @see org.xml.sax.SAXParseException
*/
public void error(SAXParseException e)
throws SAXException {
// System.out.println("error publicId=" + e.getPublicId() + " systemId=" + e.getSystemId() +
// " line=" + e.getLineNumber() + " column=" + e.getColumnNumber() + " message=" + e.getMessage() + " exception=" + e.getException());
throw e;
}
/**
* Report a fatal XML parsing error.
*
* <p>The default implementation throws a SAXParseException.
* Application writers may override this method in a subclass if
* they need to take specific actions for each fatal error (such as
* collecting all of the errors into a single report): in any case,
* the application must stop all regular processing when this
* method is invoked, since the document is no longer reliable, and
* the parser may no longer report parsing events.</p>
*
* @param e The error information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#fatalError
* @see org.xml.sax.SAXParseException
*/
public void fatalError(SAXParseException e)
throws SAXException {
// System.out.println("fatal error publicId=" + e.getPublicId() + " systemId=" + e.getSystemId() +
// " line=" + e.getLineNumber() + " column=" + e.getColumnNumber() + " message=" + e.getMessage() + " exception=" + e.getException());
throw e;
}
}
private static class Writer {
private static final int INDENT_WIDTH = 4;
protected final PrintWriter out;
private int indent;
protected boolean indentEmitted;
private Writer(PrintWriter out) {
this.out = out;
}
private void writeTechnology(Xml.Technology t, boolean includeDateAndVersion, String copyrightMessage) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
header();
pl("");
out.println("<!--");
pl(" *");
if (includeDateAndVersion)
{
pl(" * Electric(tm) VLSI Design System, version " + com.sun.electric.database.text.Version.getVersion());
} else
{
pl(" * Electric(tm) VLSI Design System");
}
pl(" *");
pl(" * File: " + t.techName + ".xml");
pl(" * " + t.techName + " technology description");
pl(" * Generated automatically from a library");
pl(" *");
if (copyrightMessage != null)
{
int start = 0;
while (start < copyrightMessage.length())
{
int endPos = copyrightMessage.indexOf('\n', start);
if (endPos < 0) endPos = copyrightMessage.length();
String oneLine = copyrightMessage.substring(start, endPos);
pl(" * " + oneLine);
start = endPos+1;
}
}
out.println("-->");
l();
b(XmlKeyword.technology); a("name", t.techName); a("class", t.className); l();
a("xmlns", "http://electric.sun.com/Technology"); l();
a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); l();
a("xsi:schemaLocation", "http://electric.sun.com/Technology ../../technology/Technology.xsd"); cl();
l();
bcpel(XmlKeyword.shortName, t.shortTechName);
bcpel(XmlKeyword.description, t.description);
for (Version version: t.versions) {
b(XmlKeyword.version); a("tech", version.techVersion); a("electric", version.electricVersion); el();
}
b(XmlKeyword.numMetals); a("min", t.minNumMetals); a("max", t.maxNumMetals); a("default", t.defaultNumMetals); el();
b(XmlKeyword.scale); a("value", t.scaleValue); a("relevant", Boolean.valueOf(t.scaleRelevant)); el();
b(XmlKeyword.resolution); a("value", t.resolutionValue); el();
b(XmlKeyword.defaultFoundry); a("value", t.defaultFoundry); el();
b(XmlKeyword.minResistance); a("value", t.minResistance); el();
b(XmlKeyword.minCapacitance); a("value", t.minCapacitance); el();
if (t.leGateCapacitance != DEFAULT_LE_GATECAP || t.leWireRatio != DEFAULT_LE_WIRERATIO || t.leDiffAlpha != DEFAULT_LE_DIFFALPHA) {
b(XmlKeyword.logicalEffort);
a("gateCapacitance", t.leGateCapacitance);
a("wireRatio", t.leWireRatio);
a("diffAlpha", t.leDiffAlpha);
el();
}
// printlnAttribute(" gateLengthSubtraction", gi.gateShrinkage);
// printlnAttribute(" gateInclusion", gi.includeGateInResistance);
// printlnAttribute(" groundNetInclusion", gi.includeGround);
l();
if (t.transparentLayers.size() != 0) {
comment("Transparent layers");
for (int i = 0; i < t.transparentLayers.size(); i++) {
Color color = t.transparentLayers.get(i);
b(XmlKeyword.transparentLayer); a("transparent", i + 1); cl();
bcpel(XmlKeyword.r, color.getRed());
bcpel(XmlKeyword.g, color.getGreen());
bcpel(XmlKeyword.b, color.getBlue());
el(XmlKeyword.transparentLayer);
}
l();
}
comment("**************************************** LAYERS ****************************************");
for (Xml.Layer li: t.layers) {
writeXml(li);
}
comment("******************** ARCS ********************");
for (Xml.ArcProto ai: t.arcs) {
writeXml(ai);
l();
}
comment("******************** NODES ********************");
for (Xml.PrimitiveNodeGroup nodeGroup: t.nodeGroups) {
writeXml(nodeGroup);
l();
}
for (Xml.SpiceHeader spiceHeader: t.spiceHeaders)
writeSpiceHeaderXml(spiceHeader);
writeMenuPaletteXml(t.menuPalette);
for (Xml.Foundry foundry: t.foundries)
writeFoundryXml(foundry);
el(XmlKeyword.technology);
}
private void writeXml(Xml.Layer li) {
EGraphics desc = li.desc;
String funString = null;
int funExtra = li.extraFunction;
if (funExtra != 0) {
final int deplEnhMask = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.ENHANCEMENT;
if ((funExtra&deplEnhMask) != 0) {
funString = com.sun.electric.technology.Layer.Function.getExtraName(funExtra&(deplEnhMask));
funExtra &= ~deplEnhMask;
if (funExtra != 0)
funString += "_" + com.sun.electric.technology.Layer.Function.getExtraName(funExtra);
} else {
funString = com.sun.electric.technology.Layer.Function.getExtraName(funExtra);
}
}
b(XmlKeyword.layer); a("name", li.name); a("fun", li.function.name()); a("extraFun", funString); cl();
if (desc.getTransparentLayer() > 0) {
b(XmlKeyword.transparentColor); a("transparent", desc.getTransparentLayer()); el();
} else {
Color color = desc.getColor();
b(XmlKeyword.opaqueColor); a("r", color.getRed()); a("g", color.getGreen()); a("b", color.getBlue()); el();
}
bcpel(XmlKeyword.patternedOnDisplay, Boolean.valueOf(desc.isPatternedOnDisplay()));
bcpel(XmlKeyword.patternedOnPrinter, Boolean.valueOf(desc.isPatternedOnPrinter()));
int [] pattern = desc.getPattern();
for(int j=0; j<16; j++) {
String p = "";
for(int k=0; k<16; k++)
p += (pattern[j] & (1 << (15-k))) != 0 ? 'X' : ' ';
bcpel(XmlKeyword.pattern, p);
}
if (li.desc.getOutlined() != null)
bcpel(XmlKeyword.outlined, desc.getOutlined().getConstName());
bcpel(XmlKeyword.opacity, desc.getOpacity());
bcpel(XmlKeyword.foreground, Boolean.valueOf(desc.getForeground()));
// write the 3D information
b(XmlKeyword.display3D);
a("thick", li.thick3D); a("height", li.height3D);
a("mode", li.desc.getTransparencyMode());
a("factor", li.desc.getTransparencyFactor());
el();
if (li.cif != null && li.cif.length() > 0) {
b(XmlKeyword.cifLayer); a("cif", li.cif); el();
}
if (li.skill != null && li.skill.length() > 0) {
b(XmlKeyword.skillLayer); a("skill", li.skill); el();
}
// write the SPICE information
if (li.resistance != 0 || li.capacitance != 0 || li.edgeCapacitance != 0) {
b(XmlKeyword.parasitics); a("resistance", li.resistance); a("capacitance", li.capacitance); a("edgeCapacitance", li.edgeCapacitance); el();
}
if (li.pureLayerNode != null) {
String nodeName = li.pureLayerNode.name;
Poly.Type style = li.pureLayerNode.style;
String styleStr = style == Poly.Type.FILLED ? null : style.name();
String portName = li.pureLayerNode.port;
b(XmlKeyword.pureLayerNode); a("name", nodeName); a("style", styleStr); a("port", portName); cl();
bcpel(XmlKeyword.oldName, li.pureLayerNode.oldName);
bcpel(XmlKeyword.lambda, li.pureLayerNode.size.value);
for (String portArc: li.pureLayerNode.portArcs)
bcpel(XmlKeyword.portArc, portArc);
el(XmlKeyword.pureLayerNode);
}
el(XmlKeyword.layer);
l();
}
private void writeXml(Xml.ArcProto ai) {
b(XmlKeyword.arcProto); a("name", ai.name); a("fun", ai.function.getConstantName()); cl();
bcpel(XmlKeyword.oldName, ai.oldName);
if (ai.wipable)
bel(XmlKeyword.wipable);
if (ai.curvable)
bel(XmlKeyword.curvable);
if (ai.special)
bel(XmlKeyword.special);
if (ai.notUsed)
bel(XmlKeyword.notUsed);
if (ai.skipSizeInPalette)
bel(XmlKeyword.skipSizeInPalette);
bcpel(XmlKeyword.extended, Boolean.valueOf(ai.extended));
bcpel(XmlKeyword.fixedAngle, Boolean.valueOf(ai.fixedAngle));
bcpel(XmlKeyword.angleIncrement, ai.angleIncrement);
if (ai.antennaRatio != 0)
bcpel(XmlKeyword.antennaRatio, ai.antennaRatio);
for (Map.Entry<Integer,Double> e: ai.diskOffset.entrySet()) {
b(XmlKeyword.diskOffset); a("untilVersion", e.getKey()); a("width", e.getValue()); el();
}
if (ai.defaultWidth.value != 0) {
bcl(XmlKeyword.defaultWidth);
bcpel(XmlKeyword.lambda, ai.defaultWidth.value);
el(XmlKeyword.defaultWidth);
}
for (Xml.ArcLayer al: ai.arcLayers) {
String style = al.style == Poly.Type.FILLED ? "FILLED" : "CLOSED";
b(XmlKeyword.arcLayer); a("layer", al.layer); a("style", style);
double extend = al.extend.value;
if (extend == 0) {
el();
} else {
cl();
bcpel(XmlKeyword.lambda, extend);
el(XmlKeyword.arcLayer);
}
}
el(XmlKeyword.arcProto);
}
private void writeXml(Xml.PrimitiveNodeGroup ng) {
if (ng.isSingleton) {
PrimitiveNode n = ng.nodes.get(0);
b(XmlKeyword.primitiveNode); a("name", n.name); a("fun", n.function.name()); cl();
bcpel(XmlKeyword.oldName, n.oldName);
} else {
bcl(XmlKeyword.primitiveNodeGroup);
for (PrimitiveNode n: ng.nodes) {
b(XmlKeyword.primitiveNode); a("name", n.name); a("fun", n.function.name());
if (n.oldName != null || n.highVt || n.lowVt || n.nativeBit || n.od18 || n.od25 || n.od33) {
cl();
bcpel(XmlKeyword.oldName, n.oldName);
if (n.lowVt)
bel(XmlKeyword.lowVt);
if (n.highVt)
bel(XmlKeyword.highVt);
if (n.nativeBit)
bel(XmlKeyword.nativeBit);
if (n.od18)
bel(XmlKeyword.od18);
if (n.od25)
bel(XmlKeyword.od25);
if (n.od33)
bel(XmlKeyword.od33);
el(XmlKeyword.primitiveNode);
} else {
el();
}
}
}
if (ng.shrinkArcs)
bel(XmlKeyword.shrinkArcs);
if (ng.square)
bel(XmlKeyword.square);
if (ng.canBeZeroSize)
bel(XmlKeyword.canBeZeroSize);
if (ng.wipes)
bel(XmlKeyword.wipes);
if (ng.lockable)
bel(XmlKeyword.lockable);
if (ng.edgeSelect)
bel(XmlKeyword.edgeSelect);
if (ng.skipSizeInPalette)
bel(XmlKeyword.skipSizeInPalette);
if (ng.notUsed)
bel(XmlKeyword.notUsed);
if (ng.isSingleton) {
PrimitiveNode n = ng.nodes.get(0);
if (n.lowVt)
bel(XmlKeyword.lowVt);
if (n.highVt)
bel(XmlKeyword.highVt);
if (n.nativeBit)
bel(XmlKeyword.nativeBit);
if (n.od18)
bel(XmlKeyword.od18);
if (n.od25)
bel(XmlKeyword.od25);
if (n.od33)
bel(XmlKeyword.od33);
}
for (Map.Entry<Integer,EPoint> e: ng.diskOffset.entrySet()) {
EPoint p = e.getValue();
b(XmlKeyword.diskOffset); a("untilVersion", e.getKey()); a("x", p.getLambdaX()); a("y", p.getLambdaY()); el();
}
if (ng.defaultWidth.value != 0) {
bcl(XmlKeyword.defaultWidth);
bcpel(XmlKeyword.lambda, ng.defaultWidth.value);
el(XmlKeyword.defaultWidth);
}
if (ng.defaultHeight.value != 0) {
bcl(XmlKeyword.defaultHeight);
bcpel(XmlKeyword.lambda, ng.defaultHeight.value);
el(XmlKeyword.defaultHeight);
}
bcl(XmlKeyword.nodeBase);
bcl(XmlKeyword.box);
b(XmlKeyword.lambdaBox); a("klx", ng.baseLX.value); a("khx", ng.baseHX.value); a("kly", ng.baseLY.value); a("khy", ng.baseHY.value); el();
el(XmlKeyword.box);
el(XmlKeyword.nodeBase);
if (ng.protection != null) {
b(XmlKeyword.protection); a("location", ng.protection); el();
}
for(int j=0; j<ng.nodeLayers.size(); j++) {
Xml.NodeLayer nl = ng.nodeLayers.get(j);
b(XmlKeyword.nodeLayer); a("layer", nl.layer); a("style", nl.style.name());
if (nl.portNum != 0) a("portNum", Integer.valueOf(nl.portNum));
if (!(nl.inLayers && nl.inElectricalLayers))
a("electrical", Boolean.valueOf(nl.inElectricalLayers));
cl();
if (nl.inNodes != null) {
assert !ng.isSingleton;
bcl(XmlKeyword.inNodes);
for (int i = 0; i < ng.nodes.size(); i++) {
if (nl.inNodes.get(i)) {
b(XmlKeyword.primitiveNode); a("name", ng.nodes.get(i).name); el();
}
}
el(XmlKeyword.inNodes);
}
switch (nl.representation) {
case com.sun.electric.technology.Technology.NodeLayer.BOX:
if (ng.specialType == com.sun.electric.technology.PrimitiveNode.SERPTRANS) {
writeBox(XmlKeyword.serpbox, nl.lx, nl.hx, nl.ly, nl.hy);
a("lWidth", nl.lWidth); a("rWidth", nl.rWidth); a("tExtent", nl.tExtent); a("bExtent", nl.bExtent); cl();
b(XmlKeyword.lambdaBox); a("klx", nl.lx.value); a("khx", nl.hx.value); a("kly", nl.ly.value); a("khy", nl.hy.value); el();
el(XmlKeyword.serpbox);
} else {
writeBox(XmlKeyword.box, nl.lx, nl.hx, nl.ly, nl.hy); cl();
b(XmlKeyword.lambdaBox); a("klx", nl.lx.value); a("khx", nl.hx.value); a("kly", nl.ly.value); a("khy", nl.hy.value); el();
el(XmlKeyword.box);
}
break;
case com.sun.electric.technology.Technology.NodeLayer.POINTS:
b(XmlKeyword.points); el();
break;
case com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX:
writeBox(XmlKeyword.multicutbox, nl.lx, nl.hx, nl.ly, nl.hy);
a("sizex", nl.sizex); a("sizey", nl.sizey); a("sep1d", nl.sep1d); a("sep2d", nl.sep2d); cl();
b(XmlKeyword.lambdaBox); a("klx", nl.lx.value); a("khx", nl.hx.value); a("kly", nl.ly.value); a("khy", nl.hy.value); el();
el(XmlKeyword.multicutbox);
break;
}
for (TechPoint tp: nl.techPoints) {
double xm = tp.getX().getMultiplier();
double xa = tp.getX().getAdder();
double ym = tp.getY().getMultiplier();
double ya = tp.getY().getAdder();
b(XmlKeyword.techPoint); a("xm", xm); a("xa", xa); a("ym", ym); a("ya", ya); el();
}
el(XmlKeyword.nodeLayer);
}
for (int j = 0; j < ng.ports.size(); j++) {
Xml.PrimitivePort pd = ng.ports.get(j);
b(XmlKeyword.primitivePort); a("name", pd.name); cl();
b(XmlKeyword.portAngle); a("primary", pd.portAngle); a("range", pd.portRange); el();
bcpel(XmlKeyword.portTopology, pd.portTopology);
writeBox(XmlKeyword.box, pd.lx, pd.hx, pd.ly, pd.hy); cl();
b(XmlKeyword.lambdaBox); a("klx", pd.lx.value); a("khx", pd.hx.value); a("kly", pd.ly.value); a("khy", pd.hy.value); el();
el(XmlKeyword.box);
for (String portArc: pd.portArcs)
bcpel(XmlKeyword.portArc, portArc);
el(XmlKeyword.primitivePort);
}
switch (ng.specialType) {
case com.sun.electric.technology.PrimitiveNode.POLYGONAL:
bel(XmlKeyword.polygonal);
break;
case com.sun.electric.technology.PrimitiveNode.SERPTRANS:
b(XmlKeyword.serpTrans); cl();
for (int i = 0; i < 6; i++) {
bcpel(XmlKeyword.specialValue, ng.specialValues[i]);
}
el(XmlKeyword.serpTrans);
break;
}
if (ng.nodeSizeRule != null) {
NodeSizeRule r = ng.nodeSizeRule;
b(XmlKeyword.minSizeRule); a("width", r.width); a("height", r.height); a("rule", r.rule); el();
}
if (ng.spiceTemplate != null)
{
b(XmlKeyword.spiceTemplate); a("value", ng.spiceTemplate); el();
}
el(ng.isSingleton ? XmlKeyword.primitiveNode : XmlKeyword.primitiveNodeGroup);
}
private void writeBox(XmlKeyword keyword, Distance lx, Distance hx, Distance ly, Distance hy) {
b(keyword);
if (lx.k != -1) a("klx", lx.k);
if (hx.k != 1) a("khx", hx.k);
if (ly.k != -1) a("kly", ly.k);
if (hy.k != 1) a("khy", hy.k);
}
private void writeSpiceHeaderXml(Xml.SpiceHeader spiceHeader) {
b(XmlKeyword.spiceHeader); a("level", spiceHeader.level); cl();
for (String line: spiceHeader.spiceLines) {
b(XmlKeyword.spiceLine); a("line", line); el();
}
el(XmlKeyword.spiceHeader);
l();
}
public void writeMenuPaletteXml(Xml.MenuPalette menuPalette) {
if (menuPalette == null) return;
b(XmlKeyword.menuPalette); a("numColumns", menuPalette.numColumns); cl();
for (int i = 0; i < menuPalette.menuBoxes.size(); i++) {
if (i % menuPalette.numColumns == 0)
l();
writeMenuBoxXml(menuPalette.menuBoxes.get(i));
}
l();
el(XmlKeyword.menuPalette);
l();
}
private void writeMenuBoxXml(List<?> list) {
b(XmlKeyword.menuBox);
if (list == null || list.size() == 0) {
el();
return;
}
cl();
for (Object o: list) {
if (o instanceof Xml.ArcProto) {
bcpel(XmlKeyword.menuArc, ((Xml.ArcProto)o).name);
} else if (o instanceof Xml.PrimitiveNode) {
bcpel(XmlKeyword.menuNode, ((Xml.PrimitiveNode)o).name);
} else if (o instanceof Xml.MenuNodeInst) {
Xml.MenuNodeInst ni = (Xml.MenuNodeInst)o;
b(XmlKeyword.menuNodeInst); a("protoName", ni.protoName); a("function", ni.function.name());
if (ni.techBits != 0) a("techBits", ni.techBits);
if (ni.rotation != 0) a("rotation", ni.rotation);
if (ni.text == null) {
el();
} else {
cl();
b(XmlKeyword.menuNodeText); a("text", ni.text); /*a("size", ni.fontSize);*/ el();
el(XmlKeyword.menuNodeInst);
}
} else {
if (o == null) bel(XmlKeyword.menuText); else
bcpel(XmlKeyword.menuText, o);
}
}
el(XmlKeyword.menuBox);
}
private void writeFoundryXml(Xml.Foundry foundry) {
b(XmlKeyword.Foundry); a("name", foundry.name); cl();
l();
for (Map.Entry<String,String> e: foundry.layerGds.entrySet()) {
b(XmlKeyword.layerGds); a("layer", e.getKey()); a("gds", e.getValue()); el();
}
l();
for (DRCTemplate rule: foundry.rules)
DRCTemplate.exportDRCRule(out, rule);
el(XmlKeyword.Foundry);
}
private void header() {
checkIndent();
out.print("<?xml"); a("version", "1.0"); a("encoding", "UTF-8"); out.println("?>");
}
private void comment(String s) {
checkIndent();
out.print("<!-- "); p(s); out.print(" -->"); l();
}
/**
* Print attribute.
*/
private void a(String name, Object value) {
checkIndent();
if (value == null) return;
out.print(" " + name + "=\"");
p(value.toString());
out.print("\"");
}
private void a(String name, double value) { a(name, new Double(value)); }
private void a(String name, int value) { a(name, new Integer(value)); }
private void bcpel(XmlKeyword key, Object v) {
if (v == null) return;
b(key); c(); p(v.toString()); el(key);
}
private void bcpel(XmlKeyword key, int v) { bcpel(key, new Integer(v)); }
private void bcpel(XmlKeyword key, double v) { bcpel(key, new Double(v)); }
private void bcl(XmlKeyword key) {
b(key); cl();
}
private void bel(XmlKeyword key) {
b(key); el();
}
/**
* Print text with replacement of special chars.
*/
private void pl(String s) {
checkIndent();
p(s); l();
}
/**
* Print text with replacement of special chars.
*/
protected void p(String s) {
assert indentEmitted;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '<':
out.print("<");
break;
case '>':
out.print(">");
break;
case '&':
out.print("&");
break;
case '\'':
out.print("'");
break;
case '"':
out.print("quot;");
break;
default:
out.print(c);
}
}
}
/**
* Print element name, and indent.
*/
private void b(XmlKeyword key) {
checkIndent();
out.print('<');
out.print(key.name());
indent += INDENT_WIDTH;
}
private void cl() {
assert indentEmitted;
out.print('>');
l();
}
private void c() {
assert indentEmitted;
out.print('>');
}
private void el() {
e(); l();
}
private void e() {
assert indentEmitted;
out.print("/>");
indent -= INDENT_WIDTH;
}
private void el(XmlKeyword key) {
indent -= INDENT_WIDTH;
checkIndent();
out.print("</");
out.print(key.name());
out.print(">");
l();
}
protected void checkIndent() {
if (indentEmitted) return;
for (int i = 0; i < indent; i++)
out.print(' ');
indentEmitted = true;
}
/**
* Print new line.
*/
protected void l() {
out.println();
indentEmitted = false;
}
}
/**
* Class to write the XML without multiple lines and indentation.
* Useful when the XML is to be a single string.
*/
private static class OneLineWriter extends Writer
{
private OneLineWriter(PrintWriter out)
{
super(out);
}
/**
* Print text without replacement of special chars.
*/
@Override
protected void p(String s)
{
for (int i = 0; i < s.length(); i++)
out.print(s.charAt(i));
}
@Override
protected void checkIndent() { indentEmitted = true; }
/**
* Do not print new line.
*/
@Override
protected void l() { indentEmitted = false; }
}
}
| true | true | public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
boolean dump = false;
XmlKeyword key = xmlKeywords.get(localName);
// System.out.print("<" + key.name());
this.attributes = attributes;
switch (key) {
case technology:
tech.techName = a("name");
tech.className = a_("class");
if (tech.className != null)
{
int index = tech.className.indexOf(".");
String realName = tech.className;
while (index != -1)
{
realName = realName.substring(index+1);
index = realName.indexOf(".");
}
if (!realName.toLowerCase().equals(tech.techName.toLowerCase()))
System.out.println("Mismatch between techName '" + tech.techName +
"' and className '" + realName + "' in the XML technology file.");
}
// dump = true;
break;
case version:
Version localVersion = new Version();
localVersion.techVersion = Integer.parseInt(a("tech"));
localVersion.electricVersion = com.sun.electric.database.text.Version.parseVersion(a("electric"));
tech.versions.add(localVersion);
break;
case numMetals:
tech.minNumMetals = Integer.parseInt(a("min"));
tech.maxNumMetals = Integer.parseInt(a("max"));
tech.defaultNumMetals = Integer.parseInt(a("default"));
break;
case scale:
tech.scaleValue = Double.parseDouble(a("value"));
tech.scaleRelevant = Boolean.parseBoolean(a("relevant"));
break;
case resolution:
tech.resolutionValue = Double.parseDouble(a("value")); // default is 0;
break;
case defaultFoundry:
tech.defaultFoundry = a("value");
break;
case minResistance:
tech.minResistance = Double.parseDouble(a("value"));
break;
case minCapacitance:
tech.minCapacitance = Double.parseDouble(a("value"));
break;
case logicalEffort:
tech.leGateCapacitance = Double.parseDouble(a("gateCapacitance"));
tech.leWireRatio = Double.parseDouble(a("wireRatio"));
tech.leDiffAlpha = Double.parseDouble(a("diffAlpha"));
break;
case transparentLayer:
curTransparent = Integer.parseInt(a("transparent"));
curR = curG = curB = 0;
break;
case layer:
curLayer = new Layer();
curLayer.name = a("name");
curLayer.function = com.sun.electric.technology.Layer.Function.valueOf(a("fun"));
String extraFunStr = a_("extraFun");
if (extraFunStr != null) {
if (extraFunStr.equals("depletion_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("depletion_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.LIGHT;
else if (extraFunStr.equals("enhancement_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("enhancement_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.LIGHT;
else
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.parseExtraName(extraFunStr);
}
curTransparent = 0;
curR = curG = curB = 0;
patternedOnDisplay = false;
patternedOnPrinter = false;
Arrays.fill(pattern, 0);
curPatternIndex = 0;
transparencyMode = EGraphics.DEFAULT_MODE;
transparencyFactor = EGraphics.DEFAULT_FACTOR;
// EGraphics.Outline outline = null;
break;
case transparentColor:
curTransparent = Integer.parseInt(a("transparent"));
if (curTransparent > 0) {
Color color = tech.transparentLayers.get(curTransparent - 1);
curR = color.getRed();
curG = color.getGreen();
curB = color.getBlue();
}
break;
case opaqueColor:
curR = Integer.parseInt(a("r"));
curG = Integer.parseInt(a("g"));
curB = Integer.parseInt(a("b"));
break;
case display3D:
curLayer.thick3D = Double.parseDouble(a("thick"));
curLayer.height3D = Double.parseDouble(a("height"));
String modeStr = a_("mode");
if (modeStr != null)
transparencyMode = EGraphics.J3DTransparencyOption.valueOf(modeStr);
String factorStr = a_("factor");
if (factorStr != null)
transparencyFactor = Double.parseDouble(factorStr);
break;
case cifLayer:
curLayer.cif = a("cif");
break;
case skillLayer:
curLayer.skill = a("skill");
break;
case parasitics:
curLayer.resistance = Double.parseDouble(a("resistance"));
curLayer.capacitance = Double.parseDouble(a("capacitance"));
curLayer.edgeCapacitance = Double.parseDouble(a("edgeCapacitance"));
break;
case pureLayerNode:
curLayer.pureLayerNode = new PureLayerNode();
curLayer.pureLayerNode.name = a("name");
String styleStr = a_("style");
curLayer.pureLayerNode.style = styleStr != null ? Poly.Type.valueOf(styleStr) : Poly.Type.FILLED;
curLayer.pureLayerNode.port = a("port");
curDistance = curLayer.pureLayerNode.size;
break;
case arcProto:
curArc = new ArcProto();
curArc.name = a("name");
curArc.function = com.sun.electric.technology.ArcProto.Function.valueOf(a("fun"));
break;
case wipable:
curArc.wipable = true;
break;
case curvable:
curArc.curvable = true;
break;
case special:
curArc.special = true;
break;
case notUsed:
if (curArc != null)
curArc.notUsed = true;
else if (curNodeGroup != null)
curNodeGroup.notUsed = true;
break;
case skipSizeInPalette:
if (curArc != null)
curArc.skipSizeInPalette = true;
else if (curNodeGroup != null)
curNodeGroup.skipSizeInPalette = true;
break;
case diskOffset:
if (curArc != null)
curArc.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
new Double(Double.parseDouble(a("width"))));
else if (curNodeGroup != null)
curNodeGroup.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
EPoint.fromLambda(Double.parseDouble(a("x")), Double.parseDouble(a("y"))));
break;
case defaultWidth:
if (curArc != null)
curDistance = curArc.defaultWidth;
else if (curNodeGroup != null)
curDistance = curNodeGroup.defaultWidth;
break;
case arcLayer:
ArcLayer arcLayer = new ArcLayer();
arcLayer.layer = a("layer");
curDistance = arcLayer.extend;
arcLayer.style = Poly.Type.valueOf(a("style"));
curArc.arcLayers.add(arcLayer);
break;
case primitiveNodeGroup:
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNode = null;
if (a_("name") != null)
System.out.println("Attribute 'name' in <primitiveNodeGroup> is deprecated");
if (a_("fun") != null)
System.out.println("Attribute 'fun' in <primitiveNodeGroup> is deprecated");
break;
case inNodes:
if (curNodeGroup.isSingleton)
throw new SAXException("<inNodes> can be used only inside <primitiveNodeGroup>");
curNodeLayer.inNodes = new BitSet();
break;
case primitiveNode:
if (curNodeLayer != null) {
assert !curNodeGroup.isSingleton && curNode == null;
String nodeName = a("name");
int i = 0;
while (i < curNodeGroup.nodes.size() && !curNodeGroup.nodes.get(i).name.equals(nodeName))
i++;
if (i >= curNodeGroup.nodes.size())
throw new SAXException("No node "+nodeName+" in group");
curNodeLayer.inNodes.set(i);
} else if (curNodeGroup != null) {
assert !curNodeGroup.isSingleton;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
} else {
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNodeGroup.isSingleton = true;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
}
break;
case shrinkArcs:
curNodeGroup.shrinkArcs = true;
break;
case square:
curNodeGroup.square = true;
break;
case canBeZeroSize:
curNodeGroup.canBeZeroSize = true;
break;
case wipes:
curNodeGroup.wipes = true;
break;
case lockable:
curNodeGroup.lockable = true;
break;
case edgeSelect:
curNodeGroup.edgeSelect = true;
break;
case lowVt:
curNode.lowVt = true;
break;
case highVt:
curNode.highVt = true;
break;
case nativeBit:
curNode.nativeBit = true;
break;
case od18:
curNode.od18 = true;
break;
case od25:
curNode.od25 = true;
break;
case od33:
curNode.od33 = true;
break;
case defaultHeight:
curDistance = curNodeGroup.defaultHeight;
break;
case nodeBase:
curNodeGroupHasNodeBase = true;
break;
case sizeOffset:
curNodeGroup.baseLX.value = Double.parseDouble(a("lx"));
curNodeGroup.baseHX.value = -Double.parseDouble(a("hx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("ly"));
curNodeGroup.baseHY.value = -Double.parseDouble(a("hy"));
break;
case protection:
curNodeGroup.protection = ProtectionType.valueOf(a("location"));
break;
case nodeLayer:
curNodeLayer = new NodeLayer();
curNodeLayer.layer = a("layer");
if (tech.findLayer(curNodeLayer.layer) == null)
{
throw new SAXException("Error: cannot find layer '" + curNodeLayer.layer + "' in primitive node '" +
curNode.name + "'. Skiping this NodeLayer");
}
else
{
curNodeLayer.style = Poly.Type.valueOf(a("style"));
String portNum = a_("portNum");
if (portNum != null)
curNodeLayer.portNum = Integer.parseInt(portNum);
String electrical = a_("electrical");
if (electrical != null) {
if (Boolean.parseBoolean(electrical))
curNodeLayer.inElectricalLayers = true;
else
curNodeLayer.inLayers = true;
} else {
curNodeLayer.inElectricalLayers = curNodeLayer.inLayers = true;
}
}
break;
case box:
if (curNodeLayer != null) {
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
} else if (curPort != null) {
curPort.lx.k = da_("klx", -1);
curPort.hx.k = da_("khx", 1);
curPort.ly.k = da_("kly", -1);
curPort.hy.k = da_("khy", 1);
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.k = curNodeGroup.baseLY.k = -1;
curNodeGroup.baseHX.k = curNodeGroup.baseHY.k = 1;
}
break;
case points:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.POINTS;
break;
case multicutbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.sizex = Double.parseDouble(a("sizex"));
curNodeLayer.sizey = Double.parseDouble(a("sizey"));
curNodeLayer.sep1d = Double.parseDouble(a("sep1d"));
curNodeLayer.sep2d = Double.parseDouble(a("sep2d"));
break;
case serpbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.lWidth = Double.parseDouble(a("lWidth"));
curNodeLayer.rWidth = Double.parseDouble(a("rWidth"));
curNodeLayer.tExtent = Double.parseDouble(a("tExtent"));
curNodeLayer.bExtent = Double.parseDouble(a("bExtent"));
break;
case lambdaBox:
if (curNodeLayer != null) {
curNodeLayer.lx.value = Double.parseDouble(a("klx"));
curNodeLayer.hx.value = Double.parseDouble(a("khx"));
curNodeLayer.ly.value = Double.parseDouble(a("kly"));
curNodeLayer.hy.value = Double.parseDouble(a("khy"));
} else if (curPort != null) {
curPort.lx.value = Double.parseDouble(a("klx"));
curPort.hx.value = Double.parseDouble(a("khx"));
curPort.ly.value = Double.parseDouble(a("kly"));
curPort.hy.value = Double.parseDouble(a("khy"));
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.value = Double.parseDouble(a("klx"));
curNodeGroup.baseHX.value = Double.parseDouble(a("khx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("kly"));
curNodeGroup.baseHY.value = Double.parseDouble(a("khy"));
}
break;
case techPoint:
double xm = Double.parseDouble(a("xm"));
double xa = Double.parseDouble(a("xa"));
double ym = Double.parseDouble(a("ym"));
double ya = Double.parseDouble(a("ya"));
TechPoint p = new TechPoint(new EdgeH(xm, xa), new EdgeV(ym, ya));
if (curNodeLayer != null)
curNodeLayer.techPoints.add(p);
break;
case primitivePort:
curPort = new PrimitivePort();
curPort.name = a("name");
break;
case portAngle:
curPort.portAngle = Integer.parseInt(a("primary"));
curPort.portRange = Integer.parseInt(a("range"));
break;
case polygonal:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.POLYGONAL;
break;
case serpTrans:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.SERPTRANS;
curNodeGroup.specialValues = new double[6];
curSpecialValueIndex = 0;
break;
case minSizeRule:
curNodeGroup.nodeSizeRule = new NodeSizeRule();
curNodeGroup.nodeSizeRule.width = Double.parseDouble(a("width"));
curNodeGroup.nodeSizeRule.height = Double.parseDouble(a("height"));
curNodeGroup.nodeSizeRule.rule = a("rule");
break;
case spiceTemplate:
curNodeGroup.spiceTemplate = a("value");
break;
case spiceHeader:
curSpiceHeader = new SpiceHeader();
curSpiceHeader.level = Integer.parseInt(a("level"));
tech.spiceHeaders.add(curSpiceHeader);
break;
case spiceLine:
curSpiceHeader.spiceLines.add(a("line"));
break;
case menuPalette:
tech.menuPalette = new MenuPalette();
tech.menuPalette.numColumns = Integer.parseInt(a("numColumns"));
break;
case menuBox:
curMenuBox = new ArrayList<Object>();
tech.menuPalette.menuBoxes.add(curMenuBox);
break;
case menuNodeInst:
curMenuNodeInst = new MenuNodeInst();
curMenuNodeInst.protoName = a("protoName");
if (tech.findNode(curMenuNodeInst.protoName) == null)
System.out.println("Warning: cannot find node '" + curMenuNodeInst.protoName + "' for component menu");
curMenuNodeInst.function = com.sun.electric.technology.PrimitiveNode.Function.findType(a("function"));
if (curMenuNodeInst.function == null)
System.out.println("Error: cannot find function '" + a("function") + "' for node '" +
a("protoName" + "'"));
String techBits = a_("techBits");
if (techBits != null)
curMenuNodeInst.techBits = Integer.parseInt(techBits);
String rotField = a_("rotation");
if (rotField != null) curMenuNodeInst.rotation = Integer.parseInt(rotField);
break;
case menuNodeText:
curMenuNodeInst.text = a("text");
// curMenuNodeInst.fontSize = Double.parseDouble(a("size"));
break;
case Foundry:
curFoundry = new Foundry();
curFoundry.name = a("name");
tech.foundries.add(curFoundry);
break;
case layerGds:
curFoundry.layerGds.put(a("layer"), a("gds"));
break;
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
if (curLayerNamesList == null)
curLayerNamesList = tech.getLayerNames();
if (curNodeNamesList == null)
curNodeNamesList = tech.getNodeNames();
if (!DRCTemplate.parseXmlElement(curFoundry.rules, curLayerNamesList, curNodeNamesList,
key.name(), attributes, localName))
System.out.println("Warning: cannot find layer name in DRC rule '" + key.name());
break;
default:
assert key.hasText;
beginCharacters();
// System.out.print(">");
return;
}
assert !key.hasText;
// System.out.println(">");
if (dump) {
System.out.println("startElement uri=" + uri + " localName=" + localName + " qName=" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println("\tattribute " + i + " uri=" + attributes.getURI(i) +
" localName=" + attributes.getLocalName(i) + " QName=" + attributes.getQName(i) +
" type=" + attributes.getType(i) + " value=<" + attributes.getValue(i) + ">");
}
}
}
| public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
boolean dump = false;
XmlKeyword key = xmlKeywords.get(localName);
// System.out.print("<" + key.name());
this.attributes = attributes;
switch (key) {
case technology:
tech.techName = a("name");
tech.className = a_("class");
if (tech.className != null)
{
int index = tech.className.indexOf(".");
String realName = tech.className;
while (index != -1)
{
realName = realName.substring(index+1);
index = realName.indexOf(".");
}
if (!realName.toLowerCase().equals(tech.techName.toLowerCase()))
System.out.println("Mismatch between techName '" + tech.techName +
"' and className '" + realName + "' in the XML technology file.");
}
// dump = true;
break;
case version:
Version localVersion = new Version();
localVersion.techVersion = Integer.parseInt(a("tech"));
localVersion.electricVersion = com.sun.electric.database.text.Version.parseVersion(a("electric"));
tech.versions.add(localVersion);
break;
case numMetals:
tech.minNumMetals = Integer.parseInt(a("min"));
tech.maxNumMetals = Integer.parseInt(a("max"));
tech.defaultNumMetals = Integer.parseInt(a("default"));
break;
case scale:
tech.scaleValue = Double.parseDouble(a("value"));
tech.scaleRelevant = Boolean.parseBoolean(a("relevant"));
break;
case resolution:
tech.resolutionValue = Double.parseDouble(a("value")); // default is 0;
break;
case defaultFoundry:
tech.defaultFoundry = a("value");
break;
case minResistance:
tech.minResistance = Double.parseDouble(a("value"));
break;
case minCapacitance:
tech.minCapacitance = Double.parseDouble(a("value"));
break;
case logicalEffort:
tech.leGateCapacitance = Double.parseDouble(a("gateCapacitance"));
tech.leWireRatio = Double.parseDouble(a("wireRatio"));
tech.leDiffAlpha = Double.parseDouble(a("diffAlpha"));
break;
case transparentLayer:
curTransparent = Integer.parseInt(a("transparent"));
curR = curG = curB = 0;
break;
case layer:
curLayer = new Layer();
curLayer.name = a("name");
curLayer.function = com.sun.electric.technology.Layer.Function.valueOf(a("fun"));
String extraFunStr = a_("extraFun");
if (extraFunStr != null) {
if (extraFunStr.equals("depletion_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("depletion_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.LIGHT;
else if (extraFunStr.equals("enhancement_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("enhancement_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.LIGHT;
else
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.parseExtraName(extraFunStr);
}
curTransparent = 0;
curR = curG = curB = 0;
patternedOnDisplay = false;
patternedOnPrinter = false;
Arrays.fill(pattern, 0);
curPatternIndex = 0;
transparencyMode = EGraphics.DEFAULT_MODE;
transparencyFactor = EGraphics.DEFAULT_FACTOR;
// EGraphics.Outline outline = null;
break;
case transparentColor:
curTransparent = Integer.parseInt(a("transparent"));
if (curTransparent > 0) {
Color color = tech.transparentLayers.get(curTransparent - 1);
curR = color.getRed();
curG = color.getGreen();
curB = color.getBlue();
}
break;
case opaqueColor:
curR = Integer.parseInt(a("r"));
curG = Integer.parseInt(a("g"));
curB = Integer.parseInt(a("b"));
break;
case display3D:
curLayer.thick3D = Double.parseDouble(a("thick"));
curLayer.height3D = Double.parseDouble(a("height"));
String modeStr = a_("mode");
if (modeStr != null)
transparencyMode = EGraphics.J3DTransparencyOption.valueOf(modeStr);
String factorStr = a_("factor");
if (factorStr != null)
transparencyFactor = Double.parseDouble(factorStr);
break;
case cifLayer:
curLayer.cif = a("cif");
break;
case skillLayer:
curLayer.skill = a("skill");
break;
case parasitics:
curLayer.resistance = Double.parseDouble(a("resistance"));
curLayer.capacitance = Double.parseDouble(a("capacitance"));
curLayer.edgeCapacitance = Double.parseDouble(a("edgeCapacitance"));
break;
case pureLayerNode:
curLayer.pureLayerNode = new PureLayerNode();
curLayer.pureLayerNode.name = a("name");
String styleStr = a_("style");
curLayer.pureLayerNode.style = styleStr != null ? Poly.Type.valueOf(styleStr) : Poly.Type.FILLED;
curLayer.pureLayerNode.port = a("port");
curDistance = curLayer.pureLayerNode.size;
Xml.PrimitiveNode n = new Xml.PrimitiveNode();
n.name = curLayer.pureLayerNode.name;
n.function = com.sun.electric.technology.PrimitiveNode.Function.NODE;
tech.pureLayerNodes.add(n);
break;
case arcProto:
curArc = new ArcProto();
curArc.name = a("name");
curArc.function = com.sun.electric.technology.ArcProto.Function.valueOf(a("fun"));
break;
case wipable:
curArc.wipable = true;
break;
case curvable:
curArc.curvable = true;
break;
case special:
curArc.special = true;
break;
case notUsed:
if (curArc != null)
curArc.notUsed = true;
else if (curNodeGroup != null)
curNodeGroup.notUsed = true;
break;
case skipSizeInPalette:
if (curArc != null)
curArc.skipSizeInPalette = true;
else if (curNodeGroup != null)
curNodeGroup.skipSizeInPalette = true;
break;
case diskOffset:
if (curArc != null)
curArc.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
new Double(Double.parseDouble(a("width"))));
else if (curNodeGroup != null)
curNodeGroup.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
EPoint.fromLambda(Double.parseDouble(a("x")), Double.parseDouble(a("y"))));
break;
case defaultWidth:
if (curArc != null)
curDistance = curArc.defaultWidth;
else if (curNodeGroup != null)
curDistance = curNodeGroup.defaultWidth;
break;
case arcLayer:
ArcLayer arcLayer = new ArcLayer();
arcLayer.layer = a("layer");
curDistance = arcLayer.extend;
arcLayer.style = Poly.Type.valueOf(a("style"));
curArc.arcLayers.add(arcLayer);
break;
case primitiveNodeGroup:
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNode = null;
if (a_("name") != null)
System.out.println("Attribute 'name' in <primitiveNodeGroup> is deprecated");
if (a_("fun") != null)
System.out.println("Attribute 'fun' in <primitiveNodeGroup> is deprecated");
break;
case inNodes:
if (curNodeGroup.isSingleton)
throw new SAXException("<inNodes> can be used only inside <primitiveNodeGroup>");
curNodeLayer.inNodes = new BitSet();
break;
case primitiveNode:
if (curNodeLayer != null) {
assert !curNodeGroup.isSingleton && curNode == null;
String nodeName = a("name");
int i = 0;
while (i < curNodeGroup.nodes.size() && !curNodeGroup.nodes.get(i).name.equals(nodeName))
i++;
if (i >= curNodeGroup.nodes.size())
throw new SAXException("No node "+nodeName+" in group");
curNodeLayer.inNodes.set(i);
} else if (curNodeGroup != null) {
assert !curNodeGroup.isSingleton;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
} else {
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNodeGroup.isSingleton = true;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
}
break;
case shrinkArcs:
curNodeGroup.shrinkArcs = true;
break;
case square:
curNodeGroup.square = true;
break;
case canBeZeroSize:
curNodeGroup.canBeZeroSize = true;
break;
case wipes:
curNodeGroup.wipes = true;
break;
case lockable:
curNodeGroup.lockable = true;
break;
case edgeSelect:
curNodeGroup.edgeSelect = true;
break;
case lowVt:
curNode.lowVt = true;
break;
case highVt:
curNode.highVt = true;
break;
case nativeBit:
curNode.nativeBit = true;
break;
case od18:
curNode.od18 = true;
break;
case od25:
curNode.od25 = true;
break;
case od33:
curNode.od33 = true;
break;
case defaultHeight:
curDistance = curNodeGroup.defaultHeight;
break;
case nodeBase:
curNodeGroupHasNodeBase = true;
break;
case sizeOffset:
curNodeGroup.baseLX.value = Double.parseDouble(a("lx"));
curNodeGroup.baseHX.value = -Double.parseDouble(a("hx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("ly"));
curNodeGroup.baseHY.value = -Double.parseDouble(a("hy"));
break;
case protection:
curNodeGroup.protection = ProtectionType.valueOf(a("location"));
break;
case nodeLayer:
curNodeLayer = new NodeLayer();
curNodeLayer.layer = a("layer");
if (tech.findLayer(curNodeLayer.layer) == null)
{
throw new SAXException("Error: cannot find layer '" + curNodeLayer.layer + "' in primitive node '" +
curNode.name + "'. Skiping this NodeLayer");
}
else
{
curNodeLayer.style = Poly.Type.valueOf(a("style"));
String portNum = a_("portNum");
if (portNum != null)
curNodeLayer.portNum = Integer.parseInt(portNum);
String electrical = a_("electrical");
if (electrical != null) {
if (Boolean.parseBoolean(electrical))
curNodeLayer.inElectricalLayers = true;
else
curNodeLayer.inLayers = true;
} else {
curNodeLayer.inElectricalLayers = curNodeLayer.inLayers = true;
}
}
break;
case box:
if (curNodeLayer != null) {
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
} else if (curPort != null) {
curPort.lx.k = da_("klx", -1);
curPort.hx.k = da_("khx", 1);
curPort.ly.k = da_("kly", -1);
curPort.hy.k = da_("khy", 1);
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.k = curNodeGroup.baseLY.k = -1;
curNodeGroup.baseHX.k = curNodeGroup.baseHY.k = 1;
}
break;
case points:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.POINTS;
break;
case multicutbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.sizex = Double.parseDouble(a("sizex"));
curNodeLayer.sizey = Double.parseDouble(a("sizey"));
curNodeLayer.sep1d = Double.parseDouble(a("sep1d"));
curNodeLayer.sep2d = Double.parseDouble(a("sep2d"));
break;
case serpbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.lWidth = Double.parseDouble(a("lWidth"));
curNodeLayer.rWidth = Double.parseDouble(a("rWidth"));
curNodeLayer.tExtent = Double.parseDouble(a("tExtent"));
curNodeLayer.bExtent = Double.parseDouble(a("bExtent"));
break;
case lambdaBox:
if (curNodeLayer != null) {
curNodeLayer.lx.value = Double.parseDouble(a("klx"));
curNodeLayer.hx.value = Double.parseDouble(a("khx"));
curNodeLayer.ly.value = Double.parseDouble(a("kly"));
curNodeLayer.hy.value = Double.parseDouble(a("khy"));
} else if (curPort != null) {
curPort.lx.value = Double.parseDouble(a("klx"));
curPort.hx.value = Double.parseDouble(a("khx"));
curPort.ly.value = Double.parseDouble(a("kly"));
curPort.hy.value = Double.parseDouble(a("khy"));
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.value = Double.parseDouble(a("klx"));
curNodeGroup.baseHX.value = Double.parseDouble(a("khx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("kly"));
curNodeGroup.baseHY.value = Double.parseDouble(a("khy"));
}
break;
case techPoint:
double xm = Double.parseDouble(a("xm"));
double xa = Double.parseDouble(a("xa"));
double ym = Double.parseDouble(a("ym"));
double ya = Double.parseDouble(a("ya"));
TechPoint p = new TechPoint(new EdgeH(xm, xa), new EdgeV(ym, ya));
if (curNodeLayer != null)
curNodeLayer.techPoints.add(p);
break;
case primitivePort:
curPort = new PrimitivePort();
curPort.name = a("name");
break;
case portAngle:
curPort.portAngle = Integer.parseInt(a("primary"));
curPort.portRange = Integer.parseInt(a("range"));
break;
case polygonal:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.POLYGONAL;
break;
case serpTrans:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.SERPTRANS;
curNodeGroup.specialValues = new double[6];
curSpecialValueIndex = 0;
break;
case minSizeRule:
curNodeGroup.nodeSizeRule = new NodeSizeRule();
curNodeGroup.nodeSizeRule.width = Double.parseDouble(a("width"));
curNodeGroup.nodeSizeRule.height = Double.parseDouble(a("height"));
curNodeGroup.nodeSizeRule.rule = a("rule");
break;
case spiceTemplate:
curNodeGroup.spiceTemplate = a("value");
break;
case spiceHeader:
curSpiceHeader = new SpiceHeader();
curSpiceHeader.level = Integer.parseInt(a("level"));
tech.spiceHeaders.add(curSpiceHeader);
break;
case spiceLine:
curSpiceHeader.spiceLines.add(a("line"));
break;
case menuPalette:
tech.menuPalette = new MenuPalette();
tech.menuPalette.numColumns = Integer.parseInt(a("numColumns"));
break;
case menuBox:
curMenuBox = new ArrayList<Object>();
tech.menuPalette.menuBoxes.add(curMenuBox);
break;
case menuNodeInst:
curMenuNodeInst = new MenuNodeInst();
curMenuNodeInst.protoName = a("protoName");
if (tech.findNode(curMenuNodeInst.protoName) == null)
System.out.println("Warning: cannot find node '" + curMenuNodeInst.protoName + "' for component menu");
curMenuNodeInst.function = com.sun.electric.technology.PrimitiveNode.Function.findType(a("function"));
if (curMenuNodeInst.function == null)
System.out.println("Error: cannot find function '" + a("function") + "' for node '" +
a("protoName" + "'"));
String techBits = a_("techBits");
if (techBits != null)
curMenuNodeInst.techBits = Integer.parseInt(techBits);
String rotField = a_("rotation");
if (rotField != null) curMenuNodeInst.rotation = Integer.parseInt(rotField);
break;
case menuNodeText:
curMenuNodeInst.text = a("text");
// curMenuNodeInst.fontSize = Double.parseDouble(a("size"));
break;
case Foundry:
curFoundry = new Foundry();
curFoundry.name = a("name");
tech.foundries.add(curFoundry);
break;
case layerGds:
curFoundry.layerGds.put(a("layer"), a("gds"));
break;
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
if (curLayerNamesList == null)
curLayerNamesList = tech.getLayerNames();
if (curNodeNamesList == null)
curNodeNamesList = tech.getNodeNames();
if (!DRCTemplate.parseXmlElement(curFoundry.rules, curLayerNamesList, curNodeNamesList,
key.name(), attributes, localName))
System.out.println("Warning: cannot find layer name in DRC rule '" + key.name());
break;
default:
assert key.hasText;
beginCharacters();
// System.out.print(">");
return;
}
assert !key.hasText;
// System.out.println(">");
if (dump) {
System.out.println("startElement uri=" + uri + " localName=" + localName + " qName=" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println("\tattribute " + i + " uri=" + attributes.getURI(i) +
" localName=" + attributes.getLocalName(i) + " QName=" + attributes.getQName(i) +
" type=" + attributes.getType(i) + " value=<" + attributes.getValue(i) + ">");
}
}
}
|
diff --git a/src/main/java/inra/watershed/plugin/Watershed_3D.java b/src/main/java/inra/watershed/plugin/Watershed_3D.java
index 0bdec3f..1d0e955 100644
--- a/src/main/java/inra/watershed/plugin/Watershed_3D.java
+++ b/src/main/java/inra/watershed/plugin/Watershed_3D.java
@@ -1,250 +1,250 @@
package inra.watershed.plugin;
/**
*
* License: GPL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
*
* 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.
*
* Authors: Ignacio Arganda-Carreras, Philippe Andrey, Axel Poulet
*/
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import ij.process.ImageProcessor;
import inra.watershed.process.ComponentLabelling;
import inra.watershed.process.RegionalMinimaFilter;
import inra.watershed.process.WatershedTransform3D;
/**
* Watershed 3D
*
* A plugin to perform watershed on a 3D image.
*
* @author Ignacio Arganda-Carreras
*/
public class Watershed_3D implements PlugIn
{
public boolean usePriorityQueue = false;
/**
* Apply 3D watershed to a 2D or 3D image (it does work for 2D images too).
*
*
* @param input the 2D or 3D image (in principle a "gradient" image)
* @param seed the image to calculate the seeds from (it can be the same as the input or another one)
*/
public ImagePlus process(
ImagePlus input,
ImagePlus seed)
{
final long start = System.currentTimeMillis();
IJ.log("-> Running regional minima filter...");
RegionalMinimaFilter rmf = new RegionalMinimaFilter( seed );
ImagePlus regionalMinima = rmf.apply();
//regionalMinima.show();
final long step1 = System.currentTimeMillis();
IJ.log( "Regional minima took " + (step1-start) + " ms.");
IJ.log("-> Running connected components...");
ComponentLabelling cl = new ComponentLabelling( regionalMinima );
ImagePlus connectedMinima = cl.apply();
//connectedMinima.show();
final long step2 = System.currentTimeMillis();
IJ.log( "Connected components took " + (step2-step1) + " ms.");
IJ.log("-> Running watershed...");
WatershedTransform3D wt = new WatershedTransform3D(input, connectedMinima, null);
ImagePlus resultImage = usePriorityQueue == false ? wt.apply() : wt.applyWithPriorityQueue();
final long end = System.currentTimeMillis();
IJ.log( "Watershed 3d took " + (end-step2) + " ms.");
IJ.log( "Whole plugin took " + (end-start) + " ms.");
return resultImage;
}
/**
* Apply 3D watershed to a 2D or 3D image (it does work for 2D images too).
*
*
* @param input the 2D or 3D image (in principle a "gradient" image)
* @param seed the image to calculate the seeds from (it can be the same as the input or another one)
* @param mask the mask to constraint the watershed
*/
public ImagePlus process(
ImagePlus input,
ImagePlus seed,
ImagePlus mask)
{
final long start = System.currentTimeMillis();
IJ.log("-> Running regional minima filter...");
RegionalMinimaFilter rmf = new RegionalMinimaFilter( seed );
if( null != mask )
rmf.setMask( mask );
ImagePlus regionalMinima = rmf.apply();
//regionalMinima.show();
final long step1 = System.currentTimeMillis();
IJ.log( "Regional minima took " + (step1-start) + " ms.");
IJ.log("-> Running connected components...");
ComponentLabelling cl = new ComponentLabelling( regionalMinima );
ImagePlus connectedMinima = cl.apply();
//connectedMinima.show();
final long step2 = System.currentTimeMillis();
IJ.log( "Connected components took " + (step2-step1) + " ms.");
IJ.log("-> Running watershed...");
WatershedTransform3D wt = new WatershedTransform3D( input, connectedMinima, mask );
ImagePlus resultImage = usePriorityQueue == false ? wt.apply() : wt.applyWithPriorityQueue();
final long end = System.currentTimeMillis();
IJ.log( "Watershed 3d took " + (end-step2) + " ms.");
IJ.log( "Whole plugin took " + (end-start) + " ms.");
return resultImage;
}
public void showAbout() {
IJ.showMessage("Watershed 3D",
"a plugin for 3D watershed"
);
}
/**
* Run method needed to work as an ImageJ plugin
*/
@Override
public void run(String arg0)
{
int nbima = WindowManager.getImageCount();
if( nbima == 0 )
{
IJ.error( "Watershed 3D",
- "At least one image needs to be open to run waterhsed in 3D");
+ "ERROR: At least one image needs to be open to run watershed in 3D");
return;
}
String[] names = new String[ nbima ];
String[] namesMask = new String[ nbima + 1 ];
namesMask[ 0 ] = "None";
for (int i = 0; i < nbima; i++)
{
names[ i ] = WindowManager.getImage(i + 1).getShortTitle();
namesMask[ i + 1 ] = WindowManager.getImage(i + 1).getShortTitle();
}
GenericDialog gd = new GenericDialog("Watershed 3D");
int spot = 0;
int seed = nbima > 1 ? 1 : 0;
gd.addChoice( "Input image", names, names[spot] );
gd.addChoice( "Image to seed from", names, names[seed] );
gd.addChoice( "Mask", namesMask, namesMask[ nbima > 2 ? 3 : 0 ] );
gd.addCheckbox( "Use priority queue", usePriorityQueue );
gd.showDialog();
if (gd.wasOKed())
{
spot = gd.getNextChoiceIndex();
seed = gd.getNextChoiceIndex();
int maskIndex = gd.getNextChoiceIndex();
usePriorityQueue = gd.getNextBoolean();
ImagePlus inputImage = WindowManager.getImage(spot + 1);
ImagePlus seedImage = WindowManager.getImage(seed + 1);
ImagePlus maskImage = maskIndex > 0 ? WindowManager.getImage( maskIndex ) : null;
ImagePlus result = process( inputImage, seedImage, maskImage );
// Adjust range to visualize result
//if( result.getImageStackSize() > 1 )
// result.setSlice( result.getImageStackSize()/2 );
ImageProcessor ip = result.getProcessor();
ip.resetMinAndMax();
result.setDisplayRange(ip.getMin(),ip.getMax());
// show result
result.show();
}
}
/**
* Main method for debugging.
*
* For debugging, it is convenient to have a method that starts ImageJ, loads an
* image and calls the plugin, e.g. after setting breakpoints.
*
* @param args unused
*/
public static void main(String[] args) {
// set the plugins.dir property to make the plugin appear in the Plugins menu
Class<?> clazz = Watershed_3D.class;
String url = clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class").toString();
String pluginsDir = url.substring(5, url.length() - clazz.getName().length() - 6);
System.setProperty("plugins.dir", pluginsDir);
// start ImageJ
new ImageJ();
// open the Blobs sample
ImagePlus image = IJ.openImage("http://imagej.net/images/blobs.gif");
// get edges
IJ.run(image, "Find Edges", "");
image.show();
// run the plugin
IJ.runPlugIn(clazz.getName(), "");
}
}
| true | true | public void run(String arg0)
{
int nbima = WindowManager.getImageCount();
if( nbima == 0 )
{
IJ.error( "Watershed 3D",
"At least one image needs to be open to run waterhsed in 3D");
return;
}
String[] names = new String[ nbima ];
String[] namesMask = new String[ nbima + 1 ];
namesMask[ 0 ] = "None";
for (int i = 0; i < nbima; i++)
{
names[ i ] = WindowManager.getImage(i + 1).getShortTitle();
namesMask[ i + 1 ] = WindowManager.getImage(i + 1).getShortTitle();
}
GenericDialog gd = new GenericDialog("Watershed 3D");
int spot = 0;
int seed = nbima > 1 ? 1 : 0;
gd.addChoice( "Input image", names, names[spot] );
gd.addChoice( "Image to seed from", names, names[seed] );
gd.addChoice( "Mask", namesMask, namesMask[ nbima > 2 ? 3 : 0 ] );
gd.addCheckbox( "Use priority queue", usePriorityQueue );
gd.showDialog();
if (gd.wasOKed())
{
spot = gd.getNextChoiceIndex();
seed = gd.getNextChoiceIndex();
int maskIndex = gd.getNextChoiceIndex();
usePriorityQueue = gd.getNextBoolean();
ImagePlus inputImage = WindowManager.getImage(spot + 1);
ImagePlus seedImage = WindowManager.getImage(seed + 1);
ImagePlus maskImage = maskIndex > 0 ? WindowManager.getImage( maskIndex ) : null;
ImagePlus result = process( inputImage, seedImage, maskImage );
// Adjust range to visualize result
//if( result.getImageStackSize() > 1 )
// result.setSlice( result.getImageStackSize()/2 );
ImageProcessor ip = result.getProcessor();
ip.resetMinAndMax();
result.setDisplayRange(ip.getMin(),ip.getMax());
// show result
result.show();
}
}
| public void run(String arg0)
{
int nbima = WindowManager.getImageCount();
if( nbima == 0 )
{
IJ.error( "Watershed 3D",
"ERROR: At least one image needs to be open to run watershed in 3D");
return;
}
String[] names = new String[ nbima ];
String[] namesMask = new String[ nbima + 1 ];
namesMask[ 0 ] = "None";
for (int i = 0; i < nbima; i++)
{
names[ i ] = WindowManager.getImage(i + 1).getShortTitle();
namesMask[ i + 1 ] = WindowManager.getImage(i + 1).getShortTitle();
}
GenericDialog gd = new GenericDialog("Watershed 3D");
int spot = 0;
int seed = nbima > 1 ? 1 : 0;
gd.addChoice( "Input image", names, names[spot] );
gd.addChoice( "Image to seed from", names, names[seed] );
gd.addChoice( "Mask", namesMask, namesMask[ nbima > 2 ? 3 : 0 ] );
gd.addCheckbox( "Use priority queue", usePriorityQueue );
gd.showDialog();
if (gd.wasOKed())
{
spot = gd.getNextChoiceIndex();
seed = gd.getNextChoiceIndex();
int maskIndex = gd.getNextChoiceIndex();
usePriorityQueue = gd.getNextBoolean();
ImagePlus inputImage = WindowManager.getImage(spot + 1);
ImagePlus seedImage = WindowManager.getImage(seed + 1);
ImagePlus maskImage = maskIndex > 0 ? WindowManager.getImage( maskIndex ) : null;
ImagePlus result = process( inputImage, seedImage, maskImage );
// Adjust range to visualize result
//if( result.getImageStackSize() > 1 )
// result.setSlice( result.getImageStackSize()/2 );
ImageProcessor ip = result.getProcessor();
ip.resetMinAndMax();
result.setDisplayRange(ip.getMin(),ip.getMax());
// show result
result.show();
}
}
|
diff --git a/src/main/java/httpServletRequestX/accept/AcceptHeaderImpl.java b/src/main/java/httpServletRequestX/accept/AcceptHeaderImpl.java
index 1f879dd..2a03a57 100644
--- a/src/main/java/httpServletRequestX/accept/AcceptHeaderImpl.java
+++ b/src/main/java/httpServletRequestX/accept/AcceptHeaderImpl.java
@@ -1,130 +1,130 @@
package httpServletRequestX.accept;
import com.google.inject.Inject;
/**
* TODO
*/
public class AcceptHeaderImpl implements AcceptHeader {
private static final String TYPE_ALL = "*/*";
private static final String TYPE_ALL_TEXT = "text/*";
private static final String TYPE_HTML = "text/html";
private static final String TYPE_ALL_APPLICATION = "application/*";
private static final String TYPE_JSON = "application/json";
private String content;
private final AcceptContenTypeList contentTypeList;
private final AcceptContenTypeFactory contentTypeFactory;
@Inject
public AcceptHeaderImpl(AcceptContenTypeList contentTypeList, AcceptContenTypeFactory contentTypeFactory) {
this.contentTypeList = contentTypeList;
this.contentTypeFactory = contentTypeFactory;
}
public AcceptHeader setContent(String content) {
this.content = content;
parseContent();
return this;
}
public String getTop() {
if (!contentTypeList.isEmpty()) {
return contentTypeList.get(0).getType();
}
return null;
}
public AcceptContenTypeList getContentTypes() {
return contentTypeList;
}
public boolean acceptType(String type) {
String[] typeElements = type.split("/");
if (typeElements.length > 0) {
return contentTypeList.containsType(type) || hasWildcard(typeElements[0]) || hasWildcard();
} else {
return contentTypeList.containsType(type) || hasWildcard();
}
}
public boolean acceptHtml() {
return contentTypeList.containsType(TYPE_HTML) || hasTextWildcard() || hasWildcard();
}
public boolean acceptJson() {
return contentTypeList.containsType(TYPE_JSON) || hasApplicationWildcard() || hasWildcard();
}
private boolean hasWildcard() {
return contentTypeList.containsType(TYPE_ALL);
}
private boolean hasWildcard(String first) {
return contentTypeList.containsType(first + "/*");
}
private boolean hasTextWildcard() {
return contentTypeList.containsType(TYPE_ALL_TEXT);
}
private boolean hasApplicationWildcard() {
return contentTypeList.containsType(TYPE_ALL_APPLICATION);
}
private void parseContent() {
this.contentTypeList.clear();
String[] contentTypes = content.split(",");
for (String contentType : contentTypes) {
String[] splittedContenttype = contentType.split(";");
if (!hasParseableContentType(splittedContenttype)) {
continue;
}
if (splittedContenttype.length == 2) {
Float quality = parseQuality(splittedContenttype[1]);
this.contentTypeList.add(contentTypeFactory.get(splittedContenttype[0], quality));
} else {
this.contentTypeList.add(contentTypeFactory.get(splittedContenttype[0]));
}
}
- // java.util.Collections.sort(this.contentTypeList);
+ java.util.Collections.sort(this.contentTypeList);
}
private boolean hasParseableContentType(String[] contentTypeElements) {
if (contentTypeElements == null || contentTypeElements.length == 0) {
return false;
}
for (String contentTypeElement : contentTypeElements) {
if (contentTypeElement.trim().equals("")) {
return false;
}
}
return true;
}
private Float parseQuality(String input) {
String[] quality = input.split("=");
if (quality[0].equals("q")) {
return Float.valueOf(quality[1]);
}
return null;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "AcceptHeader [content=" + content + "]";
}
}
| true | true | private void parseContent() {
this.contentTypeList.clear();
String[] contentTypes = content.split(",");
for (String contentType : contentTypes) {
String[] splittedContenttype = contentType.split(";");
if (!hasParseableContentType(splittedContenttype)) {
continue;
}
if (splittedContenttype.length == 2) {
Float quality = parseQuality(splittedContenttype[1]);
this.contentTypeList.add(contentTypeFactory.get(splittedContenttype[0], quality));
} else {
this.contentTypeList.add(contentTypeFactory.get(splittedContenttype[0]));
}
}
// java.util.Collections.sort(this.contentTypeList);
}
| private void parseContent() {
this.contentTypeList.clear();
String[] contentTypes = content.split(",");
for (String contentType : contentTypes) {
String[] splittedContenttype = contentType.split(";");
if (!hasParseableContentType(splittedContenttype)) {
continue;
}
if (splittedContenttype.length == 2) {
Float quality = parseQuality(splittedContenttype[1]);
this.contentTypeList.add(contentTypeFactory.get(splittedContenttype[0], quality));
} else {
this.contentTypeList.add(contentTypeFactory.get(splittedContenttype[0]));
}
}
java.util.Collections.sort(this.contentTypeList);
}
|
diff --git a/runtime/src/com/sun/xml/bind/v2/runtime/reflect/opt/Injector.java b/runtime/src/com/sun/xml/bind/v2/runtime/reflect/opt/Injector.java
index c01c5f57..716eaeac 100644
--- a/runtime/src/com/sun/xml/bind/v2/runtime/reflect/opt/Injector.java
+++ b/runtime/src/com/sun/xml/bind/v2/runtime/reflect/opt/Injector.java
@@ -1,145 +1,148 @@
package com.sun.xml.bind.v2.runtime.reflect.opt;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.xml.bind.Util;
/**
* A {@link ClassLoader} used to "inject" optimized accessor classes
* into the VM.
*
* <p>
* Its parent class loader needs to be set to the one that can see the user
* class.
*
* @author Kohsuke Kawaguchi
*/
final class Injector {
/**
* {@link Injector}s keyed by their parent {@link ClassLoader}.
*
* We only need one injector per one user class loader.
*/
private static final Map<ClassLoader,WeakReference<Injector>> injectors =
Collections.synchronizedMap(new WeakHashMap<ClassLoader,WeakReference<Injector>>());
private static final Logger logger = Util.getClassLogger();
/**
* Injects a new class into the given class loader.
*
* @return null
* if it fails to inject.
*/
static Class inject( ClassLoader cl, String className, byte[] image ) {
Injector injector = get(cl);
if(injector!=null)
return injector.inject(className,image);
else
return null;
}
/**
* Returns the already injected class, or null.
*/
static Class find( ClassLoader cl, String className ) {
Injector injector = get(cl);
if(injector!=null)
return injector.find(className);
else
return null;
}
/**
* Gets or creates an {@link Injector} for the given class loader.
*
* @return null
* if it fails.
*/
private static Injector get(ClassLoader cl) {
Injector injector = null;
WeakReference<Injector> wr = injectors.get(cl);
if(wr!=null)
injector = wr.get();
if(injector==null)
try {
injectors.put(cl,new WeakReference<Injector>(injector = new Injector(cl)));
} catch (SecurityException e) {
logger.log(Level.FINE,"Unable to set up a back-door for the injector",e);
return null;
}
return injector;
}
/**
* Injected classes keyed by their names.
*/
private final Map<String,Class> classes = new HashMap<String,Class>();
private final ClassLoader parent;
private static final Method defineClass;
private static final Method resolveClass;
static {
try {
defineClass = ClassLoader.class.getDeclaredMethod("defineClass",String.class,byte[].class,Integer.TYPE,Integer.TYPE);
resolveClass = ClassLoader.class.getDeclaredMethod("resolveClass",Class.class);
} catch (NoSuchMethodException e) {
// impossible
throw new NoSuchMethodError(e.getMessage());
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
// TODO: check security implication
// do these setAccessible allow anyone to call these methods freely?s
defineClass.setAccessible(true);
resolveClass.setAccessible(true);
return null;
}
});
}
private Injector(ClassLoader parent) {
this.parent = parent;
assert parent!=null;
}
private synchronized Class inject(String className, byte[] image) {
Class c = classes.get(className);
if(c==null) {
// we need to inject a class into the
try {
c = (Class)defineClass.invoke(parent,className.replace('/','.'),image,0,image.length);
resolveClass.invoke(parent,c);
} catch (IllegalAccessException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
} catch (InvocationTargetException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
} catch (SecurityException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
+ } catch (LinkageError e) {
+ logger.log(Level.FINE,"Unable to inject "+className,e);
+ return null;
}
classes.put(className,c);
}
return c;
}
private synchronized Class find(String className) {
return classes.get(className);
}
}
| true | true | private synchronized Class inject(String className, byte[] image) {
Class c = classes.get(className);
if(c==null) {
// we need to inject a class into the
try {
c = (Class)defineClass.invoke(parent,className.replace('/','.'),image,0,image.length);
resolveClass.invoke(parent,c);
} catch (IllegalAccessException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
} catch (InvocationTargetException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
} catch (SecurityException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
}
classes.put(className,c);
}
return c;
}
| private synchronized Class inject(String className, byte[] image) {
Class c = classes.get(className);
if(c==null) {
// we need to inject a class into the
try {
c = (Class)defineClass.invoke(parent,className.replace('/','.'),image,0,image.length);
resolveClass.invoke(parent,c);
} catch (IllegalAccessException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
} catch (InvocationTargetException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
} catch (SecurityException e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
} catch (LinkageError e) {
logger.log(Level.FINE,"Unable to inject "+className,e);
return null;
}
classes.put(className,c);
}
return c;
}
|
diff --git a/src/com/time/master/view/TabTextView.java b/src/com/time/master/view/TabTextView.java
index 0ba4961..15c5bf0 100644
--- a/src/com/time/master/view/TabTextView.java
+++ b/src/com/time/master/view/TabTextView.java
@@ -1,125 +1,125 @@
package com.time.master.view;
import com.time.master.TimeMasterApplication;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class TabTextView extends SelectedTextView {
Context context;
protected int screen_width,
screen_height,
unit_width,//view �����
gap,//view������
screen_mode; //1�������� �� 2��������
protected RelativeLayout.LayoutParams params=(LayoutParams) this.getLayoutParams();
Paint mPaint,marginPaint,linePaint;
boolean hasRightEdge=false;
float strokeWdith=10f;
public TabTextView(Context context) {
super(context);
init(context);
}
public TabTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public TabTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
/***
* ��ʼ�����в���
*/
protected void init(Context context){
this.context=context;
screen_mode=context.getResources().getConfiguration().orientation;
screen_width=TimeMasterApplication.getInstance().getScreen_W();
screen_height=TimeMasterApplication.getInstance().getScreen_H();
unit_width=screen_mode==Configuration.ORIENTATION_PORTRAIT?screen_width/6:screen_height/6;
gap=screen_mode==Configuration.ORIENTATION_PORTRAIT?screen_width/36:screen_height/36;
mPaint=new Paint();
mPaint.setColor(0xFFCCCCCC);
marginPaint=new Paint();
marginPaint.setColor(0xFFFFFFFF);
linePaint=new Paint();
linePaint.setColor(0xFFCCCCCC);
linePaint.setStyle(Style.STROKE);
linePaint.setStrokeWidth(strokeWdith);
linePaint.setAntiAlias(true); // �������
linePaint.setFlags(Paint.ANTI_ALIAS_FLAG); // �������
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// if(!hasRightEdge)
// this.setMeasuredDimension(gap+unit_width, (int)(unit_width*0.75)+(int)strokeWdith);
// else
// this.setMeasuredDimension(gap+unit_width+gap, (int)(unit_width*0.75)+(int)strokeWdith);
screen_mode=context.getResources().getConfiguration().orientation;
if(screen_mode==Configuration.ORIENTATION_PORTRAIT)
this.setMeasuredDimension(screen_width/5, (int)(unit_width*0.75)+(int)strokeWdith);
else
this.setMeasuredDimension(screen_width/5, (int)(unit_width*0.75)+gap);
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
// canvas.drawRect(0, 0, gap, unit_width*0.75f, marginPaint);//��߿�
// canvas.drawRect(gap, 0, gap+unit_width, unit_width*0.75f, mPaint);//�����
// if(hasRightEdge)
// canvas.drawRect(gap+unit_width, 0, gap+gap+unit_width, unit_width*0.75f, marginPaint);//�ұ߿�
//
// canvas.drawLine(0, unit_width*0.75f+strokeWdith/2, unit_width+gap+(hasRightEdge?gap:0), unit_width*0.75f+strokeWdith/2, linePaint);
if(screen_mode==Configuration.ORIENTATION_PORTRAIT){
canvas.drawRect(0, 0, gap/2, unit_width*0.75f, marginPaint);//��߿�
canvas.drawRect(gap/2, 0, screen_width/5-gap/2, unit_width*0.75f, mPaint);//�����
canvas.drawRect(screen_width/5-gap/2, 0, screen_width/5, unit_width*0.75f, marginPaint);//�ұ߿�
canvas.drawLine(0, unit_width*0.75f+strokeWdith/2, screen_width/5, unit_width*0.75f+strokeWdith/2, linePaint);
}else{
canvas.drawRect(0, 0, gap/2, getMeasuredHeight(), marginPaint);//��߿�
canvas.drawRect(0, 0, getMeasuredWidth(),gap/2, marginPaint);//�ϱ߿�
canvas.drawRect(gap/2, 0, getMeasuredWidth()-gap/2, getMeasuredHeight()-gap/2, mPaint);//�����
- canvas.drawRect(0, getMeasuredWidth()-gap/2, getMeasuredWidth(), getMeasuredHeight(), marginPaint);//�±߿�
+ canvas.drawRect(gap/2, getMeasuredHeight(), screen_width/5, getMeasuredHeight(), marginPaint);//�±߿�
canvas.drawRect(screen_width/5-gap/2, 0, screen_width/5, getMeasuredHeight(), marginPaint);//�ұ߿�
canvas.drawLine(getMeasuredWidth()-gap/2+strokeWdith/2, 0, getMeasuredWidth()-gap/2+strokeWdith/2, getMeasuredHeight(), linePaint);
}
super.onDraw(canvas);
}
public TabTextView setCenterText(String text){
this.setText(text);
this.setTextColor(0xFF000000);
this.setGravity(Gravity.CENTER);
//params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
//params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
return this;
}
public void setCenterBackgroud(int color){
this.naturalColor=color;
mPaint.setColor(naturalColor);
}
public void setRightMargin(){
hasRightEdge=true;
}
@Override
protected void actionDown() {
}
@Override
protected void actionUp() {
}
}
| true | true | protected void onDraw(Canvas canvas) {
// canvas.drawRect(0, 0, gap, unit_width*0.75f, marginPaint);//��߿�
// canvas.drawRect(gap, 0, gap+unit_width, unit_width*0.75f, mPaint);//�����
// if(hasRightEdge)
// canvas.drawRect(gap+unit_width, 0, gap+gap+unit_width, unit_width*0.75f, marginPaint);//�ұ߿�
//
// canvas.drawLine(0, unit_width*0.75f+strokeWdith/2, unit_width+gap+(hasRightEdge?gap:0), unit_width*0.75f+strokeWdith/2, linePaint);
if(screen_mode==Configuration.ORIENTATION_PORTRAIT){
canvas.drawRect(0, 0, gap/2, unit_width*0.75f, marginPaint);//��߿�
canvas.drawRect(gap/2, 0, screen_width/5-gap/2, unit_width*0.75f, mPaint);//�����
canvas.drawRect(screen_width/5-gap/2, 0, screen_width/5, unit_width*0.75f, marginPaint);//�ұ߿�
canvas.drawLine(0, unit_width*0.75f+strokeWdith/2, screen_width/5, unit_width*0.75f+strokeWdith/2, linePaint);
}else{
canvas.drawRect(0, 0, gap/2, getMeasuredHeight(), marginPaint);//��߿�
canvas.drawRect(0, 0, getMeasuredWidth(),gap/2, marginPaint);//�ϱ߿�
canvas.drawRect(gap/2, 0, getMeasuredWidth()-gap/2, getMeasuredHeight()-gap/2, mPaint);//�����
canvas.drawRect(0, getMeasuredWidth()-gap/2, getMeasuredWidth(), getMeasuredHeight(), marginPaint);//�±߿�
canvas.drawRect(screen_width/5-gap/2, 0, screen_width/5, getMeasuredHeight(), marginPaint);//�ұ߿�
canvas.drawLine(getMeasuredWidth()-gap/2+strokeWdith/2, 0, getMeasuredWidth()-gap/2+strokeWdith/2, getMeasuredHeight(), linePaint);
}
super.onDraw(canvas);
}
| protected void onDraw(Canvas canvas) {
// canvas.drawRect(0, 0, gap, unit_width*0.75f, marginPaint);//��߿�
// canvas.drawRect(gap, 0, gap+unit_width, unit_width*0.75f, mPaint);//�����
// if(hasRightEdge)
// canvas.drawRect(gap+unit_width, 0, gap+gap+unit_width, unit_width*0.75f, marginPaint);//�ұ߿�
//
// canvas.drawLine(0, unit_width*0.75f+strokeWdith/2, unit_width+gap+(hasRightEdge?gap:0), unit_width*0.75f+strokeWdith/2, linePaint);
if(screen_mode==Configuration.ORIENTATION_PORTRAIT){
canvas.drawRect(0, 0, gap/2, unit_width*0.75f, marginPaint);//��߿�
canvas.drawRect(gap/2, 0, screen_width/5-gap/2, unit_width*0.75f, mPaint);//�����
canvas.drawRect(screen_width/5-gap/2, 0, screen_width/5, unit_width*0.75f, marginPaint);//�ұ߿�
canvas.drawLine(0, unit_width*0.75f+strokeWdith/2, screen_width/5, unit_width*0.75f+strokeWdith/2, linePaint);
}else{
canvas.drawRect(0, 0, gap/2, getMeasuredHeight(), marginPaint);//��߿�
canvas.drawRect(0, 0, getMeasuredWidth(),gap/2, marginPaint);//�ϱ߿�
canvas.drawRect(gap/2, 0, getMeasuredWidth()-gap/2, getMeasuredHeight()-gap/2, mPaint);//�����
canvas.drawRect(gap/2, getMeasuredHeight(), screen_width/5, getMeasuredHeight(), marginPaint);//�±߿�
canvas.drawRect(screen_width/5-gap/2, 0, screen_width/5, getMeasuredHeight(), marginPaint);//�ұ߿�
canvas.drawLine(getMeasuredWidth()-gap/2+strokeWdith/2, 0, getMeasuredWidth()-gap/2+strokeWdith/2, getMeasuredHeight(), linePaint);
}
super.onDraw(canvas);
}
|
diff --git a/src/jipdbs/web/SearchServlet.java b/src/jipdbs/web/SearchServlet.java
index e225023..a56e4f8 100644
--- a/src/jipdbs/web/SearchServlet.java
+++ b/src/jipdbs/web/SearchServlet.java
@@ -1,86 +1,87 @@
package jipdbs.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jipdbs.JIPDBS;
import jipdbs.PageLink;
import jipdbs.SearchResult;
import jipdbs.util.Functions;
public class SearchServlet extends HttpServlet {
private static final int DEFAULT_PAGE_SIZE = 20;
private static final long serialVersionUID = -729953187311026007L;
private JIPDBS app;
@Override
public void init() throws ServletException {
app = (JIPDBS) getServletContext().getAttribute("jipdbs");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int page = 1;
int pageSize = DEFAULT_PAGE_SIZE;
try {
page = Integer.parseInt(req.getParameter("p"));
} catch (NumberFormatException e) {
// Ignore.
}
try {
pageSize = Integer.parseInt(req.getParameter("ps"));
} catch (NumberFormatException e) {
// Ignore.
}
int offset = (page - 1) * pageSize;
int limit = pageSize;
String query = req.getParameter("q");
String type = req.getParameter("t");
List<SearchResult> list = new ArrayList<SearchResult>();
int[] total = new int[1];
long time = System.currentTimeMillis();
String queryValue = query;
if (query == null || "".equals(query)) {
list = app.rootQuery(offset, limit, total);
} else {
// this is to get the modified value and show it in search box
if ("ip".equals(type)) {
query = Functions.fixIp(query);
queryValue = query;
}
else if ("s".equals(type)) queryValue = "";
list = app.search(query, type, offset, limit, total);
}
time = System.currentTimeMillis() - time;
int totalPages = (int) Math.ceil((double) total[0] / pageSize);
req.setAttribute("list", list);
- req.setAttribute("query", queryValue);
+ req.setAttribute("queryValue", queryValue);
+ req.setAttribute("query", query);
req.setAttribute("type", type);
req.setAttribute("count", total[0]);
req.setAttribute("time", time);
req.setAttribute("pageLink", new PageLink(page, pageSize, totalPages));
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int page = 1;
int pageSize = DEFAULT_PAGE_SIZE;
try {
page = Integer.parseInt(req.getParameter("p"));
} catch (NumberFormatException e) {
// Ignore.
}
try {
pageSize = Integer.parseInt(req.getParameter("ps"));
} catch (NumberFormatException e) {
// Ignore.
}
int offset = (page - 1) * pageSize;
int limit = pageSize;
String query = req.getParameter("q");
String type = req.getParameter("t");
List<SearchResult> list = new ArrayList<SearchResult>();
int[] total = new int[1];
long time = System.currentTimeMillis();
String queryValue = query;
if (query == null || "".equals(query)) {
list = app.rootQuery(offset, limit, total);
} else {
// this is to get the modified value and show it in search box
if ("ip".equals(type)) {
query = Functions.fixIp(query);
queryValue = query;
}
else if ("s".equals(type)) queryValue = "";
list = app.search(query, type, offset, limit, total);
}
time = System.currentTimeMillis() - time;
int totalPages = (int) Math.ceil((double) total[0] / pageSize);
req.setAttribute("list", list);
req.setAttribute("query", queryValue);
req.setAttribute("type", type);
req.setAttribute("count", total[0]);
req.setAttribute("time", time);
req.setAttribute("pageLink", new PageLink(page, pageSize, totalPages));
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int page = 1;
int pageSize = DEFAULT_PAGE_SIZE;
try {
page = Integer.parseInt(req.getParameter("p"));
} catch (NumberFormatException e) {
// Ignore.
}
try {
pageSize = Integer.parseInt(req.getParameter("ps"));
} catch (NumberFormatException e) {
// Ignore.
}
int offset = (page - 1) * pageSize;
int limit = pageSize;
String query = req.getParameter("q");
String type = req.getParameter("t");
List<SearchResult> list = new ArrayList<SearchResult>();
int[] total = new int[1];
long time = System.currentTimeMillis();
String queryValue = query;
if (query == null || "".equals(query)) {
list = app.rootQuery(offset, limit, total);
} else {
// this is to get the modified value and show it in search box
if ("ip".equals(type)) {
query = Functions.fixIp(query);
queryValue = query;
}
else if ("s".equals(type)) queryValue = "";
list = app.search(query, type, offset, limit, total);
}
time = System.currentTimeMillis() - time;
int totalPages = (int) Math.ceil((double) total[0] / pageSize);
req.setAttribute("list", list);
req.setAttribute("queryValue", queryValue);
req.setAttribute("query", query);
req.setAttribute("type", type);
req.setAttribute("count", total[0]);
req.setAttribute("time", time);
req.setAttribute("pageLink", new PageLink(page, pageSize, totalPages));
}
|
diff --git a/htroot/Blog.java b/htroot/Blog.java
index ce685ebdd..40ae8b210 100644
--- a/htroot/Blog.java
+++ b/htroot/Blog.java
@@ -1,256 +1,257 @@
// Blog.java
// -----------------------
// part of YACY
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
//
// This File is contributed by Jan Sandbrink
// Contains contributions from Marc Nause [MN]
// last change: 06.05.2006
//
// 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
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
// You must compile this file with
// javac -classpath .:../Classes Blacklist_p.java
// if the shell's current path is HTROOT
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import de.anomic.data.userDB;
import de.anomic.data.blogBoard;
import de.anomic.data.wikiCode;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsRecord;
public class Blog {
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// TODO: make userdefined date/time-strings (localisation)
public static String dateString(Date date) {
return SimpleFormatter.format(date);
}
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
blogBoard.entry page = null;
boolean hasRights = switchboard.verifyAuthentication(header, true);
if(hasRights) prop.put("mode_admin",1);
else prop.put("mode_admin",0);
if (post == null) {
post = new serverObjects();
post.put("page", "blog_default");
}
if(!hasRights){
userDB.Entry userentry = switchboard.userDB.proxyAuth((String)header.get("Authorization", "xxxxxx"));
if(userentry != null && userentry.hasBlogRight()){
hasRights=true;
}
//opens login window if login link is clicked - contrib [MN]
else if(post.containsKey("login")){
prop.put("AUTHENTICATE","admin log-in");
}
}
String pagename = post.get("page", "blog_default");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = switchboard.blogDB.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null)
author = "anonymous";
else
author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if(hasRights && post.containsKey("delete") && post.get("delete").equals("sure")) {
switchboard.blogDB.delete(pagename);
+ pagename = "blog_default";
}
if (post.containsKey("submit") && (hasRights)) {
// store a new/edited blog-entry
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
Date date = null;
//set name for new entry or date for old entry
if(pagename.equals("blog_default"))
pagename = String.valueOf(System.currentTimeMillis());
else {
page = switchboard.blogDB.read(pagename); //must I read it again after submitting?
date = page.date();
}
- String subject = wikiCode.replaceHTML(post.get("subject",""));
+ String subject = post.get("subject","");
try {
switchboard.blogDB.write(switchboard.blogDB.newEntry(pagename, subject, author, ip, date, content));
} catch (IOException e) {}
// create a news message
HashMap map = new HashMap();
map.put("subject", subject);
map.put("page", pagename);
map.put("author", author);
map.put("ip", ip);
try {
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("blog_add", map));
} catch (IOException e) {}
}
page = switchboard.blogDB.read(pagename); //maybe "if(page == null)"
if (post.containsKey("edit")) {
//edit an entry
if(hasRights) {
try {
prop.put("mode", 1); //edit
- prop.put("mode_author", wikiCode.replaceHTML(author));
+ prop.put("mode_author", wikiCode.replaceHTML(page.author()));
prop.put("mode_pageid", page.key());
prop.put("mode_subject", wikiCode.replaceHTML(page.subject()));
prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("<","<").replaceAll(">",">"));
} catch (UnsupportedEncodingException e) {}
}
else {
prop.put("mode",3); //access denied (no rights)
}
}
else if(post.containsKey("preview")) {
//preview the page
if(hasRights) {
wikiCode wikiTransformer=new wikiCode(switchboard);
prop.put("mode", 2);//preview
prop.put("mode_pageid", pagename);
prop.put("mode_author", wikiCode.replaceHTML(author));
prop.put("mode_subject", wikiCode.replaceHTML(post.get("subject","")));
prop.put("mode_date", dateString(new Date()));
prop.put("mode_page", wikiTransformer.transform(post.get("content", "")));
prop.put("mode_page-code", post.get("content", "").replaceAll("<","<").replaceAll(">",">"));
}
else prop.put("mode",3); //access denied (no rights)
}
else if(post.containsKey("delete") && post.get("delete").equals("try")) {
if(hasRights) {
prop.put("mode",4);
prop.put("mode_pageid",pagename);
prop.put("mode_author",wikiCode.replaceHTML(page.author()));
prop.put("mode_subject",wikiCode.replaceHTML(page.subject()));
}
else prop.put("mode",3); //access denied (no rights)
}
else {
wikiCode wikiTransformer=new wikiCode(switchboard);
// show blog-entry/entries
prop.put("mode", 0); //viewing
if(pagename.equals("blog_default")) {
//index all entries
try {
Iterator i = switchboard.blogDB.keys(false);
String pageid;
blogBoard.entry entry;
int count = 0; //counts how many entries are shown to the user
int start = post.getInt("start",0); //indicates from where entries should be shown
int num = post.getInt("num",20); //indicates how many entries should be shown
int nextstart = start+num; //indicates the starting offset for next results
while(i.hasNext()) {
if(count >= num && num > 0)
break;
pageid = (String) i.next();
if(0 < start--)
continue;
entry = switchboard.blogDB.read(pageid);
prop.put("mode_entries_"+count+"_pageid",entry.key());
prop.put("mode_entries_"+count+"_subject", wikiCode.replaceHTML(entry.subject()));
prop.put("mode_entries_"+count+"_author", wikiCode.replaceHTML(entry.author()));
prop.put("mode_entries_"+count+"_date", dateString(entry.date()));
prop.put("mode_entries_"+count+"_page", wikiTransformer.transform(entry.page()));
if(hasRights) {
prop.put("mode_entries_"+count+"_admin", 1);
prop.put("mode_entries_"+count+"_admin_pageid",entry.key());
}
else prop.put("mode_entries_"+count+"_admin", 0);
++count;
}
prop.put("mode_entries",count);
if(i.hasNext()) {
prop.put("mode_moreentries",1); //more entries are availible
prop.put("mode_moreentries_start",nextstart);
prop.put("mode_moreentries_num",num);
}
else prop.put("moreentries",0);
} catch (IOException e) {
}
}
else {
//only show 1 entry
prop.put("mode_entries",1);
prop.put("mode_entries_0_pageid", page.key());
prop.put("mode_entries_0_subject", wikiCode.replaceHTML(page.subject()));
prop.put("mode_entries_0_author", wikiCode.replaceHTML(page.author()));
prop.put("mode_entries_0_date", dateString(page.date()));
prop.put("mode_entries_0_page", wikiTransformer.transform(page.page()));
if(hasRights) {
prop.put("mode_entries_0_admin", 1);
prop.put("mode_entries_0_admin_pageid",page.key());
}
}
}
// return rewrite properties
return prop;
}
}
| false | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
blogBoard.entry page = null;
boolean hasRights = switchboard.verifyAuthentication(header, true);
if(hasRights) prop.put("mode_admin",1);
else prop.put("mode_admin",0);
if (post == null) {
post = new serverObjects();
post.put("page", "blog_default");
}
if(!hasRights){
userDB.Entry userentry = switchboard.userDB.proxyAuth((String)header.get("Authorization", "xxxxxx"));
if(userentry != null && userentry.hasBlogRight()){
hasRights=true;
}
//opens login window if login link is clicked - contrib [MN]
else if(post.containsKey("login")){
prop.put("AUTHENTICATE","admin log-in");
}
}
String pagename = post.get("page", "blog_default");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = switchboard.blogDB.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null)
author = "anonymous";
else
author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if(hasRights && post.containsKey("delete") && post.get("delete").equals("sure")) {
switchboard.blogDB.delete(pagename);
}
if (post.containsKey("submit") && (hasRights)) {
// store a new/edited blog-entry
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
Date date = null;
//set name for new entry or date for old entry
if(pagename.equals("blog_default"))
pagename = String.valueOf(System.currentTimeMillis());
else {
page = switchboard.blogDB.read(pagename); //must I read it again after submitting?
date = page.date();
}
String subject = wikiCode.replaceHTML(post.get("subject",""));
try {
switchboard.blogDB.write(switchboard.blogDB.newEntry(pagename, subject, author, ip, date, content));
} catch (IOException e) {}
// create a news message
HashMap map = new HashMap();
map.put("subject", subject);
map.put("page", pagename);
map.put("author", author);
map.put("ip", ip);
try {
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("blog_add", map));
} catch (IOException e) {}
}
page = switchboard.blogDB.read(pagename); //maybe "if(page == null)"
if (post.containsKey("edit")) {
//edit an entry
if(hasRights) {
try {
prop.put("mode", 1); //edit
prop.put("mode_author", wikiCode.replaceHTML(author));
prop.put("mode_pageid", page.key());
prop.put("mode_subject", wikiCode.replaceHTML(page.subject()));
prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("<","<").replaceAll(">",">"));
} catch (UnsupportedEncodingException e) {}
}
else {
prop.put("mode",3); //access denied (no rights)
}
}
else if(post.containsKey("preview")) {
//preview the page
if(hasRights) {
wikiCode wikiTransformer=new wikiCode(switchboard);
prop.put("mode", 2);//preview
prop.put("mode_pageid", pagename);
prop.put("mode_author", wikiCode.replaceHTML(author));
prop.put("mode_subject", wikiCode.replaceHTML(post.get("subject","")));
prop.put("mode_date", dateString(new Date()));
prop.put("mode_page", wikiTransformer.transform(post.get("content", "")));
prop.put("mode_page-code", post.get("content", "").replaceAll("<","<").replaceAll(">",">"));
}
else prop.put("mode",3); //access denied (no rights)
}
else if(post.containsKey("delete") && post.get("delete").equals("try")) {
if(hasRights) {
prop.put("mode",4);
prop.put("mode_pageid",pagename);
prop.put("mode_author",wikiCode.replaceHTML(page.author()));
prop.put("mode_subject",wikiCode.replaceHTML(page.subject()));
}
else prop.put("mode",3); //access denied (no rights)
}
else {
wikiCode wikiTransformer=new wikiCode(switchboard);
// show blog-entry/entries
prop.put("mode", 0); //viewing
if(pagename.equals("blog_default")) {
//index all entries
try {
Iterator i = switchboard.blogDB.keys(false);
String pageid;
blogBoard.entry entry;
int count = 0; //counts how many entries are shown to the user
int start = post.getInt("start",0); //indicates from where entries should be shown
int num = post.getInt("num",20); //indicates how many entries should be shown
int nextstart = start+num; //indicates the starting offset for next results
while(i.hasNext()) {
if(count >= num && num > 0)
break;
pageid = (String) i.next();
if(0 < start--)
continue;
entry = switchboard.blogDB.read(pageid);
prop.put("mode_entries_"+count+"_pageid",entry.key());
prop.put("mode_entries_"+count+"_subject", wikiCode.replaceHTML(entry.subject()));
prop.put("mode_entries_"+count+"_author", wikiCode.replaceHTML(entry.author()));
prop.put("mode_entries_"+count+"_date", dateString(entry.date()));
prop.put("mode_entries_"+count+"_page", wikiTransformer.transform(entry.page()));
if(hasRights) {
prop.put("mode_entries_"+count+"_admin", 1);
prop.put("mode_entries_"+count+"_admin_pageid",entry.key());
}
else prop.put("mode_entries_"+count+"_admin", 0);
++count;
}
prop.put("mode_entries",count);
if(i.hasNext()) {
prop.put("mode_moreentries",1); //more entries are availible
prop.put("mode_moreentries_start",nextstart);
prop.put("mode_moreentries_num",num);
}
else prop.put("moreentries",0);
} catch (IOException e) {
}
}
else {
//only show 1 entry
prop.put("mode_entries",1);
prop.put("mode_entries_0_pageid", page.key());
prop.put("mode_entries_0_subject", wikiCode.replaceHTML(page.subject()));
prop.put("mode_entries_0_author", wikiCode.replaceHTML(page.author()));
prop.put("mode_entries_0_date", dateString(page.date()));
prop.put("mode_entries_0_page", wikiTransformer.transform(page.page()));
if(hasRights) {
prop.put("mode_entries_0_admin", 1);
prop.put("mode_entries_0_admin_pageid",page.key());
}
}
}
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
blogBoard.entry page = null;
boolean hasRights = switchboard.verifyAuthentication(header, true);
if(hasRights) prop.put("mode_admin",1);
else prop.put("mode_admin",0);
if (post == null) {
post = new serverObjects();
post.put("page", "blog_default");
}
if(!hasRights){
userDB.Entry userentry = switchboard.userDB.proxyAuth((String)header.get("Authorization", "xxxxxx"));
if(userentry != null && userentry.hasBlogRight()){
hasRights=true;
}
//opens login window if login link is clicked - contrib [MN]
else if(post.containsKey("login")){
prop.put("AUTHENTICATE","admin log-in");
}
}
String pagename = post.get("page", "blog_default");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = switchboard.blogDB.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null)
author = "anonymous";
else
author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if(hasRights && post.containsKey("delete") && post.get("delete").equals("sure")) {
switchboard.blogDB.delete(pagename);
pagename = "blog_default";
}
if (post.containsKey("submit") && (hasRights)) {
// store a new/edited blog-entry
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
Date date = null;
//set name for new entry or date for old entry
if(pagename.equals("blog_default"))
pagename = String.valueOf(System.currentTimeMillis());
else {
page = switchboard.blogDB.read(pagename); //must I read it again after submitting?
date = page.date();
}
String subject = post.get("subject","");
try {
switchboard.blogDB.write(switchboard.blogDB.newEntry(pagename, subject, author, ip, date, content));
} catch (IOException e) {}
// create a news message
HashMap map = new HashMap();
map.put("subject", subject);
map.put("page", pagename);
map.put("author", author);
map.put("ip", ip);
try {
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("blog_add", map));
} catch (IOException e) {}
}
page = switchboard.blogDB.read(pagename); //maybe "if(page == null)"
if (post.containsKey("edit")) {
//edit an entry
if(hasRights) {
try {
prop.put("mode", 1); //edit
prop.put("mode_author", wikiCode.replaceHTML(page.author()));
prop.put("mode_pageid", page.key());
prop.put("mode_subject", wikiCode.replaceHTML(page.subject()));
prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("<","<").replaceAll(">",">"));
} catch (UnsupportedEncodingException e) {}
}
else {
prop.put("mode",3); //access denied (no rights)
}
}
else if(post.containsKey("preview")) {
//preview the page
if(hasRights) {
wikiCode wikiTransformer=new wikiCode(switchboard);
prop.put("mode", 2);//preview
prop.put("mode_pageid", pagename);
prop.put("mode_author", wikiCode.replaceHTML(author));
prop.put("mode_subject", wikiCode.replaceHTML(post.get("subject","")));
prop.put("mode_date", dateString(new Date()));
prop.put("mode_page", wikiTransformer.transform(post.get("content", "")));
prop.put("mode_page-code", post.get("content", "").replaceAll("<","<").replaceAll(">",">"));
}
else prop.put("mode",3); //access denied (no rights)
}
else if(post.containsKey("delete") && post.get("delete").equals("try")) {
if(hasRights) {
prop.put("mode",4);
prop.put("mode_pageid",pagename);
prop.put("mode_author",wikiCode.replaceHTML(page.author()));
prop.put("mode_subject",wikiCode.replaceHTML(page.subject()));
}
else prop.put("mode",3); //access denied (no rights)
}
else {
wikiCode wikiTransformer=new wikiCode(switchboard);
// show blog-entry/entries
prop.put("mode", 0); //viewing
if(pagename.equals("blog_default")) {
//index all entries
try {
Iterator i = switchboard.blogDB.keys(false);
String pageid;
blogBoard.entry entry;
int count = 0; //counts how many entries are shown to the user
int start = post.getInt("start",0); //indicates from where entries should be shown
int num = post.getInt("num",20); //indicates how many entries should be shown
int nextstart = start+num; //indicates the starting offset for next results
while(i.hasNext()) {
if(count >= num && num > 0)
break;
pageid = (String) i.next();
if(0 < start--)
continue;
entry = switchboard.blogDB.read(pageid);
prop.put("mode_entries_"+count+"_pageid",entry.key());
prop.put("mode_entries_"+count+"_subject", wikiCode.replaceHTML(entry.subject()));
prop.put("mode_entries_"+count+"_author", wikiCode.replaceHTML(entry.author()));
prop.put("mode_entries_"+count+"_date", dateString(entry.date()));
prop.put("mode_entries_"+count+"_page", wikiTransformer.transform(entry.page()));
if(hasRights) {
prop.put("mode_entries_"+count+"_admin", 1);
prop.put("mode_entries_"+count+"_admin_pageid",entry.key());
}
else prop.put("mode_entries_"+count+"_admin", 0);
++count;
}
prop.put("mode_entries",count);
if(i.hasNext()) {
prop.put("mode_moreentries",1); //more entries are availible
prop.put("mode_moreentries_start",nextstart);
prop.put("mode_moreentries_num",num);
}
else prop.put("moreentries",0);
} catch (IOException e) {
}
}
else {
//only show 1 entry
prop.put("mode_entries",1);
prop.put("mode_entries_0_pageid", page.key());
prop.put("mode_entries_0_subject", wikiCode.replaceHTML(page.subject()));
prop.put("mode_entries_0_author", wikiCode.replaceHTML(page.author()));
prop.put("mode_entries_0_date", dateString(page.date()));
prop.put("mode_entries_0_page", wikiTransformer.transform(page.page()));
if(hasRights) {
prop.put("mode_entries_0_admin", 1);
prop.put("mode_entries_0_admin_pageid",page.key());
}
}
}
// return rewrite properties
return prop;
}
|
diff --git a/museumassault/MuseumAssault.java b/museumassault/MuseumAssault.java
index 55ce1aa..f87be8d 100644
--- a/museumassault/MuseumAssault.java
+++ b/museumassault/MuseumAssault.java
@@ -1,87 +1,87 @@
package museumassault;
import java.util.Random;
import museumassault.monitor.Corridor;
import museumassault.monitor.Logger;
import museumassault.monitor.Room;
import museumassault.monitor.SharedSite;
/**
* MuseumAssault main class.
*
* @author Andre Cruz <[email protected]>
*/
public class MuseumAssault
{
/**
* Program entry point.
*
* @param args the command line arguments
*/
public static void main(String[] args)
{
// Configurable params
int nrChiefs = 1;
int nrTeams = 5;
int nrThievesPerTeam = 3;
int nrTotalThieves = 7;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
int maxDistanceBetweenRoomAndOutside = 10;
int maxPowerPerThief = 5;
int maxCanvasInRoom = 20;
String logFileName = "log.txt";
+ // Initializing the necessary entities
Random random = new Random();
Logger logger = new Logger(logFileName);
- // Initializing the necessary entities
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
rooms[x] = new Room(x + 1, random.nextInt(maxCanvasInRoom - 1) + 1, new Corridor((random.nextInt(maxDistanceBetweenRoomAndOutside - 1) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[nrTotalThieves];
for (int x = 0; x < nrTotalThieves; x++) {
Thief thief = new Thief(x + 1, random.nextInt(maxPowerPerThief - 1) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams, rooms);
// Start the threads
for (int x = 0; x < nrTotalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}
}
| false | true | public static void main(String[] args)
{
// Configurable params
int nrChiefs = 1;
int nrTeams = 5;
int nrThievesPerTeam = 3;
int nrTotalThieves = 7;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
int maxDistanceBetweenRoomAndOutside = 10;
int maxPowerPerThief = 5;
int maxCanvasInRoom = 20;
String logFileName = "log.txt";
Random random = new Random();
Logger logger = new Logger(logFileName);
// Initializing the necessary entities
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
rooms[x] = new Room(x + 1, random.nextInt(maxCanvasInRoom - 1) + 1, new Corridor((random.nextInt(maxDistanceBetweenRoomAndOutside - 1) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[nrTotalThieves];
for (int x = 0; x < nrTotalThieves; x++) {
Thief thief = new Thief(x + 1, random.nextInt(maxPowerPerThief - 1) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams, rooms);
// Start the threads
for (int x = 0; x < nrTotalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}
| public static void main(String[] args)
{
// Configurable params
int nrChiefs = 1;
int nrTeams = 5;
int nrThievesPerTeam = 3;
int nrTotalThieves = 7;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
int maxDistanceBetweenRoomAndOutside = 10;
int maxPowerPerThief = 5;
int maxCanvasInRoom = 20;
String logFileName = "log.txt";
// Initializing the necessary entities
Random random = new Random();
Logger logger = new Logger(logFileName);
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
rooms[x] = new Room(x + 1, random.nextInt(maxCanvasInRoom - 1) + 1, new Corridor((random.nextInt(maxDistanceBetweenRoomAndOutside - 1) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[nrTotalThieves];
for (int x = 0; x < nrTotalThieves; x++) {
Thief thief = new Thief(x + 1, random.nextInt(maxPowerPerThief - 1) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams, rooms);
// Start the threads
for (int x = 0; x < nrTotalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}
|
diff --git a/src/il/technion/ewolf/server/PokeMessagesAcceptor.java b/src/il/technion/ewolf/server/PokeMessagesAcceptor.java
index 1d819ef..705e6db 100644
--- a/src/il/technion/ewolf/server/PokeMessagesAcceptor.java
+++ b/src/il/technion/ewolf/server/PokeMessagesAcceptor.java
@@ -1,73 +1,73 @@
package il.technion.ewolf.server;
import il.technion.ewolf.ewolf.WolfPack;
import il.technion.ewolf.msg.PokeMessage;
import il.technion.ewolf.msg.SocialMessage;
import il.technion.ewolf.server.cache.ICache;
import il.technion.ewolf.socialfs.Profile;
import il.technion.ewolf.socialfs.exception.ProfileNotFoundException;
import il.technion.ewolf.stash.exception.GroupNotFoundException;
import java.util.List;
import java.util.Map;
import com.google.inject.Inject;
public class PokeMessagesAcceptor implements Runnable {
private final ICache<List<SocialMessage>> inboxCache;
private final ICache<Map<String,List<Profile>>> wolfpacksMembersCache;
private final ICache<Map<String, WolfPack>> wolfpacksCache;
private static final String INVITERS_WOLFPACK = "inviters";
@Inject
public PokeMessagesAcceptor(ICache<List<SocialMessage>> inboxCache,
ICache<Map<String,List<Profile>>> wolfpacksMembersCache,
ICache<Map<String, WolfPack>> wolfpacksCache) {
this.inboxCache = inboxCache;
this.wolfpacksMembersCache = wolfpacksMembersCache;
this.wolfpacksCache = wolfpacksCache;
}
@Override
public void run() {
try {
Map<String, WolfPack> wolfpacksMap = wolfpacksCache.get();
WolfPack inviters = wolfpacksMap.get(INVITERS_WOLFPACK);
while (true) {
List<SocialMessage> messages = inboxCache.get();
Map<String,List<Profile>> wolfpacksMembersMap = wolfpacksMembersCache.get();
wolfpacksMap = wolfpacksCache.get();
for (SocialMessage m : messages) {
if (m.getClass() == PokeMessage.class) {
List<Profile> invitersList = wolfpacksMembersMap.get(INVITERS_WOLFPACK);
try {
Profile inviter = m.getSender();
if (invitersList != null && !invitersList.contains(inviter)) {
- //FIXME adding to inviterss sends Poke message too
+ //FIXME adding to inviters sends Poke message too
inviters.addMember(inviter);
+ wolfpacksMembersCache.update();
+ wolfpacksMembersMap = wolfpacksMembersCache.get();
}
} catch (GroupNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProfileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((PokeMessage)m).accept();
- wolfpacksMembersCache.update();
- continue;
}
}
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
//TODO what can I do here?
}
}
}
| false | true | public void run() {
try {
Map<String, WolfPack> wolfpacksMap = wolfpacksCache.get();
WolfPack inviters = wolfpacksMap.get(INVITERS_WOLFPACK);
while (true) {
List<SocialMessage> messages = inboxCache.get();
Map<String,List<Profile>> wolfpacksMembersMap = wolfpacksMembersCache.get();
wolfpacksMap = wolfpacksCache.get();
for (SocialMessage m : messages) {
if (m.getClass() == PokeMessage.class) {
List<Profile> invitersList = wolfpacksMembersMap.get(INVITERS_WOLFPACK);
try {
Profile inviter = m.getSender();
if (invitersList != null && !invitersList.contains(inviter)) {
//FIXME adding to inviterss sends Poke message too
inviters.addMember(inviter);
}
} catch (GroupNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProfileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((PokeMessage)m).accept();
wolfpacksMembersCache.update();
continue;
}
}
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
//TODO what can I do here?
}
}
| public void run() {
try {
Map<String, WolfPack> wolfpacksMap = wolfpacksCache.get();
WolfPack inviters = wolfpacksMap.get(INVITERS_WOLFPACK);
while (true) {
List<SocialMessage> messages = inboxCache.get();
Map<String,List<Profile>> wolfpacksMembersMap = wolfpacksMembersCache.get();
wolfpacksMap = wolfpacksCache.get();
for (SocialMessage m : messages) {
if (m.getClass() == PokeMessage.class) {
List<Profile> invitersList = wolfpacksMembersMap.get(INVITERS_WOLFPACK);
try {
Profile inviter = m.getSender();
if (invitersList != null && !invitersList.contains(inviter)) {
//FIXME adding to inviters sends Poke message too
inviters.addMember(inviter);
wolfpacksMembersCache.update();
wolfpacksMembersMap = wolfpacksMembersCache.get();
}
} catch (GroupNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProfileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((PokeMessage)m).accept();
}
}
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
//TODO what can I do here?
}
}
|
diff --git a/components/ome-xml/src/ome/xml/r200706/SampleTest.java b/components/ome-xml/src/ome/xml/r200706/SampleTest.java
index 1e1a92146..5853d8cfd 100644
--- a/components/ome-xml/src/ome/xml/r200706/SampleTest.java
+++ b/components/ome-xml/src/ome/xml/r200706/SampleTest.java
@@ -1,1019 +1,1019 @@
/*
* org.xml.r200706.SampleTest
*
*-----------------------------------------------------------------------------
*
* Copyright (C) 2006 Open Microscopy Environment
* Massachusetts Institute of Technology,
* National Institutes of Health,
* University of Dundee,
* University of Wisconsin-Madison
*
*
*
* 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 (at your option) 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. 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
*
*-----------------------------------------------------------------------------
*/
/*-----------------------------------------------------------------------------
*
* Written by: Curtis Rueden <[email protected]>
*
*-----------------------------------------------------------------------------
*/
package ome.xml.r200706;
import java.io.*;
import java.util.Vector;
import ome.xml.DOMUtil;
import ome.xml.OMEXMLFactory;
import ome.xml.r200706.ome.*;
/** Tests the ome.xml.r200706 packages. */
public final class SampleTest {
// -- Constructor --
private SampleTest() { }
// -- Testing methods --
/** Tests the integrity of the given node against the Sample.ome file. */
public static void testSample(OMENode ome) throws Exception {
// -- Depth 1 --
// check OME node
int projectCount = ome.getProjectCount();
Vector projectList = ome.getProjectList();
checkCount("Project", projectCount, projectList, 1);
int datasetCount = ome.getDatasetCount();
Vector datasetList = ome.getDatasetList();
checkCount("Dataset", datasetCount, datasetList, 1);
int experimentCount = ome.getExperimentCount();
Vector experimentList = ome.getExperimentList();
checkCount("Experiment", experimentCount, experimentList, 1);
int plateCount = ome.getPlateCount();
Vector plateList = ome.getPlateList();
checkCount("Plate", plateCount, plateList, 1);
int screenCount = ome.getScreenCount();
Vector screenList = ome.getScreenList();
checkCount("Screen", screenCount, screenList, 1);
int experimenterCount = ome.getExperimenterCount();
Vector experimenterList = ome.getExperimenterList();
checkCount("Experimenter", experimenterCount, experimenterList, 1);
int groupCount = ome.getGroupCount();
Vector groupList = ome.getGroupList();
checkCount("Group", groupCount, groupList, 1);
int instrumentCount = ome.getInstrumentCount();
Vector instrumentList = ome.getInstrumentList();
checkCount("Instrument", instrumentCount, instrumentList, 1);
int imageCount = ome.getImageCount();
Vector imageList = ome.getImageList();
checkCount("Image", imageCount, imageList, 1);
// SemanticTypeDefinitionsNode semanticTypeDefinitions =
// ome.getSemanticTypeDefinitions();
// checkNull("SemanticTypeDefinitions", semanticTypeDefinitions);
// AnalysisModuleLibraryNode analysisModuleLibrary =
// ome.getAnalysisModuleLibrary();
// checkNull("AnalysisModuleLibrary", analysisModuleLibrary);
// CustomAttributesNode customAttributes = ome.getCustomAttributes();
// checkNull("CustomAttributes", customAttributes);
// -- Depth 2 --
// check OME/Project node
ProjectNode project = (ProjectNode) projectList.get(0);
ExperimenterNode projectExperimenter = project.getExperimenter();
checkNotNull("Project Experimenter", projectExperimenter);
// TODO check projectExperimenter further
String projectDescription = project.getDescription();
checkNull("Project Description", projectDescription);
GroupNode projectGroup = project.getGroup();
checkNotNull("Project Group", projectGroup);
// TODO check projectGroup further
String projectName = project.getName();
checkValue("Project Name", projectName, "Stress Response Pathway");
// check OME/Dataset node
DatasetNode dataset = (DatasetNode) datasetList.get(0);
Boolean datasetLocked = dataset.getLocked();
String datasetDescription = dataset.getDescription();
ExperimenterNode datasetExperimenter = dataset.getExperimenter();
int datasetProjectCount = dataset.getProjectCount();
Vector datasetProjectList = dataset.getProjectList();
GroupNode datasetGroup = dataset.getGroup();
String datasetCustomAttributes = dataset.getCustomAttributes();
String datasetName = dataset.getName();
// check OME/Experiment node
ExperimentNode experiment = (ExperimentNode) experimentList.get(0);
String experimentID = experiment.getNodeID();
checkValue("Experiment ID", experimentID,
"urn:lsid:foo.bar.com:Experiment:123456");
String experimentDescription = experiment.getDescription();
checkValue("Experiment Description", experimentDescription,
"This was an experiment.");
ExperimenterNode experimentExperimenter = experiment.getExperimenter();
checkNotNull("Experiment Experimenter", experimentExperimenter);
// TODO check experimentExperimenter further
int experimentMicrobeamManipulationCount =
experiment.getMicrobeamManipulationCount();
Vector experimentMicrobeamManipulationList =
experiment.getMicrobeamManipulationList();
checkCount("Experiment MicrobeamManipulation",
experimentMicrobeamManipulationCount,
experimentMicrobeamManipulationList, 0);
String experimentType = experiment.getType();
checkValue("Experiment Type", experimentType, "TimeLapse");
// check OME/Plate node
// TODO
// check OME/Screen node
// TODO
// check OME/Experimenter node
ExperimenterNode experimenter = (ExperimenterNode) experimenterList.get(0);
String experimenterID = experimenter.getNodeID();
checkValue("Experimenter ID", experimenterID,
"urn:lsid:foo.bar.com:Experimenter:123456");
String experimenterFirstName = experimenter.getFirstName();
checkValue("Experimenter FirstName", experimenterFirstName, "Nicola");
String experimenterLastName = experimenter.getLastName();
checkValue("Experimenter LastName", experimenterLastName, "Sacco");
String experimenterEmail = experimenter.getEmail();
checkValue("Experimenter Email",
experimenterEmail, "[email protected]");
String experimenterInstitution = experimenter.getInstitution();
checkNull("Experimenter Institution", experimenterInstitution);
String experimenterOMEName = experimenter.getOMEName();
checkValue("Experimenter OMEName", experimenterOMEName, "nico");
int experimenterGroupCount = experimenter.getGroupCount();
Vector experimenterGroupList = experimenter.getGroupList();
checkCount("Experimenter Group",
experimenterGroupCount, experimenterGroupList, 2);
// check OME/Group node
// TODO
// check against projectGroup, datasetGroup
// check OME/Instrument node
InstrumentNode instrument = (InstrumentNode) instrumentList.get(0);
checkNotNull("Instrument", instrument);
MicroscopeNode instrumentMicroscope = instrument.getMicroscope();
checkNotNull("Instrument Microscope", instrumentMicroscope);
int instrumentLightSourceCount = instrument.getLightSourceCount();
Vector instrumentLightSourceList = instrument.getLightSourceList();
checkCount("Instrument LightSource",
instrumentLightSourceCount, instrumentLightSourceList, 2);
int instrumentDetectorCount = instrument.getDetectorCount();
Vector instrumentDetectorList = instrument.getDetectorList();
checkCount("Instrument Detector",
instrumentDetectorCount, instrumentDetectorList, 1);
int instrumentObjectiveCount = instrument.getObjectiveCount();
Vector instrumentObjectiveList = instrument.getObjectiveList();
checkCount("Instrument Objective",
instrumentObjectiveCount, instrumentObjectiveList, 1);
int instrumentFilterSetCount = instrument.getFilterSetCount();
Vector instrumentFilterSetList = instrument.getFilterSetList();
checkCount("Instrument FilterSet",
instrumentFilterSetCount, instrumentFilterSetList, 1);
int instrumentFilterCount = instrument.getFilterCount();
Vector instrumentFilterList = instrument.getFilterList();
checkCount("Instrument Filter",
instrumentFilterCount, instrumentFilterList, 2);
int instrumentDichroicCount = instrument.getDichroicCount();
Vector instrumentDichroicList = instrument.getDichroicList();
checkCount("Instrument Dichroic",
instrumentDichroicCount, instrumentDichroicList, 0);
int instrumentOTFCount = instrument.getOTFCount();
Vector instrumentOTFList = instrument.getOTFList();
checkCount("Instrument OTF",
instrumentOTFCount, instrumentOTFList, 1);
// check OME/Image node
ImageNode image = (ImageNode) imageList.get(0);
checkNotNull("Image", image);
String imageID = image.getNodeID();
checkValue("Image ID", imageID, "urn:lsid:foo.bar.com:Image:123456");
String imageCreationDate = image.getCreationDate();
checkValue("Image CreationDate", imageCreationDate, "1988-04-07T18:39:09");
ExperimenterNode imageExperimenter = image.getExperimenter();
checkNotNull("Image Experimenter", imageExperimenter);
// TODO check imageExperimenter further
String imageDescription = image.getDescription();
checkValue("Image Description", imageDescription, "This is an Image");
ExperimentNode imageExperiment = image.getExperiment();
checkNotNull("Image Experiment", imageExperiment);
// TODO check imageExperiment further
GroupNode imageGroup = image.getGroup();
checkNotNull("Image Group", imageGroup);
// TODO check imageGroup further
int imageDatasetCount = image.getDatasetCount();
Vector imageDatasetList = image.getDatasetList();
checkCount("Image Dataset", imageDatasetCount, imageDatasetList, 1);
InstrumentNode imageInstrument = image.getInstrument();
checkNotNull("Image Instrument", imageInstrument);
// TODO check imageInstrument further
ObjectiveSettingsNode imageObjectiveSettings = image.getObjectiveSettings();
checkNull("Image ObjectiveSettings", imageObjectiveSettings);
ImagingEnvironmentNode imageImagingEnvironment =
image.getImagingEnvironment();
checkNotNull("Image ImagingEnvironment", imageImagingEnvironment);
ThumbnailNode imageThumbnail = image.getThumbnail();
checkNotNull("Image Thumbnail", imageThumbnail);
int imageLogicalChannelCount = image.getLogicalChannelCount();
Vector imageLogicalChannelList = image.getLogicalChannelList();
checkCount("Image LogicalChannel", imageLogicalChannelCount,
imageLogicalChannelList, 1);
DisplayOptionsNode imageDisplayOptions = image.getDisplayOptions();
checkNotNull("Image DisplayOptions", imageDisplayOptions);
StageLabelNode imageStageLabel = image.getStageLabel();
checkNotNull("Image StageLabel", imageStageLabel);
int imagePixelsCount = image.getPixelsCount();
Vector imagePixelsList = image.getPixelsList();
checkCount("Image Pixels", imagePixelsCount, imagePixelsList, 1);
PixelsNode imageAcquiredPixels = image.getAcquiredPixels();
checkNull("Image AcquiredPixels", imageAcquiredPixels);
int imageRegionCount = image.getRegionCount();
Vector imageRegionList = image.getRegionList();
checkCount("Image Region", imageRegionCount, imageRegionList, 0);
String imageCustomAttributes = image.getCustomAttributes();
checkNull("Image CustomAttributes", imageCustomAttributes);
int imageROICount = image.getROICount();
Vector imageROIList = image.getROIList();
checkCount("Image ROI", imageROICount, imageROIList, 0);
int imageMicrobeamManipulationCount =
image.getMicrobeamManipulationCount();
Vector imageMicrobeamManipulationList =
image.getMicrobeamManipulationList();
checkCount("Image MicrobeamManipulation", imageMicrobeamManipulationCount,
imageMicrobeamManipulationList, 0);
String imageName = image.getName();
checkValue("Image Name", imageName, "P1W1S1");
// -- Depth 3 --
// check OME/Dataset/CustomAttributes
// TODO
// check OME/Screen/Reagent
// TODO
// check OME/Screen/ScreenAcquisition
// TODO
// check OME/Instrument/Microscope
// TODO
// check OME/Instrument/LightSource-1
// TODO
// check OME/Instrument/LightSource-2
// TODO
// check OME/Instrument/Detector
// TODO
// check OME/Instrument/Objective
// TODO
// check OME/Instrument/FilterSet
// TODO
// check OME/Instrument/Filter-1
FilterNode instrumentFilter1 = (FilterNode) instrumentFilterList.get(0);
String instrumentFilter1ID = instrumentFilter1.getNodeID();
checkValue("Instrument Filter-1 ID", instrumentFilter1ID,
"urn:lsid:foo.bar.com:Filter:123456");
String instrumentFilter1Manufacturer = instrumentFilter1.getManufacturer();
checkValue("Instrument Filter-1 Manufacturer",
instrumentFilter1Manufacturer, "Omega");
String instrumentFilter1Model = instrumentFilter1.getModel();
checkValue("Instrument Filter-1 Model",
instrumentFilter1Model, "SuperGFP");
String instrumentFilter1LotNumber = instrumentFilter1.getLotNumber();
checkNull("Instrument Filter-1 LotNumber", instrumentFilter1LotNumber);
TransmittanceRangeNode instrumentFilter1TransmittanceRange =
instrumentFilter1.getTransmittanceRange();
checkNotNull("Instrument Filter-1 TransmittanceRange",
instrumentFilter1TransmittanceRange);
String instrumentFilter1Type = instrumentFilter1.getType();
checkNull("Instrument Filter-1 Type", instrumentFilter1Type);
String instrumentFilter1FilterWheel = instrumentFilter1.getFilterWheel();
checkNull("Instrument Filter-1 FilterWheel", instrumentFilter1FilterWheel);
// check OME/Instrument/Filter-2
FilterNode instrumentFilter2 = (FilterNode) instrumentFilterList.get(1);
String instrumentFilter2ID = instrumentFilter2.getNodeID();
checkValue("Instrument Filter-2 ID", instrumentFilter2ID,
"urn:lsid:foo.bar.com:Filter:1234567");
String instrumentFilter2Manufacturer = instrumentFilter2.getManufacturer();
checkValue("Instrument Filter-2 Manufacturer",
instrumentFilter2Manufacturer, "Omega");
String instrumentFilter2Model = instrumentFilter2.getModel();
checkValue("Instrument Filter-2 Model",
instrumentFilter2Model, "SuperGFP");
String instrumentFilter2LotNumber = instrumentFilter2.getLotNumber();
checkNull("Instrument Filter-2 LotNumber", instrumentFilter2LotNumber);
TransmittanceRangeNode instrumentFilter2TransmittanceRange =
instrumentFilter2.getTransmittanceRange();
checkNotNull("Instrument Filter-2 TransmittanceRange",
instrumentFilter2TransmittanceRange);
String instrumentFilter2Type = instrumentFilter2.getType();
checkNull("Instrument Filter-2 Type", instrumentFilter2Type);
String instrumentFilter2FilterWheel = instrumentFilter2.getFilterWheel();
checkNull("Instrument Filter-2 FilterWheel", instrumentFilter2FilterWheel);
// check OME/Instrument/OTF
// TODO
// check OME/Image/ImagingEnvironment
// TODO
// check OME/Image/Thumbnail
// TODO
// check OME/Image/LogicalChannel
LogicalChannelNode imageLogicalChannel =
(LogicalChannelNode) imageLogicalChannelList.get(0);
checkNotNull("Image LogicalChannel", imageLogicalChannel);
String imageLogicalChannelID = imageLogicalChannel.getNodeID();
checkValue("Image LogicalChannel ID", imageLogicalChannelID,
"urn:lsid:foo.bar.com:LogicalChannel:123456");
LightSourceNode imageLogicalChannelLightSource =
imageLogicalChannel.getLightSource();
checkNotNull("Image LogicalChannel LightSource",
imageLogicalChannelLightSource);
// TODO check imageLogicalChannelLightSource further
OTFNode imageLogicalChannelOTF = imageLogicalChannel.getOTF();
checkNotNull("Image LogicalChannel OTF", imageLogicalChannelOTF);
// TODO check imageLogicalChannelOTF further
DetectorNode imageLogicalChannelDetector =
imageLogicalChannel.getDetector();
checkNotNull("Image LogicalChannel Detector", imageLogicalChannelDetector);
// TODO check imageLogicalChannelDetector further
FilterSetNode imageLogicalChannelFilterSet =
imageLogicalChannel.getFilterSet();
checkNotNull("Image LogicalChannel FilterSet",
imageLogicalChannelFilterSet);
// TODO check imageLogicalChannelFilterSet further
int imageLogicalChannelChannelComponentCount =
imageLogicalChannel.getChannelComponentCount();
Vector imageLogicalChannelChannelComponentList =
imageLogicalChannel.getChannelComponentList();
checkCount("Image LogicalChannel ChannelComponent",
imageLogicalChannelChannelComponentCount,
imageLogicalChannelChannelComponentList, 1);
String imageLogicalChannelName = imageLogicalChannel.getName();
checkValue("Image LogicalChannel Name", imageLogicalChannelName, "Ch 1");
Integer imageLogicalChannelSamplesPerPixel =
imageLogicalChannel.getSamplesPerPixel();
checkNull("Image LogicalChannel SamplesPerPixel",
imageLogicalChannelSamplesPerPixel);
FilterNode imageLogicalChannelSecondaryEmissionFilter =
- imageLogicalChannel.getSecondaryEmissionFilter();
+ imageLogicalChannel.getSecondaryEmissionFilterNode();
checkNull("Image LogicalChannel SecondaryEmissionFilter",
imageLogicalChannelSecondaryEmissionFilter);
FilterNode imageLogicalChannelSecondaryExcitationFilter =
- imageLogicalChannel.getSecondaryExcitationFilter();
+ imageLogicalChannel.getSecondaryExcitationFilterNode();
checkNull("Image LogicalChannel SecondaryExcitationFilter",
imageLogicalChannelSecondaryExcitationFilter);
String imageLogicalChannelIlluminationType =
imageLogicalChannel.getIlluminationType();
checkValue("Image LogicalChannel IlluminationType",
imageLogicalChannelIlluminationType, "Epifluorescence");
Integer imageLogicalChannelPinholeSize =
imageLogicalChannel.getPinholeSize();
checkNull("Image LogicalChannel PinholeSize",
imageLogicalChannelPinholeSize);
String imageLogicalChannelPhotometricInterpretation =
imageLogicalChannel.getPhotometricInterpretation();
checkNull("Image LogicalChannel PhotometricInterpretation",
imageLogicalChannelPhotometricInterpretation);
String imageLogicalChannelMode = imageLogicalChannel.getMode();
checkNull("Image LogicalChannel Mode", imageLogicalChannelMode);
String imageLogicalChannelContrastMethod =
imageLogicalChannel.getContrastMethod();
checkNull("Image LogicalChannel ContrastMethod",
imageLogicalChannelContrastMethod);
Integer imageLogicalChannelExWave = imageLogicalChannel.getExWave();
checkValue("Image LogicalChannel ExWave",
imageLogicalChannelExWave, new Integer(490));
Integer imageLogicalChannelEmWave = imageLogicalChannel.getEmWave();
checkValue("Image LogicalChannel EmWave",
imageLogicalChannelEmWave, new Integer(528));
String imageLogicalChannelFluor = imageLogicalChannel.getFluor();
checkValue("Image LogicalChannel Fluor",
imageLogicalChannelFluor, "GFP");
Float imageLogicalChannelNdFilter = imageLogicalChannel.getNdFilter();
checkValue("Image LogicalChannel NdFilter",
imageLogicalChannelNdFilter, new Float(0.0f));
Integer imageLogicalChannelPockelCellSetting =
imageLogicalChannel.getPockelCellSetting();
checkNull("Image LogicalChannel PockelCellSetting",
imageLogicalChannelPockelCellSetting);
// check OME/Image/DisplayOptions
String imageDisplayOptionsID = imageDisplayOptions.getNodeID();
checkValue("Image DisplayOptions ID", imageDisplayOptionsID,
"urn:lsid:foo.bar.com:DisplayOptions:123456");
ChannelSpecTypeNode imageDisplayOptionsRedChannel =
imageDisplayOptions.getRedChannel();
checkNotNull("Image DisplayOptions RedChannel",
imageDisplayOptionsRedChannel);
ChannelSpecTypeNode imageDisplayOptionsGreenChannel =
imageDisplayOptions.getGreenChannel();
checkNotNull("Image DisplayOptions GreenChannel",
imageDisplayOptionsGreenChannel);
ChannelSpecTypeNode imageDisplayOptionsBlueChannel =
imageDisplayOptions.getBlueChannel();
checkNotNull("Image DisplayOptions BlueChannel",
imageDisplayOptionsBlueChannel);
GreyChannelNode imageDisplayOptionsGreyChannel =
imageDisplayOptions.getGreyChannel();
checkNotNull("Image DisplayOptions GreyChannel",
imageDisplayOptionsGreyChannel);
ProjectionNode imageDisplayOptionsProjection =
imageDisplayOptions.getProjection();
checkNotNull("Image DisplayOptions Projection",
imageDisplayOptionsProjection);
TimeNode imageDisplayOptionsTime =
imageDisplayOptions.getTime();
checkNotNull("Image DisplayOptions Time",
imageDisplayOptionsTime);
int imageDisplayOptionsROICount = imageDisplayOptions.getROICount();
Vector imageDisplayOptionsROIList = imageDisplayOptions.getROIList();
checkCount("Image DisplayOptions ROI",
imageDisplayOptionsROICount, imageDisplayOptionsROIList, 1);
Float imageDisplayOptionsZoom = imageDisplayOptions.getZoom();
checkValue("Image DisplayOptions Zoom",
imageDisplayOptionsZoom, new Float(1.0f));
String imageDisplayOptionsDisplay = imageDisplayOptions.getDisplay();
checkValue("Image DisplayOptions Display",
imageDisplayOptionsDisplay, "RGB");
// check OME/Image/StageLabel
String imageStageLabelName = imageStageLabel.getName();
checkValue("Image StageLabel Name", imageStageLabelName, "Zulu");
Float imageStageLabelX = imageStageLabel.getX();
checkValue("Image StageLabel X", imageStageLabelX, new Float(123));
Float imageStageLabelY = imageStageLabel.getY();
checkValue("Image StageLabel Y", imageStageLabelY, new Float(456));
Float imageStageLabelZ = imageStageLabel.getZ();
checkValue("Image StageLabel Z", imageStageLabelZ, new Float(789));
// check OME/Image/Pixels
PixelsNode imagePixels = (PixelsNode) imagePixelsList.get(0);
checkNotNull("Image Pixels", imagePixels);
int imagePixelsTiffDataCount = imagePixels.getTiffDataCount();
Vector imagePixelsTiffDataList = imagePixels.getTiffDataList();
checkCount("Image Pixels TiffData", imagePixelsTiffDataCount,
imagePixelsTiffDataList, 0);
int imagePixelsPlaneCount = imagePixels.getPlaneCount();
Vector imagePixelsPlaneList = imagePixels.getPlaneList();
checkCount("Image Pixels Plane", imagePixelsPlaneCount,
imagePixelsPlaneList, 0);
String imagePixelsDimensionOrder = imagePixels.getDimensionOrder();
checkValue("Image Pixels DimensionOrder",
imagePixelsDimensionOrder, "XYZCT");
String imagePixelsPixelType = imagePixels.getPixelType();
checkValue("Image Pixels PixelType", imagePixelsPixelType, "int16");
Boolean imagePixelsBigEndian = imagePixels.getBigEndian();
checkValue("Image Pixels BigEndian", imagePixelsBigEndian, Boolean.TRUE);
Integer imagePixelsSizeX = imagePixels.getSizeX();
checkValue("Image Pixels SizeX", imagePixelsSizeX, new Integer(20));
Integer imagePixelsSizeY = imagePixels.getSizeY();
checkValue("Image Pixels SizeY", imagePixelsSizeY, new Integer(20));
Integer imagePixelsSizeZ = imagePixels.getSizeZ();
checkValue("Image Pixels SizeZ", imagePixelsSizeZ, new Integer(5));
Integer imagePixelsSizeC = imagePixels.getSizeC();
checkValue("Image Pixels SizeC", imagePixelsSizeC, new Integer(1));
Integer imagePixelsSizeT = imagePixels.getSizeT();
checkValue("Image Pixels SizeT", imagePixelsSizeT, new Integer(6));
Float imagePixelsPhysicalSizeX = imagePixels.getPhysicalSizeX();
checkValue("Image Pixels PhysicalSizeX",
imagePixelsPhysicalSizeX, new Float(0.2f));
Float imagePixelsPhysicalSizeY = imagePixels.getPhysicalSizeY();
checkValue("Image Pixels PhysicalSizeY",
imagePixelsPhysicalSizeY, new Float(0.2f));
Float imagePixelsPhysicalSizeZ = imagePixels.getPhysicalSizeZ();
checkValue("Image Pixels PhysicalSizeZ",
imagePixelsPhysicalSizeZ, new Float(0.2f));
Float imagePixelsTimeIncrement = imagePixels.getTimeIncrement();
checkNull("Image Pixels TimeIncrement", imagePixelsTimeIncrement);
Integer imagePixelsWaveStart = imagePixels.getWaveStart();
checkNull("Image Pixels WaveStart", imagePixelsWaveStart);
Integer imagePixelsWaveIncrement = imagePixels.getWaveIncrement();
checkNull("Image Pixels WaveIncrement", imagePixelsWaveIncrement);
// -- Depth 4 --
// check OME/Instrument/LightSource-1/Laser
// TODO
// check OME/Instrument/LightSource-2/Arc
// TODO
// check OME/Instrument/Filter-1/TransmittanceRange
Integer instrumentFilter1TransmittanceRangeCutIn =
instrumentFilter1TransmittanceRange.getCutIn();
checkValue("Instrument Filter-1 TransmittanceRange CutIn",
instrumentFilter1TransmittanceRangeCutIn, new Integer(432));
Integer instrumentFilter1TransmittanceRangeTransmittance =
instrumentFilter1TransmittanceRange.getTransmittance();
checkValue("Instrument Filter-1 TransmittanceRange Transmittance",
instrumentFilter1TransmittanceRangeTransmittance, new Integer(20));
Integer instrumentFilter1TransmittanceRangeCutOut =
instrumentFilter1TransmittanceRange.getCutOut();
checkValue("Instrument Filter-1 TransmittanceRange CutOut",
instrumentFilter1TransmittanceRangeCutOut, new Integer(543));
Integer instrumentFilter1TransmittanceRangeCutInTolerance =
instrumentFilter1TransmittanceRange.getCutInTolerance();
checkNull("Instrument Filter-1 TransmittanceRange CutInTolerance",
instrumentFilter1TransmittanceRangeCutInTolerance);
Integer instrumentFilter1TransmittanceRangeCutOutTolerance =
instrumentFilter1TransmittanceRange.getCutOutTolerance();
checkNull("Instrument Filter-1 TransmittanceRange CutOutTolerance",
instrumentFilter1TransmittanceRangeCutOutTolerance);
// check OME/Instrument/Filter-2/TransmittanceRange
Integer instrumentFilter2TransmittanceRangeCutIn =
instrumentFilter2TransmittanceRange.getCutIn();
checkValue("Instrument Filter-2 TransmittanceRange CutIn",
instrumentFilter2TransmittanceRangeCutIn, new Integer(432));
Integer instrumentFilter2TransmittanceRangeTransmittance =
instrumentFilter2TransmittanceRange.getTransmittance();
checkValue("Instrument Filter-2 TransmittanceRange Transmittance",
instrumentFilter2TransmittanceRangeTransmittance, new Integer(20));
Integer instrumentFilter2TransmittanceRangeCutOut =
instrumentFilter2TransmittanceRange.getCutOut();
checkValue("Instrument Filter-2 TransmittanceRange CutOut",
instrumentFilter2TransmittanceRangeCutOut, new Integer(543));
Integer instrumentFilter2TransmittanceRangeCutInTolerance =
instrumentFilter2TransmittanceRange.getCutInTolerance();
checkNull("Instrument Filter-2 TransmittanceRange CutInTolerance",
instrumentFilter2TransmittanceRangeCutInTolerance);
Integer instrumentFilter2TransmittanceRangeCutOutTolerance =
instrumentFilter2TransmittanceRange.getCutOutTolerance();
checkNull("Instrument Filter-2 TransmittanceRange CutOutTolerance",
instrumentFilter2TransmittanceRangeCutOutTolerance);
// check OME/Instrument/OTF/BinaryFile
// TODO
// check OME/Image/LogicalChannel/ChannelComponent
// TODO
// check OME/Image/DisplayOptions/RedChannel
Integer imageDisplayOptionsRedChannelChannelNumber =
imageDisplayOptionsRedChannel.getChannelNumber();
checkValue("Image DisplayOptions RedChannel ChannelNumber",
imageDisplayOptionsRedChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsRedChannelBlackLevel =
imageDisplayOptionsRedChannel.getBlackLevel();
checkValue("Image DisplayOptions RedChannel BlackLevel",
imageDisplayOptionsRedChannelBlackLevel, new Float(144));
Float imageDisplayOptionsRedChannelWhiteLevel =
imageDisplayOptionsRedChannel.getWhiteLevel();
checkValue("Image DisplayOptions RedChannel WhiteLevel",
imageDisplayOptionsRedChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsRedChannelGamma =
imageDisplayOptionsRedChannel.getGamma();
checkNull("Image DisplayOptions RedChannel Gamma",
imageDisplayOptionsRedChannelGamma);
Boolean imageDisplayOptionsRedChannelisOn =
imageDisplayOptionsRedChannel.getisOn();
checkValue("Image DisplayOptions RedChannel isOn",
imageDisplayOptionsRedChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/GreenChannel
Integer imageDisplayOptionsGreenChannelChannelNumber =
imageDisplayOptionsGreenChannel.getChannelNumber();
checkValue("Image DisplayOptions GreenChannel ChannelNumber",
imageDisplayOptionsGreenChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsGreenChannelBlackLevel =
imageDisplayOptionsGreenChannel.getBlackLevel();
checkValue("Image DisplayOptions GreenChannel BlackLevel",
imageDisplayOptionsGreenChannelBlackLevel, new Float(144));
Float imageDisplayOptionsGreenChannelWhiteLevel =
imageDisplayOptionsGreenChannel.getWhiteLevel();
checkValue("Image DisplayOptions GreenChannel WhiteLevel",
imageDisplayOptionsGreenChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsGreenChannelGamma =
imageDisplayOptionsGreenChannel.getGamma();
checkNull("Image DisplayOptions GreenChannel Gamma",
imageDisplayOptionsGreenChannelGamma);
Boolean imageDisplayOptionsGreenChannelisOn =
imageDisplayOptionsGreenChannel.getisOn();
checkValue("Image DisplayOptions GreenChannel isOn",
imageDisplayOptionsGreenChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/BlueChannel
Integer imageDisplayOptionsBlueChannelChannelNumber =
imageDisplayOptionsBlueChannel.getChannelNumber();
checkValue("Image DisplayOptions BlueChannel ChannelNumber",
imageDisplayOptionsBlueChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsBlueChannelBlackLevel =
imageDisplayOptionsBlueChannel.getBlackLevel();
checkValue("Image DisplayOptions BlueChannel BlackLevel",
imageDisplayOptionsBlueChannelBlackLevel, new Float(144));
Float imageDisplayOptionsBlueChannelWhiteLevel =
imageDisplayOptionsBlueChannel.getWhiteLevel();
checkValue("Image DisplayOptions BlueChannel WhiteLevel",
imageDisplayOptionsBlueChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsBlueChannelGamma =
imageDisplayOptionsBlueChannel.getGamma();
checkNull("Image DisplayOptions BlueChannel Gamma",
imageDisplayOptionsBlueChannelGamma);
Boolean imageDisplayOptionsBlueChannelisOn =
imageDisplayOptionsBlueChannel.getisOn();
checkValue("Image DisplayOptions BlueChannel isOn",
imageDisplayOptionsBlueChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/GreyChannel
String imageDisplayOptionsGreyChannelColorMap =
imageDisplayOptionsGreyChannel.getColorMap();
checkNull("Image DisplayOptions GreyChannel ColorMap",
imageDisplayOptionsGreyChannelColorMap);
Integer imageDisplayOptionsGreyChannelChannelNumber =
imageDisplayOptionsGreyChannel.getChannelNumber();
checkValue("Image DisplayOptions GreyChannel ChannelNumber",
imageDisplayOptionsGreyChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsGreyChannelBlackLevel =
imageDisplayOptionsGreyChannel.getBlackLevel();
checkValue("Image DisplayOptions GreyChannel BlackLevel",
imageDisplayOptionsGreyChannelBlackLevel, new Float(144));
Float imageDisplayOptionsGreyChannelWhiteLevel =
imageDisplayOptionsGreyChannel.getWhiteLevel();
checkValue("Image DisplayOptions GreyChannel WhiteLevel",
imageDisplayOptionsGreyChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsGreyChannelGamma =
imageDisplayOptionsGreyChannel.getGamma();
checkNull("Image DisplayOptions GreyChannel Gamma",
imageDisplayOptionsGreyChannelGamma);
Boolean imageDisplayOptionsGreyChannelisOn =
imageDisplayOptionsGreyChannel.getisOn();
checkNull("Image DisplayOptions GreyChannel isOn",
imageDisplayOptionsGreyChannelisOn);
// check OME/Image/DisplayOptions/Projection
Integer imageDisplayOptionsProjectionZStart =
imageDisplayOptionsProjection.getZStart();
checkValue("Image DisplayOptions Projection ZStart",
imageDisplayOptionsProjectionZStart, new Integer(3));
Integer imageDisplayOptionsProjectionZStop =
imageDisplayOptionsProjection.getZStop();
checkValue("Image DisplayOptions Projection ZStop",
imageDisplayOptionsProjectionZStop, new Integer(3));
// check OME/Image/DisplayOptions/Time
Integer imageDisplayOptionsTimeTStart = imageDisplayOptionsTime.getTStart();
checkValue("Image DisplayOptions Time TStart",
imageDisplayOptionsTimeTStart, new Integer(3));
Integer imageDisplayOptionsTimeTStop = imageDisplayOptionsTime.getTStop();
checkValue("Image DisplayOptions Time TStop",
imageDisplayOptionsTimeTStop, new Integer(3));
// check OME/Image/DisplayOptions/ROI
// TODO
// -- Depth 5 --
// check OME/Instrument/LightSource-1/Laser/Pump
// TODO
// check OME/Instrument/OTF/BinaryFile/External
// TODO
}
/** Builds a node from scratch (to match the Sample.ome file). */
public static OMENode createNode() throws Exception {
OMENode ome = null;
/*
TODO
OMENode ome = new OMENode();
// -- Depth 1 --
// create OME/Project
ProjectNode project = new ProjectNode(ome, "Stress Response Pathway",
null, null, null);
project.setNodeID("urn:lsid:foo.bar.com:Project:123456");
// create OME/Dataset
DatasetNode dataset = new DatasetNode(ome, "Controls",
null, Boolean.FALSE, null, null);
dataset.setNodeID("urn:lsid:foo.bar.com:Dataset:123456");
// create OME/Experiment
// create OME/Plate
// create OME/Screen
// create OME/Experimenter
// create OME/Group
// create OME/Instrument
// create OME/Image
ImageNode image = new ImageNode(ome,
"P1W1S1", "1988-04-07T18:39:09", "This is an Image");
image.setNodeID("urn:lsid:foo.bar.com:Image:123456");
// -- Depth 2 --
// create OME/Dataset/ProjectRef
dataset.addToProject(project);
// create OME/Image/DatasetRef
image.addToDataset(dataset);
// create OME/Image/CA
CustomAttributesNode imageCA = new CustomAttributesNode(image);
// create OME/CA/Experimenter
ExperimenterNode experimenter = new ExperimenterNode(ca,
"Nicola", "Sacco", "[email protected]", null, null, null);
experimenter.setNodeID("urn:lsid:foo.bar.com:Experimenter:123456");
project.setOwner(experimenter);
dataset.setOwner(experimenter);
image.setOwner(experimenter);
// create first OME/CA/ExperimenterGroup
ExperimenterGroupNode experimenterGroup1 = new ExperimenterGroupNode(ca,
experimenter, null);
// create second OME/CA/ExperimenterGroup
GroupNode dummyGroup = new GroupNode(ca, false);
dummyGroup.setNodeID("urn:lsid:foo.bar.com:Group:123789");
ExperimenterGroupNode experimenterGroup2 = new ExperimenterGroupNode(ca,
experimenter, dummyGroup);
// create OME/CA/Group
GroupNode group = new GroupNode(ca, "IICBU", experimenter, experimenter);
group.setNodeID("urn:lsid:foo.bar.com:Group:123456");
project.setGroup(group);
dataset.setGroup(group);
image.setGroup(group);
experimenter.setGroup(group);
experimenterGroup1.setGroup(group);
// create OME/CA/Experiment
ExperimentNode experiment = new ExperimentNode(ca,
"Time-lapse", "This was an experiment.", experimenter);
experiment.setNodeID("urn:lsid:foo.bar.com:Experiment:123456");
// create OME/CA/Instrument
InstrumentNode instrument = new InstrumentNode(ca,
"Zeiss", "foo", "bar", "Upright");
instrument.setNodeID("urn:lsid:foo.bar.com:Instrument:123456");
// create first OME/CA/LightSource
LightSourceNode lightSource1 = new LightSourceNode(ca,
"Olympus", "WMD Laser", "123skdjhf1234", instrument);
lightSource1.setNodeID("urn:lsid:foo.bar.com:LightSource:123456");
// create OME/CA/Laser
LightSourceNode dummyLightSource = new LightSourceNode(ca, false);
dummyLightSource.setNodeID("urn:lsid:foo.bar.com:LightSource:123789");
LaserNode laser = new LaserNode(ca, "Semiconductor", "GaAs",
null, null, null, null, null, lightSource1, dummyLightSource);
// create second OME/CA/LightSource
LightSourceNode lightSource2 = new LightSourceNode(ca,
"Olympus", "Realy Bright Lite", "123skdjhf1456", instrument);
lightSource2.setNodeID("urn:lsid:foo.bar.com:LightSource:123123");
// create OME/CA/Arc
ArcNode arc = new ArcNode(ca, "Hg", null, lightSource2);
// create OME/CA/Detector
DetectorNode detector = new DetectorNode(ca, "Kodak", "Instamatic",
"fnuiprf89uh123498", "CCD", null, null, null, instrument);
detector.setNodeID("urn:lsid:foo.bar.com:Detector:123456");
// create OME/CA/Objective
ObjectiveNode objective = new ObjectiveNode(ca, "Olympus", "SPlanL",
"456anxcoas123", new Float(2.4f), new Float(40), instrument);
objective.setNodeID("urn:lsid:foo.bar.com:Objective:123456");
// create OME/CA/Filter
FilterNode filter = new FilterNode(ca, instrument);
filter.setNodeID("urn:lsid:foo.bar.com:Filter:123456");
// create OME/CA/FilterSet
FilterSetNode filterSet = new FilterSetNode(ca,
"Omega", "SuperGFP", "123LJKHG123", filter);
// create OME/CA/OTF
OTFNode otf = new OTFNode(ca, objective, filter, new Integer(512),
new Integer(512), "int8", null, null, Boolean.TRUE, instrument);
otf.setNodeID("urn:lsid:foo.bar.com:OTF:123456");
// create OME/CA/Plate
PlateNode plate = new PlateNode(ca, "SRP001", "PID.SRP001", null);
plate.setNodeID("urn:lsid:foo.bar.com:Plate:123456");
// create first OME/CA/PlateScreen
PlateScreenNode plateScreen1 = new PlateScreenNode(ca, plate, null);
// create second OME/CA/PlateScreen
ScreenNode dummyScreen = new ScreenNode(ca, false);
dummyScreen.setNodeID("urn:lsid:foo.bar.com:Screen:123789");
PlateScreenNode plateScreen2 = new PlateScreenNode(ca, plate, dummyScreen);
// create OME/CA/Screen
ScreenNode screen = new ScreenNode(ca,
"Stress Response Pathway Controls", null, "SID.SRPC001");
screen.setNodeID("urn:lsid:foo.bar.com:Screen:123456");
plateScreen1.setScreen(screen);
// -- Depth 3 --
// create OME/Image/CA/Dimensions
DimensionsNode dimensions = new DimensionsNode(imageCA,
new Float(0.2f), new Float(0.2f), new Float(0.2f), null, null);
// create OME/Image/CA/ImageExperiment
ImageExperimentNode imageExperiment = new ImageExperimentNode(imageCA,
experiment);
// create OME/Image/CA/ImageInstrument
ImageInstrumentNode imageInstrument = new ImageInstrumentNode(imageCA,
instrument, objective);
// create OME/Image/CA/ImagingEnvironment
ImagingEnvironmentNode imagingEnvironment =
new ImagingEnvironmentNode(imageCA, new Float(.1f),
new Float(.1f), new Float(.2f), new Float(.3f));
// create OME/Image/CA/Thumbnail
ThumbnailNode thumbnail = new ThumbnailNode(imageCA, "image/jpeg", null,
"http://ome.nia.gov/GetThumbnail?ID=urn:lsid:foo.bar.com:Image:123456");
// create OME/Image/CA/LogicalChannel
LogicalChannelNode logicalChannel = new LogicalChannelNode(imageCA,
"Ch 1", null, filter, lightSource2, null, null, otf, detector, null,
null, "Epifluorescence", null, null, null, null, lightSource1, null,
"Photobleaching", null, new Integer(490), new Integer(528), "GFP",
new Float(0));
logicalChannel.setNodeID("urn:lsid:foo.bar.com:LogicalChannel:123456");
// create OME/Image/CA/PixelChannelComponent
PixelChannelComponentNode pixelChannelComponent =
new PixelChannelComponentNode(imageCA, null,
new Integer(0), "foo", logicalChannel);
// create OME/Image/CA/DisplayOptions
DisplayOptionsNode displayOptions = new DisplayOptionsNode(imageCA,
null, new Float(1), null, Boolean.TRUE, null, Boolean.TRUE, null,
Boolean.TRUE, Boolean.TRUE, null, null, new Integer(3), new Integer(3),
new Integer(3), new Integer(3));
displayOptions.setNodeID("urn:lsid:foo.bar.com:DisplayOptions:123456");
// create first OME/Image/CA/DisplayChannel
DisplayChannelNode displayChannelRed = new DisplayChannelNode(imageCA,
new Integer(0), new Double(144), new Double(338), null);
displayOptions.setRedChannel(displayChannelRed);
// create second OME/Image/CA/DisplayChannel
DisplayChannelNode displayChannelGreen = new DisplayChannelNode(imageCA,
new Integer(0), new Double(144), new Double(338), null);
displayOptions.setGreenChannel(displayChannelGreen);
// create third OME/Image/CA/DisplayChannel
DisplayChannelNode displayChannelBlue = new DisplayChannelNode(imageCA,
new Integer(0), new Double(144), new Double(338), null);
displayOptions.setBlueChannel(displayChannelBlue);
// create fourth OME/Image/CA/DisplayChannel
DisplayChannelNode displayChannelGrey = new DisplayChannelNode(imageCA,
new Integer(0), new Double(144), new Double(338), null);
displayOptions.setGreyChannel(displayChannelGrey);
// create OME/Image/CA/DisplayROI
DisplayROINode displayROI = new DisplayROINode(imageCA,
new Integer(0), new Integer(0), new Integer(0), new Integer(512),
new Integer(512), new Integer(0), new Integer(0), new Integer(0),
displayOptions);
// create OME/Image/CA/StageLabel
StageLabelNode stageLabel = new StageLabelNode(imageCA,
"Zulu", new Float(123), new Float(456), new Float(789));
// create OME/Image/CA/ImagePlate
ImagePlateNode imagePlate = new ImagePlateNode(imageCA,
plate, new Integer(1), "A03");
// create OME/Image/CA/Pixels
PixelsNode pixels = new PixelsNode(imageCA, new Integer(20),
new Integer(20), new Integer(5), new Integer(1), new Integer(6),
"int16", null, null, null);
pixels.setNodeID("urn:lsid:foo.bar.com:Pixels:123456");
pixels.setBigEndian(Boolean.TRUE);
pixels.setDimensionOrder("XYZCT");
pixelChannelComponent.setPixels(pixels);
*/
return ome;
}
// -- Helper methods --
private static void checkCount(String field,
int count, Vector list, int expected)
{
if (count != expected || list.size() != expected) {
// decapitalize field name
char[] c = field.toCharArray();
for (int i=0; i<c.length; i++) {
if (c[i] < 'A' || c[i] > 'Z') break;
c[i] += 'a' - 'A';
}
// remove spaces
String var = new String(c).replaceAll("[- ]", "");
System.out.println("Error: Incorrect " + field + " count" +
" (" + var + "Count=" + count +
", " + var + "List.size()=" + list.size() + ")");
}
}
private static void checkNull(String field, Object value) {
if (value != null) {
System.out.println("Error: " + field +
" is not null as expected (" + value + ")");
}
}
private static void checkNotNull(String field, Object value) {
if (value == null) {
System.out.println("Error: " + field + " should not be null");
}
}
private static void checkValue(String field, Object value, Object expected) {
if (value == null && expected == null) return;
if (value == null || !value.equals(expected)) {
System.out.println("Error: Incorrect " + field + " (" + value + ")");
}
}
// -- Main method --
/**
* Tests the ome.xml.r200706 packages.
* <ul>
* <li>Specify path to sample-2007.ome to check it for errors.</li>
* <li>Specify -build flag to duplicate the structure in Sample.ome from
* scratch, then check it for errors.</li>
* </ul>
*/
public static void main(String[] args) throws Exception {
String path = null;
boolean build = false;
for (int i=0; i<args.length; i++) {
if (args[i] == null) continue;
if (args[i].equalsIgnoreCase("-build")) build = true;
else path = args[i];
}
if (path == null && !build) {
System.out.println("Usage: java " + SampleTest.class.getName() +
" [-build || /path/to/Sample-2007_06.ome]");
return;
}
System.out.println("Creating OME node...");
OMENode ome = null;
if (build) ome = createNode();
else ome = (OMENode) OMEXMLFactory.newOMENodeFromSource(new File(path));
System.out.println();
// perform some tests on Sample.ome structure
System.out.println("Performing API tests...");
testSample(ome);
System.out.println();
System.out.println("Writing OME-XML to String...");
// CTR TODO improve this...
DOMUtil.writeXML(System.out, ome.getDOMElement().getOwnerDocument());
}
}
| false | true | public static void testSample(OMENode ome) throws Exception {
// -- Depth 1 --
// check OME node
int projectCount = ome.getProjectCount();
Vector projectList = ome.getProjectList();
checkCount("Project", projectCount, projectList, 1);
int datasetCount = ome.getDatasetCount();
Vector datasetList = ome.getDatasetList();
checkCount("Dataset", datasetCount, datasetList, 1);
int experimentCount = ome.getExperimentCount();
Vector experimentList = ome.getExperimentList();
checkCount("Experiment", experimentCount, experimentList, 1);
int plateCount = ome.getPlateCount();
Vector plateList = ome.getPlateList();
checkCount("Plate", plateCount, plateList, 1);
int screenCount = ome.getScreenCount();
Vector screenList = ome.getScreenList();
checkCount("Screen", screenCount, screenList, 1);
int experimenterCount = ome.getExperimenterCount();
Vector experimenterList = ome.getExperimenterList();
checkCount("Experimenter", experimenterCount, experimenterList, 1);
int groupCount = ome.getGroupCount();
Vector groupList = ome.getGroupList();
checkCount("Group", groupCount, groupList, 1);
int instrumentCount = ome.getInstrumentCount();
Vector instrumentList = ome.getInstrumentList();
checkCount("Instrument", instrumentCount, instrumentList, 1);
int imageCount = ome.getImageCount();
Vector imageList = ome.getImageList();
checkCount("Image", imageCount, imageList, 1);
// SemanticTypeDefinitionsNode semanticTypeDefinitions =
// ome.getSemanticTypeDefinitions();
// checkNull("SemanticTypeDefinitions", semanticTypeDefinitions);
// AnalysisModuleLibraryNode analysisModuleLibrary =
// ome.getAnalysisModuleLibrary();
// checkNull("AnalysisModuleLibrary", analysisModuleLibrary);
// CustomAttributesNode customAttributes = ome.getCustomAttributes();
// checkNull("CustomAttributes", customAttributes);
// -- Depth 2 --
// check OME/Project node
ProjectNode project = (ProjectNode) projectList.get(0);
ExperimenterNode projectExperimenter = project.getExperimenter();
checkNotNull("Project Experimenter", projectExperimenter);
// TODO check projectExperimenter further
String projectDescription = project.getDescription();
checkNull("Project Description", projectDescription);
GroupNode projectGroup = project.getGroup();
checkNotNull("Project Group", projectGroup);
// TODO check projectGroup further
String projectName = project.getName();
checkValue("Project Name", projectName, "Stress Response Pathway");
// check OME/Dataset node
DatasetNode dataset = (DatasetNode) datasetList.get(0);
Boolean datasetLocked = dataset.getLocked();
String datasetDescription = dataset.getDescription();
ExperimenterNode datasetExperimenter = dataset.getExperimenter();
int datasetProjectCount = dataset.getProjectCount();
Vector datasetProjectList = dataset.getProjectList();
GroupNode datasetGroup = dataset.getGroup();
String datasetCustomAttributes = dataset.getCustomAttributes();
String datasetName = dataset.getName();
// check OME/Experiment node
ExperimentNode experiment = (ExperimentNode) experimentList.get(0);
String experimentID = experiment.getNodeID();
checkValue("Experiment ID", experimentID,
"urn:lsid:foo.bar.com:Experiment:123456");
String experimentDescription = experiment.getDescription();
checkValue("Experiment Description", experimentDescription,
"This was an experiment.");
ExperimenterNode experimentExperimenter = experiment.getExperimenter();
checkNotNull("Experiment Experimenter", experimentExperimenter);
// TODO check experimentExperimenter further
int experimentMicrobeamManipulationCount =
experiment.getMicrobeamManipulationCount();
Vector experimentMicrobeamManipulationList =
experiment.getMicrobeamManipulationList();
checkCount("Experiment MicrobeamManipulation",
experimentMicrobeamManipulationCount,
experimentMicrobeamManipulationList, 0);
String experimentType = experiment.getType();
checkValue("Experiment Type", experimentType, "TimeLapse");
// check OME/Plate node
// TODO
// check OME/Screen node
// TODO
// check OME/Experimenter node
ExperimenterNode experimenter = (ExperimenterNode) experimenterList.get(0);
String experimenterID = experimenter.getNodeID();
checkValue("Experimenter ID", experimenterID,
"urn:lsid:foo.bar.com:Experimenter:123456");
String experimenterFirstName = experimenter.getFirstName();
checkValue("Experimenter FirstName", experimenterFirstName, "Nicola");
String experimenterLastName = experimenter.getLastName();
checkValue("Experimenter LastName", experimenterLastName, "Sacco");
String experimenterEmail = experimenter.getEmail();
checkValue("Experimenter Email",
experimenterEmail, "[email protected]");
String experimenterInstitution = experimenter.getInstitution();
checkNull("Experimenter Institution", experimenterInstitution);
String experimenterOMEName = experimenter.getOMEName();
checkValue("Experimenter OMEName", experimenterOMEName, "nico");
int experimenterGroupCount = experimenter.getGroupCount();
Vector experimenterGroupList = experimenter.getGroupList();
checkCount("Experimenter Group",
experimenterGroupCount, experimenterGroupList, 2);
// check OME/Group node
// TODO
// check against projectGroup, datasetGroup
// check OME/Instrument node
InstrumentNode instrument = (InstrumentNode) instrumentList.get(0);
checkNotNull("Instrument", instrument);
MicroscopeNode instrumentMicroscope = instrument.getMicroscope();
checkNotNull("Instrument Microscope", instrumentMicroscope);
int instrumentLightSourceCount = instrument.getLightSourceCount();
Vector instrumentLightSourceList = instrument.getLightSourceList();
checkCount("Instrument LightSource",
instrumentLightSourceCount, instrumentLightSourceList, 2);
int instrumentDetectorCount = instrument.getDetectorCount();
Vector instrumentDetectorList = instrument.getDetectorList();
checkCount("Instrument Detector",
instrumentDetectorCount, instrumentDetectorList, 1);
int instrumentObjectiveCount = instrument.getObjectiveCount();
Vector instrumentObjectiveList = instrument.getObjectiveList();
checkCount("Instrument Objective",
instrumentObjectiveCount, instrumentObjectiveList, 1);
int instrumentFilterSetCount = instrument.getFilterSetCount();
Vector instrumentFilterSetList = instrument.getFilterSetList();
checkCount("Instrument FilterSet",
instrumentFilterSetCount, instrumentFilterSetList, 1);
int instrumentFilterCount = instrument.getFilterCount();
Vector instrumentFilterList = instrument.getFilterList();
checkCount("Instrument Filter",
instrumentFilterCount, instrumentFilterList, 2);
int instrumentDichroicCount = instrument.getDichroicCount();
Vector instrumentDichroicList = instrument.getDichroicList();
checkCount("Instrument Dichroic",
instrumentDichroicCount, instrumentDichroicList, 0);
int instrumentOTFCount = instrument.getOTFCount();
Vector instrumentOTFList = instrument.getOTFList();
checkCount("Instrument OTF",
instrumentOTFCount, instrumentOTFList, 1);
// check OME/Image node
ImageNode image = (ImageNode) imageList.get(0);
checkNotNull("Image", image);
String imageID = image.getNodeID();
checkValue("Image ID", imageID, "urn:lsid:foo.bar.com:Image:123456");
String imageCreationDate = image.getCreationDate();
checkValue("Image CreationDate", imageCreationDate, "1988-04-07T18:39:09");
ExperimenterNode imageExperimenter = image.getExperimenter();
checkNotNull("Image Experimenter", imageExperimenter);
// TODO check imageExperimenter further
String imageDescription = image.getDescription();
checkValue("Image Description", imageDescription, "This is an Image");
ExperimentNode imageExperiment = image.getExperiment();
checkNotNull("Image Experiment", imageExperiment);
// TODO check imageExperiment further
GroupNode imageGroup = image.getGroup();
checkNotNull("Image Group", imageGroup);
// TODO check imageGroup further
int imageDatasetCount = image.getDatasetCount();
Vector imageDatasetList = image.getDatasetList();
checkCount("Image Dataset", imageDatasetCount, imageDatasetList, 1);
InstrumentNode imageInstrument = image.getInstrument();
checkNotNull("Image Instrument", imageInstrument);
// TODO check imageInstrument further
ObjectiveSettingsNode imageObjectiveSettings = image.getObjectiveSettings();
checkNull("Image ObjectiveSettings", imageObjectiveSettings);
ImagingEnvironmentNode imageImagingEnvironment =
image.getImagingEnvironment();
checkNotNull("Image ImagingEnvironment", imageImagingEnvironment);
ThumbnailNode imageThumbnail = image.getThumbnail();
checkNotNull("Image Thumbnail", imageThumbnail);
int imageLogicalChannelCount = image.getLogicalChannelCount();
Vector imageLogicalChannelList = image.getLogicalChannelList();
checkCount("Image LogicalChannel", imageLogicalChannelCount,
imageLogicalChannelList, 1);
DisplayOptionsNode imageDisplayOptions = image.getDisplayOptions();
checkNotNull("Image DisplayOptions", imageDisplayOptions);
StageLabelNode imageStageLabel = image.getStageLabel();
checkNotNull("Image StageLabel", imageStageLabel);
int imagePixelsCount = image.getPixelsCount();
Vector imagePixelsList = image.getPixelsList();
checkCount("Image Pixels", imagePixelsCount, imagePixelsList, 1);
PixelsNode imageAcquiredPixels = image.getAcquiredPixels();
checkNull("Image AcquiredPixels", imageAcquiredPixels);
int imageRegionCount = image.getRegionCount();
Vector imageRegionList = image.getRegionList();
checkCount("Image Region", imageRegionCount, imageRegionList, 0);
String imageCustomAttributes = image.getCustomAttributes();
checkNull("Image CustomAttributes", imageCustomAttributes);
int imageROICount = image.getROICount();
Vector imageROIList = image.getROIList();
checkCount("Image ROI", imageROICount, imageROIList, 0);
int imageMicrobeamManipulationCount =
image.getMicrobeamManipulationCount();
Vector imageMicrobeamManipulationList =
image.getMicrobeamManipulationList();
checkCount("Image MicrobeamManipulation", imageMicrobeamManipulationCount,
imageMicrobeamManipulationList, 0);
String imageName = image.getName();
checkValue("Image Name", imageName, "P1W1S1");
// -- Depth 3 --
// check OME/Dataset/CustomAttributes
// TODO
// check OME/Screen/Reagent
// TODO
// check OME/Screen/ScreenAcquisition
// TODO
// check OME/Instrument/Microscope
// TODO
// check OME/Instrument/LightSource-1
// TODO
// check OME/Instrument/LightSource-2
// TODO
// check OME/Instrument/Detector
// TODO
// check OME/Instrument/Objective
// TODO
// check OME/Instrument/FilterSet
// TODO
// check OME/Instrument/Filter-1
FilterNode instrumentFilter1 = (FilterNode) instrumentFilterList.get(0);
String instrumentFilter1ID = instrumentFilter1.getNodeID();
checkValue("Instrument Filter-1 ID", instrumentFilter1ID,
"urn:lsid:foo.bar.com:Filter:123456");
String instrumentFilter1Manufacturer = instrumentFilter1.getManufacturer();
checkValue("Instrument Filter-1 Manufacturer",
instrumentFilter1Manufacturer, "Omega");
String instrumentFilter1Model = instrumentFilter1.getModel();
checkValue("Instrument Filter-1 Model",
instrumentFilter1Model, "SuperGFP");
String instrumentFilter1LotNumber = instrumentFilter1.getLotNumber();
checkNull("Instrument Filter-1 LotNumber", instrumentFilter1LotNumber);
TransmittanceRangeNode instrumentFilter1TransmittanceRange =
instrumentFilter1.getTransmittanceRange();
checkNotNull("Instrument Filter-1 TransmittanceRange",
instrumentFilter1TransmittanceRange);
String instrumentFilter1Type = instrumentFilter1.getType();
checkNull("Instrument Filter-1 Type", instrumentFilter1Type);
String instrumentFilter1FilterWheel = instrumentFilter1.getFilterWheel();
checkNull("Instrument Filter-1 FilterWheel", instrumentFilter1FilterWheel);
// check OME/Instrument/Filter-2
FilterNode instrumentFilter2 = (FilterNode) instrumentFilterList.get(1);
String instrumentFilter2ID = instrumentFilter2.getNodeID();
checkValue("Instrument Filter-2 ID", instrumentFilter2ID,
"urn:lsid:foo.bar.com:Filter:1234567");
String instrumentFilter2Manufacturer = instrumentFilter2.getManufacturer();
checkValue("Instrument Filter-2 Manufacturer",
instrumentFilter2Manufacturer, "Omega");
String instrumentFilter2Model = instrumentFilter2.getModel();
checkValue("Instrument Filter-2 Model",
instrumentFilter2Model, "SuperGFP");
String instrumentFilter2LotNumber = instrumentFilter2.getLotNumber();
checkNull("Instrument Filter-2 LotNumber", instrumentFilter2LotNumber);
TransmittanceRangeNode instrumentFilter2TransmittanceRange =
instrumentFilter2.getTransmittanceRange();
checkNotNull("Instrument Filter-2 TransmittanceRange",
instrumentFilter2TransmittanceRange);
String instrumentFilter2Type = instrumentFilter2.getType();
checkNull("Instrument Filter-2 Type", instrumentFilter2Type);
String instrumentFilter2FilterWheel = instrumentFilter2.getFilterWheel();
checkNull("Instrument Filter-2 FilterWheel", instrumentFilter2FilterWheel);
// check OME/Instrument/OTF
// TODO
// check OME/Image/ImagingEnvironment
// TODO
// check OME/Image/Thumbnail
// TODO
// check OME/Image/LogicalChannel
LogicalChannelNode imageLogicalChannel =
(LogicalChannelNode) imageLogicalChannelList.get(0);
checkNotNull("Image LogicalChannel", imageLogicalChannel);
String imageLogicalChannelID = imageLogicalChannel.getNodeID();
checkValue("Image LogicalChannel ID", imageLogicalChannelID,
"urn:lsid:foo.bar.com:LogicalChannel:123456");
LightSourceNode imageLogicalChannelLightSource =
imageLogicalChannel.getLightSource();
checkNotNull("Image LogicalChannel LightSource",
imageLogicalChannelLightSource);
// TODO check imageLogicalChannelLightSource further
OTFNode imageLogicalChannelOTF = imageLogicalChannel.getOTF();
checkNotNull("Image LogicalChannel OTF", imageLogicalChannelOTF);
// TODO check imageLogicalChannelOTF further
DetectorNode imageLogicalChannelDetector =
imageLogicalChannel.getDetector();
checkNotNull("Image LogicalChannel Detector", imageLogicalChannelDetector);
// TODO check imageLogicalChannelDetector further
FilterSetNode imageLogicalChannelFilterSet =
imageLogicalChannel.getFilterSet();
checkNotNull("Image LogicalChannel FilterSet",
imageLogicalChannelFilterSet);
// TODO check imageLogicalChannelFilterSet further
int imageLogicalChannelChannelComponentCount =
imageLogicalChannel.getChannelComponentCount();
Vector imageLogicalChannelChannelComponentList =
imageLogicalChannel.getChannelComponentList();
checkCount("Image LogicalChannel ChannelComponent",
imageLogicalChannelChannelComponentCount,
imageLogicalChannelChannelComponentList, 1);
String imageLogicalChannelName = imageLogicalChannel.getName();
checkValue("Image LogicalChannel Name", imageLogicalChannelName, "Ch 1");
Integer imageLogicalChannelSamplesPerPixel =
imageLogicalChannel.getSamplesPerPixel();
checkNull("Image LogicalChannel SamplesPerPixel",
imageLogicalChannelSamplesPerPixel);
FilterNode imageLogicalChannelSecondaryEmissionFilter =
imageLogicalChannel.getSecondaryEmissionFilter();
checkNull("Image LogicalChannel SecondaryEmissionFilter",
imageLogicalChannelSecondaryEmissionFilter);
FilterNode imageLogicalChannelSecondaryExcitationFilter =
imageLogicalChannel.getSecondaryExcitationFilter();
checkNull("Image LogicalChannel SecondaryExcitationFilter",
imageLogicalChannelSecondaryExcitationFilter);
String imageLogicalChannelIlluminationType =
imageLogicalChannel.getIlluminationType();
checkValue("Image LogicalChannel IlluminationType",
imageLogicalChannelIlluminationType, "Epifluorescence");
Integer imageLogicalChannelPinholeSize =
imageLogicalChannel.getPinholeSize();
checkNull("Image LogicalChannel PinholeSize",
imageLogicalChannelPinholeSize);
String imageLogicalChannelPhotometricInterpretation =
imageLogicalChannel.getPhotometricInterpretation();
checkNull("Image LogicalChannel PhotometricInterpretation",
imageLogicalChannelPhotometricInterpretation);
String imageLogicalChannelMode = imageLogicalChannel.getMode();
checkNull("Image LogicalChannel Mode", imageLogicalChannelMode);
String imageLogicalChannelContrastMethod =
imageLogicalChannel.getContrastMethod();
checkNull("Image LogicalChannel ContrastMethod",
imageLogicalChannelContrastMethod);
Integer imageLogicalChannelExWave = imageLogicalChannel.getExWave();
checkValue("Image LogicalChannel ExWave",
imageLogicalChannelExWave, new Integer(490));
Integer imageLogicalChannelEmWave = imageLogicalChannel.getEmWave();
checkValue("Image LogicalChannel EmWave",
imageLogicalChannelEmWave, new Integer(528));
String imageLogicalChannelFluor = imageLogicalChannel.getFluor();
checkValue("Image LogicalChannel Fluor",
imageLogicalChannelFluor, "GFP");
Float imageLogicalChannelNdFilter = imageLogicalChannel.getNdFilter();
checkValue("Image LogicalChannel NdFilter",
imageLogicalChannelNdFilter, new Float(0.0f));
Integer imageLogicalChannelPockelCellSetting =
imageLogicalChannel.getPockelCellSetting();
checkNull("Image LogicalChannel PockelCellSetting",
imageLogicalChannelPockelCellSetting);
// check OME/Image/DisplayOptions
String imageDisplayOptionsID = imageDisplayOptions.getNodeID();
checkValue("Image DisplayOptions ID", imageDisplayOptionsID,
"urn:lsid:foo.bar.com:DisplayOptions:123456");
ChannelSpecTypeNode imageDisplayOptionsRedChannel =
imageDisplayOptions.getRedChannel();
checkNotNull("Image DisplayOptions RedChannel",
imageDisplayOptionsRedChannel);
ChannelSpecTypeNode imageDisplayOptionsGreenChannel =
imageDisplayOptions.getGreenChannel();
checkNotNull("Image DisplayOptions GreenChannel",
imageDisplayOptionsGreenChannel);
ChannelSpecTypeNode imageDisplayOptionsBlueChannel =
imageDisplayOptions.getBlueChannel();
checkNotNull("Image DisplayOptions BlueChannel",
imageDisplayOptionsBlueChannel);
GreyChannelNode imageDisplayOptionsGreyChannel =
imageDisplayOptions.getGreyChannel();
checkNotNull("Image DisplayOptions GreyChannel",
imageDisplayOptionsGreyChannel);
ProjectionNode imageDisplayOptionsProjection =
imageDisplayOptions.getProjection();
checkNotNull("Image DisplayOptions Projection",
imageDisplayOptionsProjection);
TimeNode imageDisplayOptionsTime =
imageDisplayOptions.getTime();
checkNotNull("Image DisplayOptions Time",
imageDisplayOptionsTime);
int imageDisplayOptionsROICount = imageDisplayOptions.getROICount();
Vector imageDisplayOptionsROIList = imageDisplayOptions.getROIList();
checkCount("Image DisplayOptions ROI",
imageDisplayOptionsROICount, imageDisplayOptionsROIList, 1);
Float imageDisplayOptionsZoom = imageDisplayOptions.getZoom();
checkValue("Image DisplayOptions Zoom",
imageDisplayOptionsZoom, new Float(1.0f));
String imageDisplayOptionsDisplay = imageDisplayOptions.getDisplay();
checkValue("Image DisplayOptions Display",
imageDisplayOptionsDisplay, "RGB");
// check OME/Image/StageLabel
String imageStageLabelName = imageStageLabel.getName();
checkValue("Image StageLabel Name", imageStageLabelName, "Zulu");
Float imageStageLabelX = imageStageLabel.getX();
checkValue("Image StageLabel X", imageStageLabelX, new Float(123));
Float imageStageLabelY = imageStageLabel.getY();
checkValue("Image StageLabel Y", imageStageLabelY, new Float(456));
Float imageStageLabelZ = imageStageLabel.getZ();
checkValue("Image StageLabel Z", imageStageLabelZ, new Float(789));
// check OME/Image/Pixels
PixelsNode imagePixels = (PixelsNode) imagePixelsList.get(0);
checkNotNull("Image Pixels", imagePixels);
int imagePixelsTiffDataCount = imagePixels.getTiffDataCount();
Vector imagePixelsTiffDataList = imagePixels.getTiffDataList();
checkCount("Image Pixels TiffData", imagePixelsTiffDataCount,
imagePixelsTiffDataList, 0);
int imagePixelsPlaneCount = imagePixels.getPlaneCount();
Vector imagePixelsPlaneList = imagePixels.getPlaneList();
checkCount("Image Pixels Plane", imagePixelsPlaneCount,
imagePixelsPlaneList, 0);
String imagePixelsDimensionOrder = imagePixels.getDimensionOrder();
checkValue("Image Pixels DimensionOrder",
imagePixelsDimensionOrder, "XYZCT");
String imagePixelsPixelType = imagePixels.getPixelType();
checkValue("Image Pixels PixelType", imagePixelsPixelType, "int16");
Boolean imagePixelsBigEndian = imagePixels.getBigEndian();
checkValue("Image Pixels BigEndian", imagePixelsBigEndian, Boolean.TRUE);
Integer imagePixelsSizeX = imagePixels.getSizeX();
checkValue("Image Pixels SizeX", imagePixelsSizeX, new Integer(20));
Integer imagePixelsSizeY = imagePixels.getSizeY();
checkValue("Image Pixels SizeY", imagePixelsSizeY, new Integer(20));
Integer imagePixelsSizeZ = imagePixels.getSizeZ();
checkValue("Image Pixels SizeZ", imagePixelsSizeZ, new Integer(5));
Integer imagePixelsSizeC = imagePixels.getSizeC();
checkValue("Image Pixels SizeC", imagePixelsSizeC, new Integer(1));
Integer imagePixelsSizeT = imagePixels.getSizeT();
checkValue("Image Pixels SizeT", imagePixelsSizeT, new Integer(6));
Float imagePixelsPhysicalSizeX = imagePixels.getPhysicalSizeX();
checkValue("Image Pixels PhysicalSizeX",
imagePixelsPhysicalSizeX, new Float(0.2f));
Float imagePixelsPhysicalSizeY = imagePixels.getPhysicalSizeY();
checkValue("Image Pixels PhysicalSizeY",
imagePixelsPhysicalSizeY, new Float(0.2f));
Float imagePixelsPhysicalSizeZ = imagePixels.getPhysicalSizeZ();
checkValue("Image Pixels PhysicalSizeZ",
imagePixelsPhysicalSizeZ, new Float(0.2f));
Float imagePixelsTimeIncrement = imagePixels.getTimeIncrement();
checkNull("Image Pixels TimeIncrement", imagePixelsTimeIncrement);
Integer imagePixelsWaveStart = imagePixels.getWaveStart();
checkNull("Image Pixels WaveStart", imagePixelsWaveStart);
Integer imagePixelsWaveIncrement = imagePixels.getWaveIncrement();
checkNull("Image Pixels WaveIncrement", imagePixelsWaveIncrement);
// -- Depth 4 --
// check OME/Instrument/LightSource-1/Laser
// TODO
// check OME/Instrument/LightSource-2/Arc
// TODO
// check OME/Instrument/Filter-1/TransmittanceRange
Integer instrumentFilter1TransmittanceRangeCutIn =
instrumentFilter1TransmittanceRange.getCutIn();
checkValue("Instrument Filter-1 TransmittanceRange CutIn",
instrumentFilter1TransmittanceRangeCutIn, new Integer(432));
Integer instrumentFilter1TransmittanceRangeTransmittance =
instrumentFilter1TransmittanceRange.getTransmittance();
checkValue("Instrument Filter-1 TransmittanceRange Transmittance",
instrumentFilter1TransmittanceRangeTransmittance, new Integer(20));
Integer instrumentFilter1TransmittanceRangeCutOut =
instrumentFilter1TransmittanceRange.getCutOut();
checkValue("Instrument Filter-1 TransmittanceRange CutOut",
instrumentFilter1TransmittanceRangeCutOut, new Integer(543));
Integer instrumentFilter1TransmittanceRangeCutInTolerance =
instrumentFilter1TransmittanceRange.getCutInTolerance();
checkNull("Instrument Filter-1 TransmittanceRange CutInTolerance",
instrumentFilter1TransmittanceRangeCutInTolerance);
Integer instrumentFilter1TransmittanceRangeCutOutTolerance =
instrumentFilter1TransmittanceRange.getCutOutTolerance();
checkNull("Instrument Filter-1 TransmittanceRange CutOutTolerance",
instrumentFilter1TransmittanceRangeCutOutTolerance);
// check OME/Instrument/Filter-2/TransmittanceRange
Integer instrumentFilter2TransmittanceRangeCutIn =
instrumentFilter2TransmittanceRange.getCutIn();
checkValue("Instrument Filter-2 TransmittanceRange CutIn",
instrumentFilter2TransmittanceRangeCutIn, new Integer(432));
Integer instrumentFilter2TransmittanceRangeTransmittance =
instrumentFilter2TransmittanceRange.getTransmittance();
checkValue("Instrument Filter-2 TransmittanceRange Transmittance",
instrumentFilter2TransmittanceRangeTransmittance, new Integer(20));
Integer instrumentFilter2TransmittanceRangeCutOut =
instrumentFilter2TransmittanceRange.getCutOut();
checkValue("Instrument Filter-2 TransmittanceRange CutOut",
instrumentFilter2TransmittanceRangeCutOut, new Integer(543));
Integer instrumentFilter2TransmittanceRangeCutInTolerance =
instrumentFilter2TransmittanceRange.getCutInTolerance();
checkNull("Instrument Filter-2 TransmittanceRange CutInTolerance",
instrumentFilter2TransmittanceRangeCutInTolerance);
Integer instrumentFilter2TransmittanceRangeCutOutTolerance =
instrumentFilter2TransmittanceRange.getCutOutTolerance();
checkNull("Instrument Filter-2 TransmittanceRange CutOutTolerance",
instrumentFilter2TransmittanceRangeCutOutTolerance);
// check OME/Instrument/OTF/BinaryFile
// TODO
// check OME/Image/LogicalChannel/ChannelComponent
// TODO
// check OME/Image/DisplayOptions/RedChannel
Integer imageDisplayOptionsRedChannelChannelNumber =
imageDisplayOptionsRedChannel.getChannelNumber();
checkValue("Image DisplayOptions RedChannel ChannelNumber",
imageDisplayOptionsRedChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsRedChannelBlackLevel =
imageDisplayOptionsRedChannel.getBlackLevel();
checkValue("Image DisplayOptions RedChannel BlackLevel",
imageDisplayOptionsRedChannelBlackLevel, new Float(144));
Float imageDisplayOptionsRedChannelWhiteLevel =
imageDisplayOptionsRedChannel.getWhiteLevel();
checkValue("Image DisplayOptions RedChannel WhiteLevel",
imageDisplayOptionsRedChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsRedChannelGamma =
imageDisplayOptionsRedChannel.getGamma();
checkNull("Image DisplayOptions RedChannel Gamma",
imageDisplayOptionsRedChannelGamma);
Boolean imageDisplayOptionsRedChannelisOn =
imageDisplayOptionsRedChannel.getisOn();
checkValue("Image DisplayOptions RedChannel isOn",
imageDisplayOptionsRedChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/GreenChannel
Integer imageDisplayOptionsGreenChannelChannelNumber =
imageDisplayOptionsGreenChannel.getChannelNumber();
checkValue("Image DisplayOptions GreenChannel ChannelNumber",
imageDisplayOptionsGreenChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsGreenChannelBlackLevel =
imageDisplayOptionsGreenChannel.getBlackLevel();
checkValue("Image DisplayOptions GreenChannel BlackLevel",
imageDisplayOptionsGreenChannelBlackLevel, new Float(144));
Float imageDisplayOptionsGreenChannelWhiteLevel =
imageDisplayOptionsGreenChannel.getWhiteLevel();
checkValue("Image DisplayOptions GreenChannel WhiteLevel",
imageDisplayOptionsGreenChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsGreenChannelGamma =
imageDisplayOptionsGreenChannel.getGamma();
checkNull("Image DisplayOptions GreenChannel Gamma",
imageDisplayOptionsGreenChannelGamma);
Boolean imageDisplayOptionsGreenChannelisOn =
imageDisplayOptionsGreenChannel.getisOn();
checkValue("Image DisplayOptions GreenChannel isOn",
imageDisplayOptionsGreenChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/BlueChannel
Integer imageDisplayOptionsBlueChannelChannelNumber =
imageDisplayOptionsBlueChannel.getChannelNumber();
checkValue("Image DisplayOptions BlueChannel ChannelNumber",
imageDisplayOptionsBlueChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsBlueChannelBlackLevel =
imageDisplayOptionsBlueChannel.getBlackLevel();
checkValue("Image DisplayOptions BlueChannel BlackLevel",
imageDisplayOptionsBlueChannelBlackLevel, new Float(144));
Float imageDisplayOptionsBlueChannelWhiteLevel =
imageDisplayOptionsBlueChannel.getWhiteLevel();
checkValue("Image DisplayOptions BlueChannel WhiteLevel",
imageDisplayOptionsBlueChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsBlueChannelGamma =
imageDisplayOptionsBlueChannel.getGamma();
checkNull("Image DisplayOptions BlueChannel Gamma",
imageDisplayOptionsBlueChannelGamma);
Boolean imageDisplayOptionsBlueChannelisOn =
imageDisplayOptionsBlueChannel.getisOn();
checkValue("Image DisplayOptions BlueChannel isOn",
imageDisplayOptionsBlueChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/GreyChannel
String imageDisplayOptionsGreyChannelColorMap =
imageDisplayOptionsGreyChannel.getColorMap();
checkNull("Image DisplayOptions GreyChannel ColorMap",
imageDisplayOptionsGreyChannelColorMap);
Integer imageDisplayOptionsGreyChannelChannelNumber =
imageDisplayOptionsGreyChannel.getChannelNumber();
checkValue("Image DisplayOptions GreyChannel ChannelNumber",
imageDisplayOptionsGreyChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsGreyChannelBlackLevel =
imageDisplayOptionsGreyChannel.getBlackLevel();
checkValue("Image DisplayOptions GreyChannel BlackLevel",
imageDisplayOptionsGreyChannelBlackLevel, new Float(144));
Float imageDisplayOptionsGreyChannelWhiteLevel =
imageDisplayOptionsGreyChannel.getWhiteLevel();
checkValue("Image DisplayOptions GreyChannel WhiteLevel",
imageDisplayOptionsGreyChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsGreyChannelGamma =
imageDisplayOptionsGreyChannel.getGamma();
checkNull("Image DisplayOptions GreyChannel Gamma",
imageDisplayOptionsGreyChannelGamma);
Boolean imageDisplayOptionsGreyChannelisOn =
imageDisplayOptionsGreyChannel.getisOn();
checkNull("Image DisplayOptions GreyChannel isOn",
imageDisplayOptionsGreyChannelisOn);
// check OME/Image/DisplayOptions/Projection
Integer imageDisplayOptionsProjectionZStart =
imageDisplayOptionsProjection.getZStart();
checkValue("Image DisplayOptions Projection ZStart",
imageDisplayOptionsProjectionZStart, new Integer(3));
Integer imageDisplayOptionsProjectionZStop =
imageDisplayOptionsProjection.getZStop();
checkValue("Image DisplayOptions Projection ZStop",
imageDisplayOptionsProjectionZStop, new Integer(3));
// check OME/Image/DisplayOptions/Time
Integer imageDisplayOptionsTimeTStart = imageDisplayOptionsTime.getTStart();
checkValue("Image DisplayOptions Time TStart",
imageDisplayOptionsTimeTStart, new Integer(3));
Integer imageDisplayOptionsTimeTStop = imageDisplayOptionsTime.getTStop();
checkValue("Image DisplayOptions Time TStop",
imageDisplayOptionsTimeTStop, new Integer(3));
// check OME/Image/DisplayOptions/ROI
// TODO
// -- Depth 5 --
// check OME/Instrument/LightSource-1/Laser/Pump
// TODO
// check OME/Instrument/OTF/BinaryFile/External
// TODO
}
| public static void testSample(OMENode ome) throws Exception {
// -- Depth 1 --
// check OME node
int projectCount = ome.getProjectCount();
Vector projectList = ome.getProjectList();
checkCount("Project", projectCount, projectList, 1);
int datasetCount = ome.getDatasetCount();
Vector datasetList = ome.getDatasetList();
checkCount("Dataset", datasetCount, datasetList, 1);
int experimentCount = ome.getExperimentCount();
Vector experimentList = ome.getExperimentList();
checkCount("Experiment", experimentCount, experimentList, 1);
int plateCount = ome.getPlateCount();
Vector plateList = ome.getPlateList();
checkCount("Plate", plateCount, plateList, 1);
int screenCount = ome.getScreenCount();
Vector screenList = ome.getScreenList();
checkCount("Screen", screenCount, screenList, 1);
int experimenterCount = ome.getExperimenterCount();
Vector experimenterList = ome.getExperimenterList();
checkCount("Experimenter", experimenterCount, experimenterList, 1);
int groupCount = ome.getGroupCount();
Vector groupList = ome.getGroupList();
checkCount("Group", groupCount, groupList, 1);
int instrumentCount = ome.getInstrumentCount();
Vector instrumentList = ome.getInstrumentList();
checkCount("Instrument", instrumentCount, instrumentList, 1);
int imageCount = ome.getImageCount();
Vector imageList = ome.getImageList();
checkCount("Image", imageCount, imageList, 1);
// SemanticTypeDefinitionsNode semanticTypeDefinitions =
// ome.getSemanticTypeDefinitions();
// checkNull("SemanticTypeDefinitions", semanticTypeDefinitions);
// AnalysisModuleLibraryNode analysisModuleLibrary =
// ome.getAnalysisModuleLibrary();
// checkNull("AnalysisModuleLibrary", analysisModuleLibrary);
// CustomAttributesNode customAttributes = ome.getCustomAttributes();
// checkNull("CustomAttributes", customAttributes);
// -- Depth 2 --
// check OME/Project node
ProjectNode project = (ProjectNode) projectList.get(0);
ExperimenterNode projectExperimenter = project.getExperimenter();
checkNotNull("Project Experimenter", projectExperimenter);
// TODO check projectExperimenter further
String projectDescription = project.getDescription();
checkNull("Project Description", projectDescription);
GroupNode projectGroup = project.getGroup();
checkNotNull("Project Group", projectGroup);
// TODO check projectGroup further
String projectName = project.getName();
checkValue("Project Name", projectName, "Stress Response Pathway");
// check OME/Dataset node
DatasetNode dataset = (DatasetNode) datasetList.get(0);
Boolean datasetLocked = dataset.getLocked();
String datasetDescription = dataset.getDescription();
ExperimenterNode datasetExperimenter = dataset.getExperimenter();
int datasetProjectCount = dataset.getProjectCount();
Vector datasetProjectList = dataset.getProjectList();
GroupNode datasetGroup = dataset.getGroup();
String datasetCustomAttributes = dataset.getCustomAttributes();
String datasetName = dataset.getName();
// check OME/Experiment node
ExperimentNode experiment = (ExperimentNode) experimentList.get(0);
String experimentID = experiment.getNodeID();
checkValue("Experiment ID", experimentID,
"urn:lsid:foo.bar.com:Experiment:123456");
String experimentDescription = experiment.getDescription();
checkValue("Experiment Description", experimentDescription,
"This was an experiment.");
ExperimenterNode experimentExperimenter = experiment.getExperimenter();
checkNotNull("Experiment Experimenter", experimentExperimenter);
// TODO check experimentExperimenter further
int experimentMicrobeamManipulationCount =
experiment.getMicrobeamManipulationCount();
Vector experimentMicrobeamManipulationList =
experiment.getMicrobeamManipulationList();
checkCount("Experiment MicrobeamManipulation",
experimentMicrobeamManipulationCount,
experimentMicrobeamManipulationList, 0);
String experimentType = experiment.getType();
checkValue("Experiment Type", experimentType, "TimeLapse");
// check OME/Plate node
// TODO
// check OME/Screen node
// TODO
// check OME/Experimenter node
ExperimenterNode experimenter = (ExperimenterNode) experimenterList.get(0);
String experimenterID = experimenter.getNodeID();
checkValue("Experimenter ID", experimenterID,
"urn:lsid:foo.bar.com:Experimenter:123456");
String experimenterFirstName = experimenter.getFirstName();
checkValue("Experimenter FirstName", experimenterFirstName, "Nicola");
String experimenterLastName = experimenter.getLastName();
checkValue("Experimenter LastName", experimenterLastName, "Sacco");
String experimenterEmail = experimenter.getEmail();
checkValue("Experimenter Email",
experimenterEmail, "[email protected]");
String experimenterInstitution = experimenter.getInstitution();
checkNull("Experimenter Institution", experimenterInstitution);
String experimenterOMEName = experimenter.getOMEName();
checkValue("Experimenter OMEName", experimenterOMEName, "nico");
int experimenterGroupCount = experimenter.getGroupCount();
Vector experimenterGroupList = experimenter.getGroupList();
checkCount("Experimenter Group",
experimenterGroupCount, experimenterGroupList, 2);
// check OME/Group node
// TODO
// check against projectGroup, datasetGroup
// check OME/Instrument node
InstrumentNode instrument = (InstrumentNode) instrumentList.get(0);
checkNotNull("Instrument", instrument);
MicroscopeNode instrumentMicroscope = instrument.getMicroscope();
checkNotNull("Instrument Microscope", instrumentMicroscope);
int instrumentLightSourceCount = instrument.getLightSourceCount();
Vector instrumentLightSourceList = instrument.getLightSourceList();
checkCount("Instrument LightSource",
instrumentLightSourceCount, instrumentLightSourceList, 2);
int instrumentDetectorCount = instrument.getDetectorCount();
Vector instrumentDetectorList = instrument.getDetectorList();
checkCount("Instrument Detector",
instrumentDetectorCount, instrumentDetectorList, 1);
int instrumentObjectiveCount = instrument.getObjectiveCount();
Vector instrumentObjectiveList = instrument.getObjectiveList();
checkCount("Instrument Objective",
instrumentObjectiveCount, instrumentObjectiveList, 1);
int instrumentFilterSetCount = instrument.getFilterSetCount();
Vector instrumentFilterSetList = instrument.getFilterSetList();
checkCount("Instrument FilterSet",
instrumentFilterSetCount, instrumentFilterSetList, 1);
int instrumentFilterCount = instrument.getFilterCount();
Vector instrumentFilterList = instrument.getFilterList();
checkCount("Instrument Filter",
instrumentFilterCount, instrumentFilterList, 2);
int instrumentDichroicCount = instrument.getDichroicCount();
Vector instrumentDichroicList = instrument.getDichroicList();
checkCount("Instrument Dichroic",
instrumentDichroicCount, instrumentDichroicList, 0);
int instrumentOTFCount = instrument.getOTFCount();
Vector instrumentOTFList = instrument.getOTFList();
checkCount("Instrument OTF",
instrumentOTFCount, instrumentOTFList, 1);
// check OME/Image node
ImageNode image = (ImageNode) imageList.get(0);
checkNotNull("Image", image);
String imageID = image.getNodeID();
checkValue("Image ID", imageID, "urn:lsid:foo.bar.com:Image:123456");
String imageCreationDate = image.getCreationDate();
checkValue("Image CreationDate", imageCreationDate, "1988-04-07T18:39:09");
ExperimenterNode imageExperimenter = image.getExperimenter();
checkNotNull("Image Experimenter", imageExperimenter);
// TODO check imageExperimenter further
String imageDescription = image.getDescription();
checkValue("Image Description", imageDescription, "This is an Image");
ExperimentNode imageExperiment = image.getExperiment();
checkNotNull("Image Experiment", imageExperiment);
// TODO check imageExperiment further
GroupNode imageGroup = image.getGroup();
checkNotNull("Image Group", imageGroup);
// TODO check imageGroup further
int imageDatasetCount = image.getDatasetCount();
Vector imageDatasetList = image.getDatasetList();
checkCount("Image Dataset", imageDatasetCount, imageDatasetList, 1);
InstrumentNode imageInstrument = image.getInstrument();
checkNotNull("Image Instrument", imageInstrument);
// TODO check imageInstrument further
ObjectiveSettingsNode imageObjectiveSettings = image.getObjectiveSettings();
checkNull("Image ObjectiveSettings", imageObjectiveSettings);
ImagingEnvironmentNode imageImagingEnvironment =
image.getImagingEnvironment();
checkNotNull("Image ImagingEnvironment", imageImagingEnvironment);
ThumbnailNode imageThumbnail = image.getThumbnail();
checkNotNull("Image Thumbnail", imageThumbnail);
int imageLogicalChannelCount = image.getLogicalChannelCount();
Vector imageLogicalChannelList = image.getLogicalChannelList();
checkCount("Image LogicalChannel", imageLogicalChannelCount,
imageLogicalChannelList, 1);
DisplayOptionsNode imageDisplayOptions = image.getDisplayOptions();
checkNotNull("Image DisplayOptions", imageDisplayOptions);
StageLabelNode imageStageLabel = image.getStageLabel();
checkNotNull("Image StageLabel", imageStageLabel);
int imagePixelsCount = image.getPixelsCount();
Vector imagePixelsList = image.getPixelsList();
checkCount("Image Pixels", imagePixelsCount, imagePixelsList, 1);
PixelsNode imageAcquiredPixels = image.getAcquiredPixels();
checkNull("Image AcquiredPixels", imageAcquiredPixels);
int imageRegionCount = image.getRegionCount();
Vector imageRegionList = image.getRegionList();
checkCount("Image Region", imageRegionCount, imageRegionList, 0);
String imageCustomAttributes = image.getCustomAttributes();
checkNull("Image CustomAttributes", imageCustomAttributes);
int imageROICount = image.getROICount();
Vector imageROIList = image.getROIList();
checkCount("Image ROI", imageROICount, imageROIList, 0);
int imageMicrobeamManipulationCount =
image.getMicrobeamManipulationCount();
Vector imageMicrobeamManipulationList =
image.getMicrobeamManipulationList();
checkCount("Image MicrobeamManipulation", imageMicrobeamManipulationCount,
imageMicrobeamManipulationList, 0);
String imageName = image.getName();
checkValue("Image Name", imageName, "P1W1S1");
// -- Depth 3 --
// check OME/Dataset/CustomAttributes
// TODO
// check OME/Screen/Reagent
// TODO
// check OME/Screen/ScreenAcquisition
// TODO
// check OME/Instrument/Microscope
// TODO
// check OME/Instrument/LightSource-1
// TODO
// check OME/Instrument/LightSource-2
// TODO
// check OME/Instrument/Detector
// TODO
// check OME/Instrument/Objective
// TODO
// check OME/Instrument/FilterSet
// TODO
// check OME/Instrument/Filter-1
FilterNode instrumentFilter1 = (FilterNode) instrumentFilterList.get(0);
String instrumentFilter1ID = instrumentFilter1.getNodeID();
checkValue("Instrument Filter-1 ID", instrumentFilter1ID,
"urn:lsid:foo.bar.com:Filter:123456");
String instrumentFilter1Manufacturer = instrumentFilter1.getManufacturer();
checkValue("Instrument Filter-1 Manufacturer",
instrumentFilter1Manufacturer, "Omega");
String instrumentFilter1Model = instrumentFilter1.getModel();
checkValue("Instrument Filter-1 Model",
instrumentFilter1Model, "SuperGFP");
String instrumentFilter1LotNumber = instrumentFilter1.getLotNumber();
checkNull("Instrument Filter-1 LotNumber", instrumentFilter1LotNumber);
TransmittanceRangeNode instrumentFilter1TransmittanceRange =
instrumentFilter1.getTransmittanceRange();
checkNotNull("Instrument Filter-1 TransmittanceRange",
instrumentFilter1TransmittanceRange);
String instrumentFilter1Type = instrumentFilter1.getType();
checkNull("Instrument Filter-1 Type", instrumentFilter1Type);
String instrumentFilter1FilterWheel = instrumentFilter1.getFilterWheel();
checkNull("Instrument Filter-1 FilterWheel", instrumentFilter1FilterWheel);
// check OME/Instrument/Filter-2
FilterNode instrumentFilter2 = (FilterNode) instrumentFilterList.get(1);
String instrumentFilter2ID = instrumentFilter2.getNodeID();
checkValue("Instrument Filter-2 ID", instrumentFilter2ID,
"urn:lsid:foo.bar.com:Filter:1234567");
String instrumentFilter2Manufacturer = instrumentFilter2.getManufacturer();
checkValue("Instrument Filter-2 Manufacturer",
instrumentFilter2Manufacturer, "Omega");
String instrumentFilter2Model = instrumentFilter2.getModel();
checkValue("Instrument Filter-2 Model",
instrumentFilter2Model, "SuperGFP");
String instrumentFilter2LotNumber = instrumentFilter2.getLotNumber();
checkNull("Instrument Filter-2 LotNumber", instrumentFilter2LotNumber);
TransmittanceRangeNode instrumentFilter2TransmittanceRange =
instrumentFilter2.getTransmittanceRange();
checkNotNull("Instrument Filter-2 TransmittanceRange",
instrumentFilter2TransmittanceRange);
String instrumentFilter2Type = instrumentFilter2.getType();
checkNull("Instrument Filter-2 Type", instrumentFilter2Type);
String instrumentFilter2FilterWheel = instrumentFilter2.getFilterWheel();
checkNull("Instrument Filter-2 FilterWheel", instrumentFilter2FilterWheel);
// check OME/Instrument/OTF
// TODO
// check OME/Image/ImagingEnvironment
// TODO
// check OME/Image/Thumbnail
// TODO
// check OME/Image/LogicalChannel
LogicalChannelNode imageLogicalChannel =
(LogicalChannelNode) imageLogicalChannelList.get(0);
checkNotNull("Image LogicalChannel", imageLogicalChannel);
String imageLogicalChannelID = imageLogicalChannel.getNodeID();
checkValue("Image LogicalChannel ID", imageLogicalChannelID,
"urn:lsid:foo.bar.com:LogicalChannel:123456");
LightSourceNode imageLogicalChannelLightSource =
imageLogicalChannel.getLightSource();
checkNotNull("Image LogicalChannel LightSource",
imageLogicalChannelLightSource);
// TODO check imageLogicalChannelLightSource further
OTFNode imageLogicalChannelOTF = imageLogicalChannel.getOTF();
checkNotNull("Image LogicalChannel OTF", imageLogicalChannelOTF);
// TODO check imageLogicalChannelOTF further
DetectorNode imageLogicalChannelDetector =
imageLogicalChannel.getDetector();
checkNotNull("Image LogicalChannel Detector", imageLogicalChannelDetector);
// TODO check imageLogicalChannelDetector further
FilterSetNode imageLogicalChannelFilterSet =
imageLogicalChannel.getFilterSet();
checkNotNull("Image LogicalChannel FilterSet",
imageLogicalChannelFilterSet);
// TODO check imageLogicalChannelFilterSet further
int imageLogicalChannelChannelComponentCount =
imageLogicalChannel.getChannelComponentCount();
Vector imageLogicalChannelChannelComponentList =
imageLogicalChannel.getChannelComponentList();
checkCount("Image LogicalChannel ChannelComponent",
imageLogicalChannelChannelComponentCount,
imageLogicalChannelChannelComponentList, 1);
String imageLogicalChannelName = imageLogicalChannel.getName();
checkValue("Image LogicalChannel Name", imageLogicalChannelName, "Ch 1");
Integer imageLogicalChannelSamplesPerPixel =
imageLogicalChannel.getSamplesPerPixel();
checkNull("Image LogicalChannel SamplesPerPixel",
imageLogicalChannelSamplesPerPixel);
FilterNode imageLogicalChannelSecondaryEmissionFilter =
imageLogicalChannel.getSecondaryEmissionFilterNode();
checkNull("Image LogicalChannel SecondaryEmissionFilter",
imageLogicalChannelSecondaryEmissionFilter);
FilterNode imageLogicalChannelSecondaryExcitationFilter =
imageLogicalChannel.getSecondaryExcitationFilterNode();
checkNull("Image LogicalChannel SecondaryExcitationFilter",
imageLogicalChannelSecondaryExcitationFilter);
String imageLogicalChannelIlluminationType =
imageLogicalChannel.getIlluminationType();
checkValue("Image LogicalChannel IlluminationType",
imageLogicalChannelIlluminationType, "Epifluorescence");
Integer imageLogicalChannelPinholeSize =
imageLogicalChannel.getPinholeSize();
checkNull("Image LogicalChannel PinholeSize",
imageLogicalChannelPinholeSize);
String imageLogicalChannelPhotometricInterpretation =
imageLogicalChannel.getPhotometricInterpretation();
checkNull("Image LogicalChannel PhotometricInterpretation",
imageLogicalChannelPhotometricInterpretation);
String imageLogicalChannelMode = imageLogicalChannel.getMode();
checkNull("Image LogicalChannel Mode", imageLogicalChannelMode);
String imageLogicalChannelContrastMethod =
imageLogicalChannel.getContrastMethod();
checkNull("Image LogicalChannel ContrastMethod",
imageLogicalChannelContrastMethod);
Integer imageLogicalChannelExWave = imageLogicalChannel.getExWave();
checkValue("Image LogicalChannel ExWave",
imageLogicalChannelExWave, new Integer(490));
Integer imageLogicalChannelEmWave = imageLogicalChannel.getEmWave();
checkValue("Image LogicalChannel EmWave",
imageLogicalChannelEmWave, new Integer(528));
String imageLogicalChannelFluor = imageLogicalChannel.getFluor();
checkValue("Image LogicalChannel Fluor",
imageLogicalChannelFluor, "GFP");
Float imageLogicalChannelNdFilter = imageLogicalChannel.getNdFilter();
checkValue("Image LogicalChannel NdFilter",
imageLogicalChannelNdFilter, new Float(0.0f));
Integer imageLogicalChannelPockelCellSetting =
imageLogicalChannel.getPockelCellSetting();
checkNull("Image LogicalChannel PockelCellSetting",
imageLogicalChannelPockelCellSetting);
// check OME/Image/DisplayOptions
String imageDisplayOptionsID = imageDisplayOptions.getNodeID();
checkValue("Image DisplayOptions ID", imageDisplayOptionsID,
"urn:lsid:foo.bar.com:DisplayOptions:123456");
ChannelSpecTypeNode imageDisplayOptionsRedChannel =
imageDisplayOptions.getRedChannel();
checkNotNull("Image DisplayOptions RedChannel",
imageDisplayOptionsRedChannel);
ChannelSpecTypeNode imageDisplayOptionsGreenChannel =
imageDisplayOptions.getGreenChannel();
checkNotNull("Image DisplayOptions GreenChannel",
imageDisplayOptionsGreenChannel);
ChannelSpecTypeNode imageDisplayOptionsBlueChannel =
imageDisplayOptions.getBlueChannel();
checkNotNull("Image DisplayOptions BlueChannel",
imageDisplayOptionsBlueChannel);
GreyChannelNode imageDisplayOptionsGreyChannel =
imageDisplayOptions.getGreyChannel();
checkNotNull("Image DisplayOptions GreyChannel",
imageDisplayOptionsGreyChannel);
ProjectionNode imageDisplayOptionsProjection =
imageDisplayOptions.getProjection();
checkNotNull("Image DisplayOptions Projection",
imageDisplayOptionsProjection);
TimeNode imageDisplayOptionsTime =
imageDisplayOptions.getTime();
checkNotNull("Image DisplayOptions Time",
imageDisplayOptionsTime);
int imageDisplayOptionsROICount = imageDisplayOptions.getROICount();
Vector imageDisplayOptionsROIList = imageDisplayOptions.getROIList();
checkCount("Image DisplayOptions ROI",
imageDisplayOptionsROICount, imageDisplayOptionsROIList, 1);
Float imageDisplayOptionsZoom = imageDisplayOptions.getZoom();
checkValue("Image DisplayOptions Zoom",
imageDisplayOptionsZoom, new Float(1.0f));
String imageDisplayOptionsDisplay = imageDisplayOptions.getDisplay();
checkValue("Image DisplayOptions Display",
imageDisplayOptionsDisplay, "RGB");
// check OME/Image/StageLabel
String imageStageLabelName = imageStageLabel.getName();
checkValue("Image StageLabel Name", imageStageLabelName, "Zulu");
Float imageStageLabelX = imageStageLabel.getX();
checkValue("Image StageLabel X", imageStageLabelX, new Float(123));
Float imageStageLabelY = imageStageLabel.getY();
checkValue("Image StageLabel Y", imageStageLabelY, new Float(456));
Float imageStageLabelZ = imageStageLabel.getZ();
checkValue("Image StageLabel Z", imageStageLabelZ, new Float(789));
// check OME/Image/Pixels
PixelsNode imagePixels = (PixelsNode) imagePixelsList.get(0);
checkNotNull("Image Pixels", imagePixels);
int imagePixelsTiffDataCount = imagePixels.getTiffDataCount();
Vector imagePixelsTiffDataList = imagePixels.getTiffDataList();
checkCount("Image Pixels TiffData", imagePixelsTiffDataCount,
imagePixelsTiffDataList, 0);
int imagePixelsPlaneCount = imagePixels.getPlaneCount();
Vector imagePixelsPlaneList = imagePixels.getPlaneList();
checkCount("Image Pixels Plane", imagePixelsPlaneCount,
imagePixelsPlaneList, 0);
String imagePixelsDimensionOrder = imagePixels.getDimensionOrder();
checkValue("Image Pixels DimensionOrder",
imagePixelsDimensionOrder, "XYZCT");
String imagePixelsPixelType = imagePixels.getPixelType();
checkValue("Image Pixels PixelType", imagePixelsPixelType, "int16");
Boolean imagePixelsBigEndian = imagePixels.getBigEndian();
checkValue("Image Pixels BigEndian", imagePixelsBigEndian, Boolean.TRUE);
Integer imagePixelsSizeX = imagePixels.getSizeX();
checkValue("Image Pixels SizeX", imagePixelsSizeX, new Integer(20));
Integer imagePixelsSizeY = imagePixels.getSizeY();
checkValue("Image Pixels SizeY", imagePixelsSizeY, new Integer(20));
Integer imagePixelsSizeZ = imagePixels.getSizeZ();
checkValue("Image Pixels SizeZ", imagePixelsSizeZ, new Integer(5));
Integer imagePixelsSizeC = imagePixels.getSizeC();
checkValue("Image Pixels SizeC", imagePixelsSizeC, new Integer(1));
Integer imagePixelsSizeT = imagePixels.getSizeT();
checkValue("Image Pixels SizeT", imagePixelsSizeT, new Integer(6));
Float imagePixelsPhysicalSizeX = imagePixels.getPhysicalSizeX();
checkValue("Image Pixels PhysicalSizeX",
imagePixelsPhysicalSizeX, new Float(0.2f));
Float imagePixelsPhysicalSizeY = imagePixels.getPhysicalSizeY();
checkValue("Image Pixels PhysicalSizeY",
imagePixelsPhysicalSizeY, new Float(0.2f));
Float imagePixelsPhysicalSizeZ = imagePixels.getPhysicalSizeZ();
checkValue("Image Pixels PhysicalSizeZ",
imagePixelsPhysicalSizeZ, new Float(0.2f));
Float imagePixelsTimeIncrement = imagePixels.getTimeIncrement();
checkNull("Image Pixels TimeIncrement", imagePixelsTimeIncrement);
Integer imagePixelsWaveStart = imagePixels.getWaveStart();
checkNull("Image Pixels WaveStart", imagePixelsWaveStart);
Integer imagePixelsWaveIncrement = imagePixels.getWaveIncrement();
checkNull("Image Pixels WaveIncrement", imagePixelsWaveIncrement);
// -- Depth 4 --
// check OME/Instrument/LightSource-1/Laser
// TODO
// check OME/Instrument/LightSource-2/Arc
// TODO
// check OME/Instrument/Filter-1/TransmittanceRange
Integer instrumentFilter1TransmittanceRangeCutIn =
instrumentFilter1TransmittanceRange.getCutIn();
checkValue("Instrument Filter-1 TransmittanceRange CutIn",
instrumentFilter1TransmittanceRangeCutIn, new Integer(432));
Integer instrumentFilter1TransmittanceRangeTransmittance =
instrumentFilter1TransmittanceRange.getTransmittance();
checkValue("Instrument Filter-1 TransmittanceRange Transmittance",
instrumentFilter1TransmittanceRangeTransmittance, new Integer(20));
Integer instrumentFilter1TransmittanceRangeCutOut =
instrumentFilter1TransmittanceRange.getCutOut();
checkValue("Instrument Filter-1 TransmittanceRange CutOut",
instrumentFilter1TransmittanceRangeCutOut, new Integer(543));
Integer instrumentFilter1TransmittanceRangeCutInTolerance =
instrumentFilter1TransmittanceRange.getCutInTolerance();
checkNull("Instrument Filter-1 TransmittanceRange CutInTolerance",
instrumentFilter1TransmittanceRangeCutInTolerance);
Integer instrumentFilter1TransmittanceRangeCutOutTolerance =
instrumentFilter1TransmittanceRange.getCutOutTolerance();
checkNull("Instrument Filter-1 TransmittanceRange CutOutTolerance",
instrumentFilter1TransmittanceRangeCutOutTolerance);
// check OME/Instrument/Filter-2/TransmittanceRange
Integer instrumentFilter2TransmittanceRangeCutIn =
instrumentFilter2TransmittanceRange.getCutIn();
checkValue("Instrument Filter-2 TransmittanceRange CutIn",
instrumentFilter2TransmittanceRangeCutIn, new Integer(432));
Integer instrumentFilter2TransmittanceRangeTransmittance =
instrumentFilter2TransmittanceRange.getTransmittance();
checkValue("Instrument Filter-2 TransmittanceRange Transmittance",
instrumentFilter2TransmittanceRangeTransmittance, new Integer(20));
Integer instrumentFilter2TransmittanceRangeCutOut =
instrumentFilter2TransmittanceRange.getCutOut();
checkValue("Instrument Filter-2 TransmittanceRange CutOut",
instrumentFilter2TransmittanceRangeCutOut, new Integer(543));
Integer instrumentFilter2TransmittanceRangeCutInTolerance =
instrumentFilter2TransmittanceRange.getCutInTolerance();
checkNull("Instrument Filter-2 TransmittanceRange CutInTolerance",
instrumentFilter2TransmittanceRangeCutInTolerance);
Integer instrumentFilter2TransmittanceRangeCutOutTolerance =
instrumentFilter2TransmittanceRange.getCutOutTolerance();
checkNull("Instrument Filter-2 TransmittanceRange CutOutTolerance",
instrumentFilter2TransmittanceRangeCutOutTolerance);
// check OME/Instrument/OTF/BinaryFile
// TODO
// check OME/Image/LogicalChannel/ChannelComponent
// TODO
// check OME/Image/DisplayOptions/RedChannel
Integer imageDisplayOptionsRedChannelChannelNumber =
imageDisplayOptionsRedChannel.getChannelNumber();
checkValue("Image DisplayOptions RedChannel ChannelNumber",
imageDisplayOptionsRedChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsRedChannelBlackLevel =
imageDisplayOptionsRedChannel.getBlackLevel();
checkValue("Image DisplayOptions RedChannel BlackLevel",
imageDisplayOptionsRedChannelBlackLevel, new Float(144));
Float imageDisplayOptionsRedChannelWhiteLevel =
imageDisplayOptionsRedChannel.getWhiteLevel();
checkValue("Image DisplayOptions RedChannel WhiteLevel",
imageDisplayOptionsRedChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsRedChannelGamma =
imageDisplayOptionsRedChannel.getGamma();
checkNull("Image DisplayOptions RedChannel Gamma",
imageDisplayOptionsRedChannelGamma);
Boolean imageDisplayOptionsRedChannelisOn =
imageDisplayOptionsRedChannel.getisOn();
checkValue("Image DisplayOptions RedChannel isOn",
imageDisplayOptionsRedChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/GreenChannel
Integer imageDisplayOptionsGreenChannelChannelNumber =
imageDisplayOptionsGreenChannel.getChannelNumber();
checkValue("Image DisplayOptions GreenChannel ChannelNumber",
imageDisplayOptionsGreenChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsGreenChannelBlackLevel =
imageDisplayOptionsGreenChannel.getBlackLevel();
checkValue("Image DisplayOptions GreenChannel BlackLevel",
imageDisplayOptionsGreenChannelBlackLevel, new Float(144));
Float imageDisplayOptionsGreenChannelWhiteLevel =
imageDisplayOptionsGreenChannel.getWhiteLevel();
checkValue("Image DisplayOptions GreenChannel WhiteLevel",
imageDisplayOptionsGreenChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsGreenChannelGamma =
imageDisplayOptionsGreenChannel.getGamma();
checkNull("Image DisplayOptions GreenChannel Gamma",
imageDisplayOptionsGreenChannelGamma);
Boolean imageDisplayOptionsGreenChannelisOn =
imageDisplayOptionsGreenChannel.getisOn();
checkValue("Image DisplayOptions GreenChannel isOn",
imageDisplayOptionsGreenChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/BlueChannel
Integer imageDisplayOptionsBlueChannelChannelNumber =
imageDisplayOptionsBlueChannel.getChannelNumber();
checkValue("Image DisplayOptions BlueChannel ChannelNumber",
imageDisplayOptionsBlueChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsBlueChannelBlackLevel =
imageDisplayOptionsBlueChannel.getBlackLevel();
checkValue("Image DisplayOptions BlueChannel BlackLevel",
imageDisplayOptionsBlueChannelBlackLevel, new Float(144));
Float imageDisplayOptionsBlueChannelWhiteLevel =
imageDisplayOptionsBlueChannel.getWhiteLevel();
checkValue("Image DisplayOptions BlueChannel WhiteLevel",
imageDisplayOptionsBlueChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsBlueChannelGamma =
imageDisplayOptionsBlueChannel.getGamma();
checkNull("Image DisplayOptions BlueChannel Gamma",
imageDisplayOptionsBlueChannelGamma);
Boolean imageDisplayOptionsBlueChannelisOn =
imageDisplayOptionsBlueChannel.getisOn();
checkValue("Image DisplayOptions BlueChannel isOn",
imageDisplayOptionsBlueChannelisOn, Boolean.TRUE);
// check OME/Image/DisplayOptions/GreyChannel
String imageDisplayOptionsGreyChannelColorMap =
imageDisplayOptionsGreyChannel.getColorMap();
checkNull("Image DisplayOptions GreyChannel ColorMap",
imageDisplayOptionsGreyChannelColorMap);
Integer imageDisplayOptionsGreyChannelChannelNumber =
imageDisplayOptionsGreyChannel.getChannelNumber();
checkValue("Image DisplayOptions GreyChannel ChannelNumber",
imageDisplayOptionsGreyChannelChannelNumber, new Integer(0));
Float imageDisplayOptionsGreyChannelBlackLevel =
imageDisplayOptionsGreyChannel.getBlackLevel();
checkValue("Image DisplayOptions GreyChannel BlackLevel",
imageDisplayOptionsGreyChannelBlackLevel, new Float(144));
Float imageDisplayOptionsGreyChannelWhiteLevel =
imageDisplayOptionsGreyChannel.getWhiteLevel();
checkValue("Image DisplayOptions GreyChannel WhiteLevel",
imageDisplayOptionsGreyChannelWhiteLevel, new Float(338));
Float imageDisplayOptionsGreyChannelGamma =
imageDisplayOptionsGreyChannel.getGamma();
checkNull("Image DisplayOptions GreyChannel Gamma",
imageDisplayOptionsGreyChannelGamma);
Boolean imageDisplayOptionsGreyChannelisOn =
imageDisplayOptionsGreyChannel.getisOn();
checkNull("Image DisplayOptions GreyChannel isOn",
imageDisplayOptionsGreyChannelisOn);
// check OME/Image/DisplayOptions/Projection
Integer imageDisplayOptionsProjectionZStart =
imageDisplayOptionsProjection.getZStart();
checkValue("Image DisplayOptions Projection ZStart",
imageDisplayOptionsProjectionZStart, new Integer(3));
Integer imageDisplayOptionsProjectionZStop =
imageDisplayOptionsProjection.getZStop();
checkValue("Image DisplayOptions Projection ZStop",
imageDisplayOptionsProjectionZStop, new Integer(3));
// check OME/Image/DisplayOptions/Time
Integer imageDisplayOptionsTimeTStart = imageDisplayOptionsTime.getTStart();
checkValue("Image DisplayOptions Time TStart",
imageDisplayOptionsTimeTStart, new Integer(3));
Integer imageDisplayOptionsTimeTStop = imageDisplayOptionsTime.getTStop();
checkValue("Image DisplayOptions Time TStop",
imageDisplayOptionsTimeTStop, new Integer(3));
// check OME/Image/DisplayOptions/ROI
// TODO
// -- Depth 5 --
// check OME/Instrument/LightSource-1/Laser/Pump
// TODO
// check OME/Instrument/OTF/BinaryFile/External
// TODO
}
|
diff --git a/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java b/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java
index 82241af..d00b861 100644
--- a/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java
+++ b/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java
@@ -1,160 +1,160 @@
package com.candroidsample;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.caldroid.CaldroidFragment;
import com.caldroid.CaldroidListener;
@SuppressLint("SimpleDateFormat")
public class CaldroidSampleActivity extends FragmentActivity {
private boolean undo = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
// Setup caldroid fragment
final CaldroidFragment caldroidFragment = new CaldroidFragment();
Bundle args = new Bundle();
Calendar cal = Calendar.getInstance();
args.putInt("month", cal.get(Calendar.MONTH) + 1);
args.putInt("year", cal.get(Calendar.YEAR));
caldroidFragment.setArguments(args);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
- t.add(R.id.calendar1, caldroidFragment);
+ t.replace(R.id.calendar1, caldroidFragment);
t.commit();
// Setup listener
final CaldroidListener listener = new CaldroidListener() {
@Override
public void onSelectDate(Date date, TextView textView) {
Toast.makeText(getApplicationContext(), formatter.format(date),
Toast.LENGTH_LONG).show();
}
@Override
public void onChangeMonth(int month, int year) {
String text = "month: " + month + " year: " + year;
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG)
.show();
}
};
// Setup Caldroid
caldroidFragment.setCaldroidListener(listener);
final TextView textView = (TextView) findViewById(R.id.textview);
final Button customizeButton = (Button) findViewById(R.id.customize_button);
// Customize the calendar
customizeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (undo) {
customizeButton.setText(getString(R.string.customize));
textView.setText("");
// Reset calendar
caldroidFragment.clearDisableDates();
caldroidFragment.clearSelectedDates();
caldroidFragment.setMinDate(null);
caldroidFragment.setMaxDate(null);
caldroidFragment.setShowNavigationArrows(true);
caldroidFragment.refreshView();
undo = false;
return;
}
// Else
undo = true;
customizeButton.setText(getString(R.string.undo));
Calendar cal = Calendar.getInstance();
// Min date is last 7 days
cal.add(Calendar.DATE, -7);
Date minDate = cal.getTime();
// Max date is next 7 days
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 14);
Date maxDate = cal.getTime();
// Set selected dates
// From Date
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 2);
Date fromDate = cal.getTime();
// To Date
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 3);
Date toDate = cal.getTime();
// Set disabled dates
ArrayList<Date> disabledDates = new ArrayList<Date>();
for (int i = 5; i < 8; i++) {
cal = Calendar.getInstance();
cal.add(Calendar.DATE, i);
disabledDates.add(cal.getTime());
}
// Customize
caldroidFragment.setMinDate(minDate);
caldroidFragment.setMaxDate(maxDate);
caldroidFragment.setDisableDates(disabledDates);
caldroidFragment.setSelectedDates(fromDate, toDate);
caldroidFragment.setShowNavigationArrows(false);
caldroidFragment.refreshView();
String text = "Today: " + formatter.format(new Date()) + "\n";
text += "Min Date: " + formatter.format(minDate) + "\n";
text += "Max Date: " + formatter.format(maxDate) + "\n";
text += "Select From Date: " + formatter.format(fromDate)
+ "\n";
text += "Select To Date: " + formatter.format(toDate) + "\n";
for (Date date : disabledDates) {
text += "Max Date: " + formatter.format(date) + "\n";
}
textView.setText(text);
}
});
Button showDialogButton = (Button) findViewById(R.id.show_dialog_button);
showDialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CaldroidFragment dialogCaldroidFragment = CaldroidFragment
.newInstance("Select a date", 3, 2013);
dialogCaldroidFragment.show(getSupportFragmentManager(),
"CALDROID_DIALOG_FRAGMENT");
dialogCaldroidFragment.setCaldroidListener(listener);
}
});
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
// Setup caldroid fragment
final CaldroidFragment caldroidFragment = new CaldroidFragment();
Bundle args = new Bundle();
Calendar cal = Calendar.getInstance();
args.putInt("month", cal.get(Calendar.MONTH) + 1);
args.putInt("year", cal.get(Calendar.YEAR));
caldroidFragment.setArguments(args);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.add(R.id.calendar1, caldroidFragment);
t.commit();
// Setup listener
final CaldroidListener listener = new CaldroidListener() {
@Override
public void onSelectDate(Date date, TextView textView) {
Toast.makeText(getApplicationContext(), formatter.format(date),
Toast.LENGTH_LONG).show();
}
@Override
public void onChangeMonth(int month, int year) {
String text = "month: " + month + " year: " + year;
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG)
.show();
}
};
// Setup Caldroid
caldroidFragment.setCaldroidListener(listener);
final TextView textView = (TextView) findViewById(R.id.textview);
final Button customizeButton = (Button) findViewById(R.id.customize_button);
// Customize the calendar
customizeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (undo) {
customizeButton.setText(getString(R.string.customize));
textView.setText("");
// Reset calendar
caldroidFragment.clearDisableDates();
caldroidFragment.clearSelectedDates();
caldroidFragment.setMinDate(null);
caldroidFragment.setMaxDate(null);
caldroidFragment.setShowNavigationArrows(true);
caldroidFragment.refreshView();
undo = false;
return;
}
// Else
undo = true;
customizeButton.setText(getString(R.string.undo));
Calendar cal = Calendar.getInstance();
// Min date is last 7 days
cal.add(Calendar.DATE, -7);
Date minDate = cal.getTime();
// Max date is next 7 days
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 14);
Date maxDate = cal.getTime();
// Set selected dates
// From Date
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 2);
Date fromDate = cal.getTime();
// To Date
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 3);
Date toDate = cal.getTime();
// Set disabled dates
ArrayList<Date> disabledDates = new ArrayList<Date>();
for (int i = 5; i < 8; i++) {
cal = Calendar.getInstance();
cal.add(Calendar.DATE, i);
disabledDates.add(cal.getTime());
}
// Customize
caldroidFragment.setMinDate(minDate);
caldroidFragment.setMaxDate(maxDate);
caldroidFragment.setDisableDates(disabledDates);
caldroidFragment.setSelectedDates(fromDate, toDate);
caldroidFragment.setShowNavigationArrows(false);
caldroidFragment.refreshView();
String text = "Today: " + formatter.format(new Date()) + "\n";
text += "Min Date: " + formatter.format(minDate) + "\n";
text += "Max Date: " + formatter.format(maxDate) + "\n";
text += "Select From Date: " + formatter.format(fromDate)
+ "\n";
text += "Select To Date: " + formatter.format(toDate) + "\n";
for (Date date : disabledDates) {
text += "Max Date: " + formatter.format(date) + "\n";
}
textView.setText(text);
}
});
Button showDialogButton = (Button) findViewById(R.id.show_dialog_button);
showDialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CaldroidFragment dialogCaldroidFragment = CaldroidFragment
.newInstance("Select a date", 3, 2013);
dialogCaldroidFragment.show(getSupportFragmentManager(),
"CALDROID_DIALOG_FRAGMENT");
dialogCaldroidFragment.setCaldroidListener(listener);
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
// Setup caldroid fragment
final CaldroidFragment caldroidFragment = new CaldroidFragment();
Bundle args = new Bundle();
Calendar cal = Calendar.getInstance();
args.putInt("month", cal.get(Calendar.MONTH) + 1);
args.putInt("year", cal.get(Calendar.YEAR));
caldroidFragment.setArguments(args);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.calendar1, caldroidFragment);
t.commit();
// Setup listener
final CaldroidListener listener = new CaldroidListener() {
@Override
public void onSelectDate(Date date, TextView textView) {
Toast.makeText(getApplicationContext(), formatter.format(date),
Toast.LENGTH_LONG).show();
}
@Override
public void onChangeMonth(int month, int year) {
String text = "month: " + month + " year: " + year;
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG)
.show();
}
};
// Setup Caldroid
caldroidFragment.setCaldroidListener(listener);
final TextView textView = (TextView) findViewById(R.id.textview);
final Button customizeButton = (Button) findViewById(R.id.customize_button);
// Customize the calendar
customizeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (undo) {
customizeButton.setText(getString(R.string.customize));
textView.setText("");
// Reset calendar
caldroidFragment.clearDisableDates();
caldroidFragment.clearSelectedDates();
caldroidFragment.setMinDate(null);
caldroidFragment.setMaxDate(null);
caldroidFragment.setShowNavigationArrows(true);
caldroidFragment.refreshView();
undo = false;
return;
}
// Else
undo = true;
customizeButton.setText(getString(R.string.undo));
Calendar cal = Calendar.getInstance();
// Min date is last 7 days
cal.add(Calendar.DATE, -7);
Date minDate = cal.getTime();
// Max date is next 7 days
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 14);
Date maxDate = cal.getTime();
// Set selected dates
// From Date
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 2);
Date fromDate = cal.getTime();
// To Date
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 3);
Date toDate = cal.getTime();
// Set disabled dates
ArrayList<Date> disabledDates = new ArrayList<Date>();
for (int i = 5; i < 8; i++) {
cal = Calendar.getInstance();
cal.add(Calendar.DATE, i);
disabledDates.add(cal.getTime());
}
// Customize
caldroidFragment.setMinDate(minDate);
caldroidFragment.setMaxDate(maxDate);
caldroidFragment.setDisableDates(disabledDates);
caldroidFragment.setSelectedDates(fromDate, toDate);
caldroidFragment.setShowNavigationArrows(false);
caldroidFragment.refreshView();
String text = "Today: " + formatter.format(new Date()) + "\n";
text += "Min Date: " + formatter.format(minDate) + "\n";
text += "Max Date: " + formatter.format(maxDate) + "\n";
text += "Select From Date: " + formatter.format(fromDate)
+ "\n";
text += "Select To Date: " + formatter.format(toDate) + "\n";
for (Date date : disabledDates) {
text += "Max Date: " + formatter.format(date) + "\n";
}
textView.setText(text);
}
});
Button showDialogButton = (Button) findViewById(R.id.show_dialog_button);
showDialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CaldroidFragment dialogCaldroidFragment = CaldroidFragment
.newInstance("Select a date", 3, 2013);
dialogCaldroidFragment.show(getSupportFragmentManager(),
"CALDROID_DIALOG_FRAGMENT");
dialogCaldroidFragment.setCaldroidListener(listener);
}
});
}
|
diff --git a/src/risk/game/Map.java b/src/risk/game/Map.java
index 03a32ee..6741a3b 100644
--- a/src/risk/game/Map.java
+++ b/src/risk/game/Map.java
@@ -1,269 +1,272 @@
package risk.game;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
public class Map {
/**
* A list of continents.
*/
private LinkedList<Continent> continents;
public Map() {
continents = new LinkedList<Continent>();
initEurope();
initNorthAmerica();
initSouthAmerica();
initAsia();
initAfrica();
initAustralia();
setNeighbours();
}
private void initEurope() {
LinkedList<Country> countries = new LinkedList<Country>();
String[] names = {
Country.ICELAND,
Country.SCANDINAVIA,
Country.GREATBRITAIN,
Country.NORTHERNEUROPE,
Country.WESTERNEUROPE,
Country.SOUTHERNEUROPE,
};
for (String n : names) {
countries.add(new Country(n));
}
continents.add(new Continent("Europe", countries));
}
private void initNorthAmerica() {
LinkedList<Country> countries = new LinkedList<Country>();
String[] names = {
Country.ALASKA,
Country.NORTHWESTTERRITORY,
Country.GREENLAND,
Country.EASTERNCANADA,
Country.ALBERTA,
Country.ONTARIO,
Country.EASTERNUNITEDSTATES,
Country.WESTERNUNITEDSTATES,
Country.CENTRALAMERICA,
};
for (String n : names) {
countries.add(new Country(n));
}
continents.add(new Continent("North America", countries));
}
private void initSouthAmerica() {
LinkedList<Country> countries = new LinkedList<Country>();
String[] names = {
Country.VENEZUELA,
Country.BRAZIL,
Country.PERU,
Country.ARGENTINA,
};
for (String n : names) {
countries.add(new Country(n));
}
continents.add(new Continent("South America", countries));
}
private void initAfrica() {
LinkedList<Country> countries = new LinkedList<Country>();
String[] names = {
Country.EGYPT,
Country.NORTHAFRICA,
Country.EASTAFRICA,
Country.CENTRALAFRICA,
Country.SOUTHAFRICA,
Country.MADAGASCAR,
};
for (String n : names) {
countries.add(new Country(n));
}
continents.add(new Continent("Africa", countries));
}
private void initAsia() {
LinkedList<Country> countries = new LinkedList<Country>();
String[] names = {
Country.RUSSIA,
Country.URAL,
Country.SIBERIA,
Country.YAKUTSK,
Country.KAMCHATKA,
Country.AFGHANISTAN,
Country.MIDDLEEAST,
Country.INDIA,
Country.CHINA,
Country.SIAM,
Country.IRKUTSK,
Country.JAPAN,
Country.MONGOLIA,
};
for (String n : names) {
countries.add(new Country(n));
}
continents.add(new Continent("Asia", countries));
}
private void initAustralia() {
LinkedList<Country> countries = new LinkedList<Country>();
String[] names = {
Country.INDONESIA,
Country.EASTERNAUSTRALIA,
Country.WESTERNAUSTRALIA,
Country.NEWGUINEA,
};
for (String n : names) {
countries.add(new Country(n));
}
continents.add(new Continent("Australia", countries));
}
private void setNeighbours(String a, String b) {
Country ca = getCountry(a);
Country cb = getCountry(b);
ca.addNeighbour(cb);
cb.addNeighbour(ca);
}
private void setNeighbours() {
setNeighbours(Country.ALASKA, Country.NORTHWESTTERRITORY);
setNeighbours(Country.ALASKA, Country.KAMCHATKA);
setNeighbours(Country.ALASKA, Country.ALBERTA);
setNeighbours(Country.NORTHWESTTERRITORY, Country.GREENLAND);
setNeighbours(Country.NORTHWESTTERRITORY, Country.ALBERTA);
setNeighbours(Country.NORTHWESTTERRITORY, Country.ONTARIO);
setNeighbours(Country.GREENLAND, Country.ONTARIO);
setNeighbours(Country.GREENLAND, Country.EASTERNCANADA);
setNeighbours(Country.GREENLAND, Country.ICELAND);
setNeighbours(Country.ALBERTA, Country.ONTARIO);
setNeighbours(Country.ALBERTA, Country.WESTERNUNITEDSTATES);
setNeighbours(Country.ONTARIO, Country.EASTERNCANADA);
setNeighbours(Country.ONTARIO, Country.WESTERNUNITEDSTATES);
setNeighbours(Country.ONTARIO, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.EASTERNCANADA, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.WESTERNUNITEDSTATES, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.WESTERNUNITEDSTATES, Country.CENTRALAMERICA);
setNeighbours(Country.EASTERNUNITEDSTATES, Country.CENTRALAMERICA);
setNeighbours(Country.CENTRALAMERICA, Country.VENEZUELA);
setNeighbours(Country.VENEZUELA, Country.PERU);
setNeighbours(Country.VENEZUELA, Country.BRAZIL);
setNeighbours(Country.PERU, Country.BRAZIL);
setNeighbours(Country.PERU, Country.ARGENTINA);
setNeighbours(Country.BRAZIL, Country.ARGENTINA);
setNeighbours(Country.BRAZIL, Country.NORTHAFRICA);
setNeighbours(Country.ICELAND, Country.SCANDINAVIA);
setNeighbours(Country.ICELAND, Country.GREATBRITAIN);
setNeighbours(Country.SCANDINAVIA, Country.RUSSIA);
setNeighbours(Country.SCANDINAVIA, Country.GREATBRITAIN);
setNeighbours(Country.SCANDINAVIA, Country.NORTHERNEUROPE);
setNeighbours(Country.GREATBRITAIN, Country.NORTHERNEUROPE);
setNeighbours(Country.GREATBRITAIN, Country.WESTERNEUROPE);
setNeighbours(Country.NORTHERNEUROPE, Country.SOUTHERNEUROPE);
setNeighbours(Country.NORTHERNEUROPE, Country.RUSSIA);
setNeighbours(Country.NORTHERNEUROPE, Country.WESTERNEUROPE);
setNeighbours(Country.WESTERNEUROPE, Country.SOUTHERNEUROPE);
setNeighbours(Country.WESTERNEUROPE, Country.NORTHAFRICA);
setNeighbours(Country.SOUTHERNEUROPE, Country.MIDDLEEAST);
setNeighbours(Country.SOUTHERNEUROPE, Country.RUSSIA);
- // setNeighbours(Country.SOUTHERNEUROPE, Country.NORTHAFRICA); ????
+ setNeighbours(Country.SOUTHERNEUROPE, Country.NORTHAFRICA);
+ setNeighbours(Country.SOUTHERNEUROPE, Country.EGYPT);
setNeighbours(Country.NORTHAFRICA, Country.EGYPT);
setNeighbours(Country.NORTHAFRICA, Country.EASTAFRICA);
setNeighbours(Country.NORTHAFRICA, Country.CENTRALAFRICA);
setNeighbours(Country.EGYPT, Country.MIDDLEEAST);
setNeighbours(Country.EGYPT, Country.EASTAFRICA);
setNeighbours(Country.EASTAFRICA, Country.CENTRALAFRICA);
- // setNeighbours(Country.EASTAFRICA, Country.MADAGASCAR); ????
+ setNeighbours(Country.EASTAFRICA, Country.SOUTHAFRICA);
+ setNeighbours(Country.EASTAFRICA, Country.MADAGASCAR);
setNeighbours(Country.CENTRALAFRICA, Country.SOUTHAFRICA);
setNeighbours(Country.SOUTHAFRICA, Country.MADAGASCAR);
setNeighbours(Country.RUSSIA, Country.URAL);
setNeighbours(Country.RUSSIA, Country.AFGHANISTAN);
setNeighbours(Country.RUSSIA, Country.MIDDLEEAST);
setNeighbours(Country.URAL, Country.SIBERIA);
setNeighbours(Country.URAL, Country.AFGHANISTAN);
setNeighbours(Country.URAL, Country.CHINA);
setNeighbours(Country.SIBERIA, Country.YAKUTSK);
setNeighbours(Country.SIBERIA, Country.IRKUTSK);
setNeighbours(Country.SIBERIA, Country.MONGOLIA);
setNeighbours(Country.SIBERIA, Country.CHINA);
setNeighbours(Country.YAKUTSK, Country.KAMCHATKA);
setNeighbours(Country.YAKUTSK, Country.IRKUTSK);
setNeighbours(Country.KAMCHATKA, Country.JAPAN);
setNeighbours(Country.KAMCHATKA, Country.MONGOLIA);
setNeighbours(Country.IRKUTSK, Country.KAMCHATKA);
setNeighbours(Country.IRKUTSK, Country.MONGOLIA);
setNeighbours(Country.MONGOLIA, Country.JAPAN);
setNeighbours(Country.MONGOLIA, Country.CHINA);
setNeighbours(Country.AFGHANISTAN, Country.CHINA);
setNeighbours(Country.AFGHANISTAN, Country.INDIA);
setNeighbours(Country.AFGHANISTAN, Country.MIDDLEEAST);
setNeighbours(Country.CHINA, Country.INDIA);
setNeighbours(Country.CHINA, Country.SIAM);
setNeighbours(Country.MIDDLEEAST, Country.INDIA);
+ setNeighbours(Country.MIDDLEEAST, Country.EASTAFRICA);
setNeighbours(Country.INDIA, Country.SIAM);
setNeighbours(Country.SIAM, Country.INDONESIA);
setNeighbours(Country.INDONESIA, Country.NEWGUINEA);
setNeighbours(Country.INDONESIA, Country.WESTERNAUSTRALIA);
- setNeighbours(Country.INDONESIA, Country.EASTERNAUSTRALIA);
setNeighbours(Country.NEWGUINEA, Country.EASTERNAUSTRALIA);
setNeighbours(Country.WESTERNAUSTRALIA, Country.EASTERNAUSTRALIA);
+ setNeighbours(Country.WESTERNAUSTRALIA, Country.NEWGUINEA);
}
public Country getCountry(String countryName) {
for(Continent c : continents) {
for (Country country : c.getCountries()) {
if (country.getName().compareTo(countryName) == 0) {
return country;
}
}
}
return null;
}
public Collection<Continent> getContinents() {
return continents;
}
public void selectCountry(Country c) {
c.setSelected(true);
}
public void cancelCountrySelection(Country c) {
c.setSelected(false);
}
public Country getSelectedCountryNeighbour(Country c) {
for (Country neighbour : c.getNeighbours()) {
if (neighbour.isSelected()) {
return neighbour;
}
}
return null;
}
public boolean isCountrySelected(Country c) {
return c.isSelected();
}
public void cancelCountryNeighbourSelection(Country c) {
for (Country neighbour : c.getNeighbours()) {
if (neighbour.isSelected()) {
neighbour.setSelected(false);
break;
}
}
}
}
| false | true | private void setNeighbours() {
setNeighbours(Country.ALASKA, Country.NORTHWESTTERRITORY);
setNeighbours(Country.ALASKA, Country.KAMCHATKA);
setNeighbours(Country.ALASKA, Country.ALBERTA);
setNeighbours(Country.NORTHWESTTERRITORY, Country.GREENLAND);
setNeighbours(Country.NORTHWESTTERRITORY, Country.ALBERTA);
setNeighbours(Country.NORTHWESTTERRITORY, Country.ONTARIO);
setNeighbours(Country.GREENLAND, Country.ONTARIO);
setNeighbours(Country.GREENLAND, Country.EASTERNCANADA);
setNeighbours(Country.GREENLAND, Country.ICELAND);
setNeighbours(Country.ALBERTA, Country.ONTARIO);
setNeighbours(Country.ALBERTA, Country.WESTERNUNITEDSTATES);
setNeighbours(Country.ONTARIO, Country.EASTERNCANADA);
setNeighbours(Country.ONTARIO, Country.WESTERNUNITEDSTATES);
setNeighbours(Country.ONTARIO, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.EASTERNCANADA, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.WESTERNUNITEDSTATES, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.WESTERNUNITEDSTATES, Country.CENTRALAMERICA);
setNeighbours(Country.EASTERNUNITEDSTATES, Country.CENTRALAMERICA);
setNeighbours(Country.CENTRALAMERICA, Country.VENEZUELA);
setNeighbours(Country.VENEZUELA, Country.PERU);
setNeighbours(Country.VENEZUELA, Country.BRAZIL);
setNeighbours(Country.PERU, Country.BRAZIL);
setNeighbours(Country.PERU, Country.ARGENTINA);
setNeighbours(Country.BRAZIL, Country.ARGENTINA);
setNeighbours(Country.BRAZIL, Country.NORTHAFRICA);
setNeighbours(Country.ICELAND, Country.SCANDINAVIA);
setNeighbours(Country.ICELAND, Country.GREATBRITAIN);
setNeighbours(Country.SCANDINAVIA, Country.RUSSIA);
setNeighbours(Country.SCANDINAVIA, Country.GREATBRITAIN);
setNeighbours(Country.SCANDINAVIA, Country.NORTHERNEUROPE);
setNeighbours(Country.GREATBRITAIN, Country.NORTHERNEUROPE);
setNeighbours(Country.GREATBRITAIN, Country.WESTERNEUROPE);
setNeighbours(Country.NORTHERNEUROPE, Country.SOUTHERNEUROPE);
setNeighbours(Country.NORTHERNEUROPE, Country.RUSSIA);
setNeighbours(Country.NORTHERNEUROPE, Country.WESTERNEUROPE);
setNeighbours(Country.WESTERNEUROPE, Country.SOUTHERNEUROPE);
setNeighbours(Country.WESTERNEUROPE, Country.NORTHAFRICA);
setNeighbours(Country.SOUTHERNEUROPE, Country.MIDDLEEAST);
setNeighbours(Country.SOUTHERNEUROPE, Country.RUSSIA);
// setNeighbours(Country.SOUTHERNEUROPE, Country.NORTHAFRICA); ????
setNeighbours(Country.NORTHAFRICA, Country.EGYPT);
setNeighbours(Country.NORTHAFRICA, Country.EASTAFRICA);
setNeighbours(Country.NORTHAFRICA, Country.CENTRALAFRICA);
setNeighbours(Country.EGYPT, Country.MIDDLEEAST);
setNeighbours(Country.EGYPT, Country.EASTAFRICA);
setNeighbours(Country.EASTAFRICA, Country.CENTRALAFRICA);
// setNeighbours(Country.EASTAFRICA, Country.MADAGASCAR); ????
setNeighbours(Country.CENTRALAFRICA, Country.SOUTHAFRICA);
setNeighbours(Country.SOUTHAFRICA, Country.MADAGASCAR);
setNeighbours(Country.RUSSIA, Country.URAL);
setNeighbours(Country.RUSSIA, Country.AFGHANISTAN);
setNeighbours(Country.RUSSIA, Country.MIDDLEEAST);
setNeighbours(Country.URAL, Country.SIBERIA);
setNeighbours(Country.URAL, Country.AFGHANISTAN);
setNeighbours(Country.URAL, Country.CHINA);
setNeighbours(Country.SIBERIA, Country.YAKUTSK);
setNeighbours(Country.SIBERIA, Country.IRKUTSK);
setNeighbours(Country.SIBERIA, Country.MONGOLIA);
setNeighbours(Country.SIBERIA, Country.CHINA);
setNeighbours(Country.YAKUTSK, Country.KAMCHATKA);
setNeighbours(Country.YAKUTSK, Country.IRKUTSK);
setNeighbours(Country.KAMCHATKA, Country.JAPAN);
setNeighbours(Country.KAMCHATKA, Country.MONGOLIA);
setNeighbours(Country.IRKUTSK, Country.KAMCHATKA);
setNeighbours(Country.IRKUTSK, Country.MONGOLIA);
setNeighbours(Country.MONGOLIA, Country.JAPAN);
setNeighbours(Country.MONGOLIA, Country.CHINA);
setNeighbours(Country.AFGHANISTAN, Country.CHINA);
setNeighbours(Country.AFGHANISTAN, Country.INDIA);
setNeighbours(Country.AFGHANISTAN, Country.MIDDLEEAST);
setNeighbours(Country.CHINA, Country.INDIA);
setNeighbours(Country.CHINA, Country.SIAM);
setNeighbours(Country.MIDDLEEAST, Country.INDIA);
setNeighbours(Country.INDIA, Country.SIAM);
setNeighbours(Country.SIAM, Country.INDONESIA);
setNeighbours(Country.INDONESIA, Country.NEWGUINEA);
setNeighbours(Country.INDONESIA, Country.WESTERNAUSTRALIA);
setNeighbours(Country.INDONESIA, Country.EASTERNAUSTRALIA);
setNeighbours(Country.NEWGUINEA, Country.EASTERNAUSTRALIA);
setNeighbours(Country.WESTERNAUSTRALIA, Country.EASTERNAUSTRALIA);
}
| private void setNeighbours() {
setNeighbours(Country.ALASKA, Country.NORTHWESTTERRITORY);
setNeighbours(Country.ALASKA, Country.KAMCHATKA);
setNeighbours(Country.ALASKA, Country.ALBERTA);
setNeighbours(Country.NORTHWESTTERRITORY, Country.GREENLAND);
setNeighbours(Country.NORTHWESTTERRITORY, Country.ALBERTA);
setNeighbours(Country.NORTHWESTTERRITORY, Country.ONTARIO);
setNeighbours(Country.GREENLAND, Country.ONTARIO);
setNeighbours(Country.GREENLAND, Country.EASTERNCANADA);
setNeighbours(Country.GREENLAND, Country.ICELAND);
setNeighbours(Country.ALBERTA, Country.ONTARIO);
setNeighbours(Country.ALBERTA, Country.WESTERNUNITEDSTATES);
setNeighbours(Country.ONTARIO, Country.EASTERNCANADA);
setNeighbours(Country.ONTARIO, Country.WESTERNUNITEDSTATES);
setNeighbours(Country.ONTARIO, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.EASTERNCANADA, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.WESTERNUNITEDSTATES, Country.EASTERNUNITEDSTATES);
setNeighbours(Country.WESTERNUNITEDSTATES, Country.CENTRALAMERICA);
setNeighbours(Country.EASTERNUNITEDSTATES, Country.CENTRALAMERICA);
setNeighbours(Country.CENTRALAMERICA, Country.VENEZUELA);
setNeighbours(Country.VENEZUELA, Country.PERU);
setNeighbours(Country.VENEZUELA, Country.BRAZIL);
setNeighbours(Country.PERU, Country.BRAZIL);
setNeighbours(Country.PERU, Country.ARGENTINA);
setNeighbours(Country.BRAZIL, Country.ARGENTINA);
setNeighbours(Country.BRAZIL, Country.NORTHAFRICA);
setNeighbours(Country.ICELAND, Country.SCANDINAVIA);
setNeighbours(Country.ICELAND, Country.GREATBRITAIN);
setNeighbours(Country.SCANDINAVIA, Country.RUSSIA);
setNeighbours(Country.SCANDINAVIA, Country.GREATBRITAIN);
setNeighbours(Country.SCANDINAVIA, Country.NORTHERNEUROPE);
setNeighbours(Country.GREATBRITAIN, Country.NORTHERNEUROPE);
setNeighbours(Country.GREATBRITAIN, Country.WESTERNEUROPE);
setNeighbours(Country.NORTHERNEUROPE, Country.SOUTHERNEUROPE);
setNeighbours(Country.NORTHERNEUROPE, Country.RUSSIA);
setNeighbours(Country.NORTHERNEUROPE, Country.WESTERNEUROPE);
setNeighbours(Country.WESTERNEUROPE, Country.SOUTHERNEUROPE);
setNeighbours(Country.WESTERNEUROPE, Country.NORTHAFRICA);
setNeighbours(Country.SOUTHERNEUROPE, Country.MIDDLEEAST);
setNeighbours(Country.SOUTHERNEUROPE, Country.RUSSIA);
setNeighbours(Country.SOUTHERNEUROPE, Country.NORTHAFRICA);
setNeighbours(Country.SOUTHERNEUROPE, Country.EGYPT);
setNeighbours(Country.NORTHAFRICA, Country.EGYPT);
setNeighbours(Country.NORTHAFRICA, Country.EASTAFRICA);
setNeighbours(Country.NORTHAFRICA, Country.CENTRALAFRICA);
setNeighbours(Country.EGYPT, Country.MIDDLEEAST);
setNeighbours(Country.EGYPT, Country.EASTAFRICA);
setNeighbours(Country.EASTAFRICA, Country.CENTRALAFRICA);
setNeighbours(Country.EASTAFRICA, Country.SOUTHAFRICA);
setNeighbours(Country.EASTAFRICA, Country.MADAGASCAR);
setNeighbours(Country.CENTRALAFRICA, Country.SOUTHAFRICA);
setNeighbours(Country.SOUTHAFRICA, Country.MADAGASCAR);
setNeighbours(Country.RUSSIA, Country.URAL);
setNeighbours(Country.RUSSIA, Country.AFGHANISTAN);
setNeighbours(Country.RUSSIA, Country.MIDDLEEAST);
setNeighbours(Country.URAL, Country.SIBERIA);
setNeighbours(Country.URAL, Country.AFGHANISTAN);
setNeighbours(Country.URAL, Country.CHINA);
setNeighbours(Country.SIBERIA, Country.YAKUTSK);
setNeighbours(Country.SIBERIA, Country.IRKUTSK);
setNeighbours(Country.SIBERIA, Country.MONGOLIA);
setNeighbours(Country.SIBERIA, Country.CHINA);
setNeighbours(Country.YAKUTSK, Country.KAMCHATKA);
setNeighbours(Country.YAKUTSK, Country.IRKUTSK);
setNeighbours(Country.KAMCHATKA, Country.JAPAN);
setNeighbours(Country.KAMCHATKA, Country.MONGOLIA);
setNeighbours(Country.IRKUTSK, Country.KAMCHATKA);
setNeighbours(Country.IRKUTSK, Country.MONGOLIA);
setNeighbours(Country.MONGOLIA, Country.JAPAN);
setNeighbours(Country.MONGOLIA, Country.CHINA);
setNeighbours(Country.AFGHANISTAN, Country.CHINA);
setNeighbours(Country.AFGHANISTAN, Country.INDIA);
setNeighbours(Country.AFGHANISTAN, Country.MIDDLEEAST);
setNeighbours(Country.CHINA, Country.INDIA);
setNeighbours(Country.CHINA, Country.SIAM);
setNeighbours(Country.MIDDLEEAST, Country.INDIA);
setNeighbours(Country.MIDDLEEAST, Country.EASTAFRICA);
setNeighbours(Country.INDIA, Country.SIAM);
setNeighbours(Country.SIAM, Country.INDONESIA);
setNeighbours(Country.INDONESIA, Country.NEWGUINEA);
setNeighbours(Country.INDONESIA, Country.WESTERNAUSTRALIA);
setNeighbours(Country.NEWGUINEA, Country.EASTERNAUSTRALIA);
setNeighbours(Country.WESTERNAUSTRALIA, Country.EASTERNAUSTRALIA);
setNeighbours(Country.WESTERNAUSTRALIA, Country.NEWGUINEA);
}
|
diff --git a/autotools/org.eclipse.linuxtools.cdt.autotools.ui/src/org/eclipse/linuxtools/internal/cdt/autotools/ui/actions/InvokeLibtoolizeAction.java b/autotools/org.eclipse.linuxtools.cdt.autotools.ui/src/org/eclipse/linuxtools/internal/cdt/autotools/ui/actions/InvokeLibtoolizeAction.java
index 02ec65d21..43435290a 100644
--- a/autotools/org.eclipse.linuxtools.cdt.autotools.ui/src/org/eclipse/linuxtools/internal/cdt/autotools/ui/actions/InvokeLibtoolizeAction.java
+++ b/autotools/org.eclipse.linuxtools.cdt.autotools.ui/src/org/eclipse/linuxtools/internal/cdt/autotools/ui/actions/InvokeLibtoolizeAction.java
@@ -1,78 +1,78 @@
/*******************************************************************************
* Copyright (c) 2009 Red Hat Inc..
* 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:
* Red Hat Incorporated - initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.internal.cdt.autotools.ui.actions;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.linuxtools.internal.cdt.autotools.core.AutotoolsPropertyConstants;
import org.eclipse.swt.widgets.Shell;
public class InvokeLibtoolizeAction extends InvokeAction {
private static final String DEFAULT_OPTION = ""; //$NON-NLS-1$
private static final String DEFAULT_COMMAND = "libtoolize"; //$NON-NLS-1$
public void run(IAction action) {
IContainer container = getSelectedContainer();
if (container == null)
return;
IPath execDir = getExecDir(container);
String cwd = InvokeMessages.getString("CWD") + getCWD(container); //$NON-NLS-1$
InputDialog optionDialog = new SingleInputDialog(
new Shell(),
cwd,
InvokeMessages
.getString("InvokeLibtoolizeAction.windowTitle.options"), //$NON-NLS-1$
InvokeMessages
.getString("InvokeLibtoolizeAction.message.options.otherOptions"), //$NON-NLS-1$
DEFAULT_OPTION, null);
optionDialog.open();
// chop args into string array
String rawArgList = optionDialog.getValue();
String[] optionsList = simpleParseOptions(rawArgList);
String[] argumentList = new String[optionsList.length];
System.arraycopy(optionsList, 0, argumentList, 0, optionsList.length);
if (container != null) {
String libtoolizeCommand = null;
IProject project = getSelectedContainer().getProject();
try {
- libtoolizeCommand = project.getPersistentProperty(AutotoolsPropertyConstants.AUTOHEADER_TOOL);
+ libtoolizeCommand = project.getPersistentProperty(AutotoolsPropertyConstants.LIBTOOLIZE_TOOL);
} catch (CoreException e) {
// do nothing
}
// If unset, use default system path
if (libtoolizeCommand == null)
libtoolizeCommand = DEFAULT_COMMAND;
executeConsoleCommand(DEFAULT_COMMAND, libtoolizeCommand,
argumentList, execDir);
}
}
public void dispose() {
}
}
| true | true | public void run(IAction action) {
IContainer container = getSelectedContainer();
if (container == null)
return;
IPath execDir = getExecDir(container);
String cwd = InvokeMessages.getString("CWD") + getCWD(container); //$NON-NLS-1$
InputDialog optionDialog = new SingleInputDialog(
new Shell(),
cwd,
InvokeMessages
.getString("InvokeLibtoolizeAction.windowTitle.options"), //$NON-NLS-1$
InvokeMessages
.getString("InvokeLibtoolizeAction.message.options.otherOptions"), //$NON-NLS-1$
DEFAULT_OPTION, null);
optionDialog.open();
// chop args into string array
String rawArgList = optionDialog.getValue();
String[] optionsList = simpleParseOptions(rawArgList);
String[] argumentList = new String[optionsList.length];
System.arraycopy(optionsList, 0, argumentList, 0, optionsList.length);
if (container != null) {
String libtoolizeCommand = null;
IProject project = getSelectedContainer().getProject();
try {
libtoolizeCommand = project.getPersistentProperty(AutotoolsPropertyConstants.AUTOHEADER_TOOL);
} catch (CoreException e) {
// do nothing
}
// If unset, use default system path
if (libtoolizeCommand == null)
libtoolizeCommand = DEFAULT_COMMAND;
executeConsoleCommand(DEFAULT_COMMAND, libtoolizeCommand,
argumentList, execDir);
}
}
| public void run(IAction action) {
IContainer container = getSelectedContainer();
if (container == null)
return;
IPath execDir = getExecDir(container);
String cwd = InvokeMessages.getString("CWD") + getCWD(container); //$NON-NLS-1$
InputDialog optionDialog = new SingleInputDialog(
new Shell(),
cwd,
InvokeMessages
.getString("InvokeLibtoolizeAction.windowTitle.options"), //$NON-NLS-1$
InvokeMessages
.getString("InvokeLibtoolizeAction.message.options.otherOptions"), //$NON-NLS-1$
DEFAULT_OPTION, null);
optionDialog.open();
// chop args into string array
String rawArgList = optionDialog.getValue();
String[] optionsList = simpleParseOptions(rawArgList);
String[] argumentList = new String[optionsList.length];
System.arraycopy(optionsList, 0, argumentList, 0, optionsList.length);
if (container != null) {
String libtoolizeCommand = null;
IProject project = getSelectedContainer().getProject();
try {
libtoolizeCommand = project.getPersistentProperty(AutotoolsPropertyConstants.LIBTOOLIZE_TOOL);
} catch (CoreException e) {
// do nothing
}
// If unset, use default system path
if (libtoolizeCommand == null)
libtoolizeCommand = DEFAULT_COMMAND;
executeConsoleCommand(DEFAULT_COMMAND, libtoolizeCommand,
argumentList, execDir);
}
}
|
diff --git a/src/me/Kruithne/WolfHunt/Configuration.java b/src/me/Kruithne/WolfHunt/Configuration.java
index 02fb6db..0076887 100644
--- a/src/me/Kruithne/WolfHunt/Configuration.java
+++ b/src/me/Kruithne/WolfHunt/Configuration.java
@@ -1,60 +1,60 @@
package me.Kruithne.WolfHunt;
public class Configuration {
private WolfHunt wolfHuntPlugin = null;
public int trackingItem;
public int trackingRadius;
public boolean babyWolvesCanTrack;
public boolean preventTrackingOps;
public boolean allowOpOverride;
public boolean enableVanishNoPacketSupport;
Configuration(WolfHunt parentPlugin)
{
this.wolfHuntPlugin = parentPlugin;
}
public String getOrSetConfigValue(String configKey, String defaultValue)
{
if (this.hasConfigValue(configKey))
{
return this.getConfigValue(configKey);
}
else
{
- this.setConfigValue(String.format(Constants.pluginNodePath, configKey), defaultValue);
+ this.setConfigValue(configKey, defaultValue);
return defaultValue;
}
}
public String getConfigValue(String configKey)
{
return this.wolfHuntPlugin.getConfig().getString(String.format(Constants.pluginNodePath, configKey));
}
public boolean hasConfigValue(String configKey)
{
return this.wolfHuntPlugin.getConfig().contains(String.format(Constants.pluginNodePath, configKey));
}
public void setConfigValue(String configKey, String configValue)
{
this.wolfHuntPlugin.getConfig().set(String.format(Constants.pluginNodePath, configKey), configValue);
this.wolfHuntPlugin.saveConfig();
}
public void loadConfiguration()
{
this.trackingItem = Integer.parseInt(this.getOrSetConfigValue("trackingItem", Constants.default_trackingItem));
this.trackingRadius = Integer.parseInt(this.getOrSetConfigValue("trackingRadius", Constants.default_trackingRadius));
this.allowOpOverride = Boolean.parseBoolean(this.getOrSetConfigValue("allowOpOverride", Constants.default_allowOpOverride));
this.preventTrackingOps = Boolean.parseBoolean(this.getOrSetConfigValue("preventTrackingOps", Constants.default_preventTrackingOps));
this.babyWolvesCanTrack = Boolean.parseBoolean(this.getOrSetConfigValue("babyWolvesCanTrack", Constants.default_babyWolvesCanTrack));
this.enableVanishNoPacketSupport = Boolean.parseBoolean(this.getOrSetConfigValue("enableVanishNoPacketSupport", Constants.default_enableVanishNoPacketSupport));
}
}
| true | true | public String getOrSetConfigValue(String configKey, String defaultValue)
{
if (this.hasConfigValue(configKey))
{
return this.getConfigValue(configKey);
}
else
{
this.setConfigValue(String.format(Constants.pluginNodePath, configKey), defaultValue);
return defaultValue;
}
}
| public String getOrSetConfigValue(String configKey, String defaultValue)
{
if (this.hasConfigValue(configKey))
{
return this.getConfigValue(configKey);
}
else
{
this.setConfigValue(configKey, defaultValue);
return defaultValue;
}
}
|
diff --git a/src/org/cyberneko/html/HTMLTagBalancer.java b/src/org/cyberneko/html/HTMLTagBalancer.java
index b56b046..cc1b23f 100644
--- a/src/org/cyberneko/html/HTMLTagBalancer.java
+++ b/src/org/cyberneko/html/HTMLTagBalancer.java
@@ -1,1458 +1,1447 @@
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* 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.cyberneko.html;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.xerces.util.XMLAttributesImpl;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.cyberneko.html.HTMLElements.Element;
import org.cyberneko.html.filters.NamespaceBinder;
import org.cyberneko.html.xercesbridge.XercesBridge;
/**
* Balances tags in an HTML document. This component receives document events
* and tries to correct many common mistakes that human (and computer) HTML
* document authors make. This tag balancer can:
* <ul>
* <li>add missing parent elements;
* <li>automatically close elements with optional end tags; and
* <li>handle mis-matched inline element tags.
* </ul>
* <p>
* This component recognizes the following features:
* <ul>
* <li>http://cyberneko.org/html/features/augmentations
* <li>http://cyberneko.org/html/features/report-errors
* <li>http://cyberneko.org/html/features/balance-tags/document-fragment
* <li>http://cyberneko.org/html/features/balance-tags/ignore-outside-content
* </ul>
* <p>
* This component recognizes the following properties:
* <ul>
* <li>http://cyberneko.org/html/properties/names/elems
* <li>http://cyberneko.org/html/properties/names/attrs
* <li>http://cyberneko.org/html/properties/error-reporter
* <li>http://cyberneko.org/html/properties/balance-tags/current-stack
* </ul>
*
* @see HTMLElements
*
* @author Andy Clark
* @author Marc Guillemot
*
* @version $Id: HTMLTagBalancer.java,v 1.20 2005/02/14 04:06:22 andyc Exp $
*/
public class HTMLTagBalancer
implements XMLDocumentFilter, HTMLComponent {
//
// Constants
//
// features
/** Namespaces. */
protected static final String NAMESPACES = "http://xml.org/sax/features/namespaces";
/** Include infoset augmentations. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Report errors. */
protected static final String REPORT_ERRORS = "http://cyberneko.org/html/features/report-errors";
/** Document fragment balancing only (deprecated). */
protected static final String DOCUMENT_FRAGMENT_DEPRECATED = "http://cyberneko.org/html/features/document-fragment";
/** Document fragment balancing only. */
protected static final String DOCUMENT_FRAGMENT = "http://cyberneko.org/html/features/balance-tags/document-fragment";
/** Ignore outside content. */
protected static final String IGNORE_OUTSIDE_CONTENT = "http://cyberneko.org/html/features/balance-tags/ignore-outside-content";
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
NAMESPACES,
AUGMENTATIONS,
REPORT_ERRORS,
DOCUMENT_FRAGMENT_DEPRECATED,
DOCUMENT_FRAGMENT,
IGNORE_OUTSIDE_CONTENT,
};
/** Recognized features defaults. */
private static final Boolean[] RECOGNIZED_FEATURES_DEFAULTS = {
null,
null,
null,
null,
Boolean.FALSE,
Boolean.FALSE,
};
// properties
/** Modify HTML element names: { "upper", "lower", "default" }. */
protected static final String NAMES_ELEMS = "http://cyberneko.org/html/properties/names/elems";
/** Modify HTML attribute names: { "upper", "lower", "default" }. */
protected static final String NAMES_ATTRS = "http://cyberneko.org/html/properties/names/attrs";
/** Error reporter. */
protected static final String ERROR_REPORTER = "http://cyberneko.org/html/properties/error-reporter";
/**
* <font color="red">EXPERIMENTAL: may change in next release</font><br/>
* Name of the property holding the stack of elements in which context a document fragment should be parsed.
**/
public static final String FRAGMENT_CONTEXT_STACK = "http://cyberneko.org/html/properties/balance-tags/fragment-context-stack";
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
NAMES_ELEMS,
NAMES_ATTRS,
ERROR_REPORTER,
FRAGMENT_CONTEXT_STACK,
};
/** Recognized properties defaults. */
private static final Object[] RECOGNIZED_PROPERTIES_DEFAULTS = {
null,
null,
null,
null,
};
// modify HTML names
/** Don't modify HTML names. */
protected static final short NAMES_NO_CHANGE = 0;
/** Match HTML element names. */
protected static final short NAMES_MATCH = 0;
/** Uppercase HTML names. */
protected static final short NAMES_UPPERCASE = 1;
/** Lowercase HTML names. */
protected static final short NAMES_LOWERCASE = 2;
// static vars
/** Synthesized event info item. */
protected static final HTMLEventInfo SYNTHESIZED_ITEM =
new HTMLEventInfo.SynthesizedItem();
//
// Data
//
// features
/** Namespaces. */
protected boolean fNamespaces;
/** Include infoset augmentations. */
protected boolean fAugmentations;
/** Report errors. */
protected boolean fReportErrors;
/** Document fragment balancing only. */
protected boolean fDocumentFragment;
/** Ignore outside content. */
protected boolean fIgnoreOutsideContent;
/** Allows self closing iframe tags. */
protected boolean fAllowSelfclosingIframe;
/** Allows self closing tags. */
protected boolean fAllowSelfclosingTags;
// properties
/** Modify HTML element names. */
protected short fNamesElems;
/** Modify HTML attribute names. */
protected short fNamesAttrs;
/** Error reporter. */
protected HTMLErrorReporter fErrorReporter;
// connections
/** The document source. */
protected XMLDocumentSource fDocumentSource;
/** The document handler. */
protected XMLDocumentHandler fDocumentHandler;
// state
/** The element stack. */
protected final InfoStack fElementStack = new InfoStack();
/** The inline stack. */
protected final InfoStack fInlineStack = new InfoStack();
/** True if seen anything. Important for xml declaration. */
protected boolean fSeenAnything;
/** True if root element has been seen. */
protected boolean fSeenDoctype;
/** True if root element has been seen. */
protected boolean fSeenRootElement;
/**
* True if seen the end of the document element. In other words,
* this variable is set to false <em>until</em> the end </HTML>
* tag is seen (or synthesized). This is used to ensure that
* extraneous events after the end of the document element do not
* make the document stream ill-formed.
*/
protected boolean fSeenRootElementEnd;
/** True if seen <head< element. */
protected boolean fSeenHeadElement;
/** True if seen <body< element. */
protected boolean fSeenBodyElement;
private boolean fSeenBodyElementEnd;
/** True if seen <frameset< element. */
private boolean fSeenFramesetElement;
/** True if a form is in the stack (allow to discard opening of nested forms) */
protected boolean fOpenedForm;
// temp vars
/** A qualified name. */
private final QName fQName = new QName();
/** Empty attributes. */
private final XMLAttributes fEmptyAttrs = new XMLAttributesImpl();
/** Augmentations. */
private final HTMLAugmentations fInfosetAugs = new HTMLAugmentations();
protected HTMLTagBalancingListener tagBalancingListener;
private LostText lostText_ = new LostText();
private boolean forcedStartElement_ = false;
private boolean forcedEndElement_ = false;
/**
* Stack of elements determining the context in which a document fragment should be parsed
*/
private QName[] fragmentContextStack_ = null;
private int fragmentContextStackSize_ = 0; // not 0 only when a fragment is parsed and fragmentContextStack_ is set
private List/*ElementEntry*/ endElementsBuffer_ = new ArrayList();
//
// HTMLComponent methods
//
/** Returns the default state for a feature. */
public Boolean getFeatureDefault(String featureId) {
int length = RECOGNIZED_FEATURES != null ? RECOGNIZED_FEATURES.length : 0;
for (int i = 0; i < length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return RECOGNIZED_FEATURES_DEFAULTS[i];
}
}
return null;
} // getFeatureDefault(String):Boolean
/** Returns the default state for a property. */
public Object getPropertyDefault(String propertyId) {
int length = RECOGNIZED_PROPERTIES != null ? RECOGNIZED_PROPERTIES.length : 0;
for (int i = 0; i < length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return RECOGNIZED_PROPERTIES_DEFAULTS[i];
}
}
return null;
} // getPropertyDefault(String):Object
//
// XMLComponent methods
//
/** Returns recognized features. */
public String[] getRecognizedFeatures() {
return RECOGNIZED_FEATURES;
} // getRecognizedFeatures():String[]
/** Returns recognized properties. */
public String[] getRecognizedProperties() {
return RECOGNIZED_PROPERTIES;
} // getRecognizedProperties():String[]
/** Resets the component. */
public void reset(final XMLComponentManager manager)
throws XMLConfigurationException {
// get features
fNamespaces = manager.getFeature(NAMESPACES);
fAugmentations = manager.getFeature(AUGMENTATIONS);
fReportErrors = manager.getFeature(REPORT_ERRORS);
fDocumentFragment = manager.getFeature(DOCUMENT_FRAGMENT) ||
manager.getFeature(DOCUMENT_FRAGMENT_DEPRECATED);
fIgnoreOutsideContent = manager.getFeature(IGNORE_OUTSIDE_CONTENT);
fAllowSelfclosingIframe = manager.getFeature(HTMLScanner.ALLOW_SELFCLOSING_IFRAME);
fAllowSelfclosingTags = manager.getFeature(HTMLScanner.ALLOW_SELFCLOSING_TAGS);
// get properties
fNamesElems = getNamesValue(String.valueOf(manager.getProperty(NAMES_ELEMS)));
fNamesAttrs = getNamesValue(String.valueOf(manager.getProperty(NAMES_ATTRS)));
fErrorReporter = (HTMLErrorReporter)manager.getProperty(ERROR_REPORTER);
fragmentContextStack_ = (QName[]) manager.getProperty(FRAGMENT_CONTEXT_STACK);
} // reset(XMLComponentManager)
/** Sets a feature. */
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
if (featureId.equals(AUGMENTATIONS)) {
fAugmentations = state;
return;
}
if (featureId.equals(REPORT_ERRORS)) {
fReportErrors = state;
return;
}
if (featureId.equals(IGNORE_OUTSIDE_CONTENT)) {
fIgnoreOutsideContent = state;
return;
}
} // setFeature(String,boolean)
/** Sets a property. */
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
if (propertyId.equals(NAMES_ELEMS)) {
fNamesElems = getNamesValue(String.valueOf(value));
return;
}
if (propertyId.equals(NAMES_ATTRS)) {
fNamesAttrs = getNamesValue(String.valueOf(value));
return;
}
} // setProperty(String,Object)
//
// XMLDocumentSource methods
//
/** Sets the document handler. */
public void setDocumentHandler(XMLDocumentHandler handler) {
fDocumentHandler = handler;
} // setDocumentHandler(XMLDocumentHandler)
// @since Xerces 2.1.0
/** Returns the document handler. */
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
} // getDocumentHandler():XMLDocumentHandler
//
// XMLDocumentHandler methods
//
// since Xerces-J 2.2.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext, Augmentations augs)
throws XNIException {
// reset state
fElementStack.top = 0;
if (fragmentContextStack_ != null) {
fragmentContextStackSize_ = fragmentContextStack_.length;
for (int i=0; i<fragmentContextStack_.length; ++i) {
final QName name = fragmentContextStack_[i];
final Element elt = HTMLElements.getElement(name.localpart);
fElementStack.push(new Info(elt, name));
}
}
else {
fragmentContextStackSize_ = 0;
}
fSeenAnything = false;
fSeenDoctype = false;
fSeenRootElement = false;
fSeenRootElementEnd = false;
fSeenHeadElement = false;
fSeenBodyElement = false;
// pass on event
if (fDocumentHandler != null) {
XercesBridge.getInstance().XMLDocumentHandler_startDocument(fDocumentHandler, locator, encoding, nscontext, augs);
}
} // startDocument(XMLLocator,String,Augmentations)
// old methods
/** XML declaration. */
public void xmlDecl(String version, String encoding, String standalone,
Augmentations augs) throws XNIException {
if (!fSeenAnything && fDocumentHandler != null) {
fDocumentHandler.xmlDecl(version, encoding, standalone, augs);
}
} // xmlDecl(String,String,String,Augmentations)
/** Doctype declaration. */
public void doctypeDecl(String rootElementName, String publicId, String systemId,
Augmentations augs) throws XNIException {
fSeenAnything = true;
if (fReportErrors) {
if (fSeenRootElement) {
fErrorReporter.reportError("HTML2010", null);
}
else if (fSeenDoctype) {
fErrorReporter.reportError("HTML2011", null);
}
}
if (!fSeenRootElement && !fSeenDoctype) {
fSeenDoctype = true;
if (fDocumentHandler != null) {
fDocumentHandler.doctypeDecl(rootElementName, publicId, systemId, augs);
}
}
} // doctypeDecl(String,String,String,Augmentations)
/** End document. */
public void endDocument(Augmentations augs) throws XNIException {
// </body> and </html> have been buffered to consider outside content
fIgnoreOutsideContent = true; // endElement should not ignore the elements passed from buffer
consumeBufferedEndElements();
// handle empty document
if (!fSeenRootElement && !fDocumentFragment) {
if (fReportErrors) {
fErrorReporter.reportError("HTML2000", null);
}
if (fDocumentHandler != null) {
fSeenRootElementEnd = false;
forceStartBody(); // will force <html> and <head></head>
final String body = modifyName("body", fNamesElems);
fQName.setValues(null, body, body, null);
callEndElement(fQName, synthesizedAugs());
final String ename = modifyName("html", fNamesElems);
fQName.setValues(null, ename, ename, null);
callEndElement(fQName, synthesizedAugs());
}
}
// pop all remaining elements
else {
int length = fElementStack.top - fragmentContextStackSize_;
for (int i = 0; i < length; i++) {
Info info = fElementStack.pop();
if (fReportErrors) {
String ename = info.qname.rawname;
fErrorReporter.reportWarning("HTML2001", new Object[]{ename});
}
if (fDocumentHandler != null) {
callEndElement(info.qname, synthesizedAugs());
}
}
}
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.endDocument(augs);
}
} // endDocument(Augmentations)
/**
* Consume elements that have been buffered, like </body></html> that are first consumed
* at the end of document
*/
private void consumeBufferedEndElements() {
final List toConsume = new ArrayList(endElementsBuffer_);
endElementsBuffer_.clear();
for (int i=0; i<toConsume.size(); ++i) {
final ElementEntry entry = (ElementEntry) toConsume.get(i);
forcedEndElement_ = true;
endElement(entry.name_, entry.augs_);
}
endElementsBuffer_.clear();
}
/** Comment. */
public void comment(XMLString text, Augmentations augs) throws XNIException {
fSeenAnything = true;
consumeEarlyTextIfNeeded();
if (fDocumentHandler != null) {
fDocumentHandler.comment(text, augs);
}
} // comment(XMLString,Augmentations)
private void consumeEarlyTextIfNeeded() {
if (!lostText_.isEmpty()) {
if (!fSeenBodyElement) {
forceStartBody();
}
lostText_.refeed(this);
}
}
/** Processing instruction. */
public void processingInstruction(String target, XMLString data,
Augmentations augs) throws XNIException {
fSeenAnything = true;
consumeEarlyTextIfNeeded();
if (fDocumentHandler != null) {
fDocumentHandler.processingInstruction(target, data, augs);
}
} // processingInstruction(String,XMLString,Augmentations)
/** Start element. */
public void startElement(final QName elem, XMLAttributes attrs, final Augmentations augs)
throws XNIException {
fSeenAnything = true;
final boolean isForcedCreation = forcedStartElement_;
forcedStartElement_ = false;
// check for end of document
if (fSeenRootElementEnd) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
// get element information
final HTMLElements.Element element = getElement(elem);
final short elementCode = element.code;
// the creation of some elements like TABLE or SELECT can't be forced. Any others?
if (isForcedCreation && (elementCode == HTMLElements.TABLE || elementCode == HTMLElements.SELECT)) {
return; // don't accept creation
}
// ignore multiple html, head, body elements
if (fSeenRootElement && elementCode == HTMLElements.HTML) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
// accept only frame and frameset within frameset
if (fSeenFramesetElement && elementCode != HTMLElements.FRAME && elementCode != HTMLElements.FRAMESET) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
if (elementCode == HTMLElements.HEAD) {
if (fSeenHeadElement) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fSeenHeadElement = true;
}
else if (elementCode == HTMLElements.FRAMESET) {
// create <head></head> if none was present
if (!fSeenHeadElement) {
final QName head = createQName("head");
forceStartElement(head, null, synthesizedAugs());
endElement(head, synthesizedAugs());
}
consumeBufferedEndElements(); // </head> (if any) has been buffered
fSeenFramesetElement = true;
}
else if (elementCode == HTMLElements.BODY) {
// create <head></head> if none was present
if (!fSeenHeadElement) {
final QName head = createQName("head");
forceStartElement(head, null, synthesizedAugs());
endElement(head, synthesizedAugs());
}
consumeBufferedEndElements(); // </head> (if any) has been buffered
if (fSeenBodyElement) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fSeenBodyElement = true;
}
else if (elementCode == HTMLElements.FORM) {
if (fOpenedForm) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fOpenedForm = true;
}
else if (elementCode == HTMLElements.UNKNOWN) {
consumeBufferedEndElements();
}
// check proper parent
if (element.parent != null) {
final HTMLElements.Element preferedParent = element.parent[0];
if (fDocumentFragment && (preferedParent.code == HTMLElements.HEAD || preferedParent.code == HTMLElements.BODY)) {
// nothing, don't force HEAD or BODY creation for a document fragment
}
else if (!fSeenRootElement && !fDocumentFragment) {
String pname = preferedParent.name;
pname = modifyName(pname, fNamesElems);
if (fReportErrors) {
String ename = elem.rawname;
fErrorReporter.reportWarning("HTML2002", new Object[]{ename,pname});
}
final QName qname = new QName(null, pname, pname, null);
final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
if (!parentCreated) {
if (!isForcedCreation) {
notifyDiscardedStartElement(elem, attrs, augs);
}
return;
}
}
else {
if (preferedParent.code != HTMLElements.HEAD || (!fSeenBodyElement && !fDocumentFragment)) {
int depth = getParentDepth(element.parent, element.bounds);
if (depth == -1) { // no parent found
final String pname = modifyName(preferedParent.name, fNamesElems);
final QName qname = new QName(null, pname, pname, null);
if (fReportErrors) {
String ename = elem.rawname;
fErrorReporter.reportWarning("HTML2004", new Object[]{ename,pname});
}
final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
if (!parentCreated) {
if (!isForcedCreation) {
notifyDiscardedStartElement(elem, attrs, augs);
}
return;
}
}
}
}
}
// if block element, save immediate parent inline elements
int depth = 0;
if (element.flags == 0) {
int length = fElementStack.top;
fInlineStack.top = 0;
for (int i = length - 1; i >= 0; i--) {
Info info = fElementStack.data[i];
if (!info.element.isInline()) {
break;
}
fInlineStack.push(info);
endElement(info.qname, synthesizedAugs());
}
depth = fInlineStack.top;
}
// close previous elements
// all elements close a <script>
// in head, no element has children
if ((fElementStack.top > 1
&& (fElementStack.peek().element.code == HTMLElements.SCRIPT))
|| fElementStack.top > 2 && fElementStack.data[fElementStack.top-2].element.code == HTMLElements.HEAD) {
final Info info = fElementStack.pop();
if (fDocumentHandler != null) {
callEndElement(info.qname, synthesizedAugs());
}
}
if (element.closes != null) {
int length = fElementStack.top;
for (int i = length - 1; i >= 0; i--) {
Info info = fElementStack.data[i];
// does it close the element we're looking at?
if (element.closes(info.element.code)) {
if (fReportErrors) {
String ename = elem.rawname;
String iname = info.qname.rawname;
fErrorReporter.reportWarning("HTML2005", new Object[]{ename,iname});
}
for (int j = length - 1; j >= i; j--) {
info = fElementStack.pop();
if (fDocumentHandler != null) {
// PATCH: Marc-Andr� Morissette
callEndElement(info.qname, synthesizedAugs());
}
}
length = i;
continue;
}
// should we stop searching?
if (info.element.isBlock() || element.isParent(info.element)) {
break;
}
}
}
- // TODO: investigate if only table is special here
- // table closes all opened inline elements
- else if (elementCode == HTMLElements.TABLE) {
- for (int i=fElementStack.top-1; i >= 0; i--) {
- final Info info = fElementStack.data[i];
- if (!info.element.isInline()) {
- break;
- }
- endElement(info.qname, synthesizedAugs());
- }
- }
// call handler
fSeenRootElement = true;
if (element != null && element.isEmpty()) {
if (attrs == null) {
attrs = emptyAttributes();
}
if (fDocumentHandler != null) {
fDocumentHandler.emptyElement(elem, attrs, augs);
}
}
else {
boolean inline = element != null && element.isInline();
fElementStack.push(new Info(element, elem, inline ? attrs : null));
if (attrs == null) {
attrs = emptyAttributes();
}
if (fDocumentHandler != null) {
callStartElement(elem, attrs, augs);
}
}
// re-open inline elements
for (int i = 0; i < depth; i++) {
Info info = fInlineStack.pop();
forceStartElement(info.qname, info.attributes, synthesizedAugs());
}
if (elementCode == HTMLElements.BODY) {
lostText_.refeed(this);
}
} // startElement(QName,XMLAttributes,Augmentations)
/**
* Forces an element start, taking care to set the information to allow startElement to "see" that's
* the element has been forced.
* @return <code>true</code> if creation could be done (TABLE's creation for instance can't be forced)
*/
private boolean forceStartElement(final QName elem, XMLAttributes attrs, final Augmentations augs)
throws XNIException {
forcedStartElement_ = true;
startElement(elem, attrs, augs);
return fElementStack.top > 0 && elem.equals(fElementStack.peek().qname);
}
private QName createQName(String tagName) {
tagName = modifyName(tagName, fNamesElems);
return new QName(null, tagName, tagName, NamespaceBinder.XHTML_1_0_URI);
}
/** Empty element. */
public void emptyElement(final QName element, XMLAttributes attrs, Augmentations augs)
throws XNIException {
startElement(element, attrs, augs);
// browser ignore the closing indication for non empty tags like <form .../> but not for unknown element
final HTMLElements.Element elem = getElement(element);
if (elem.isEmpty()
|| fAllowSelfclosingTags
|| elem.code == HTMLElements.UNKNOWN
|| (elem.code == HTMLElements.IFRAME && fAllowSelfclosingIframe)) {
endElement(element, augs);
}
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Start entity. */
public void startGeneralEntity(String name,
XMLResourceIdentifier id,
String encoding,
Augmentations augs) throws XNIException {
fSeenAnything = true;
// check for end of document
if (fSeenRootElementEnd) {
return;
}
// insert body, if needed
if (!fDocumentFragment) {
boolean insertBody = !fSeenRootElement;
if (!insertBody) {
Info info = fElementStack.peek();
if (info.element.code == HTMLElements.HEAD ||
info.element.code == HTMLElements.HTML) {
String hname = modifyName("head", fNamesElems);
String bname = modifyName("body", fNamesElems);
if (fReportErrors) {
fErrorReporter.reportWarning("HTML2009", new Object[]{hname,bname});
}
fQName.setValues(null, hname, hname, null);
endElement(fQName, synthesizedAugs());
insertBody = true;
}
}
if (insertBody) {
forceStartBody();
}
}
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.startGeneralEntity(name, id, encoding, augs);
}
} // startGeneralEntity(String,XMLResourceIdentifier,String,Augmentations)
/**
* Generates a missing <body> (which creates missing <head> when needed)
*/
private void forceStartBody() {
final QName body = createQName("body");
if (fReportErrors) {
fErrorReporter.reportWarning("HTML2006", new Object[]{body.localpart});
}
forceStartElement(body, null, synthesizedAugs());
}
/** Text declaration. */
public void textDecl(String version, String encoding, Augmentations augs)
throws XNIException {
fSeenAnything = true;
// check for end of document
if (fSeenRootElementEnd) {
return;
}
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.textDecl(version, encoding, augs);
}
} // textDecl(String,String,Augmentations)
/** End entity. */
public void endGeneralEntity(String name, Augmentations augs) throws XNIException {
// check for end of document
if (fSeenRootElementEnd) {
return;
}
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.endGeneralEntity(name, augs);
}
} // endGeneralEntity(String,Augmentations)
/** Start CDATA section. */
public void startCDATA(Augmentations augs) throws XNIException {
fSeenAnything = true;
consumeEarlyTextIfNeeded();
// check for end of document
if (fSeenRootElementEnd) {
return;
}
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.startCDATA(augs);
}
} // startCDATA(Augmentations)
/** End CDATA section. */
public void endCDATA(Augmentations augs) throws XNIException {
// check for end of document
if (fSeenRootElementEnd) {
return;
}
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.endCDATA(augs);
}
} // endCDATA(Augmentations)
/** Characters. */
public void characters(final XMLString text, final Augmentations augs) throws XNIException {
// check for end of document
if (fSeenRootElementEnd || fSeenBodyElementEnd) {
return;
}
if (fElementStack.top == 0 && !fDocumentFragment) {
// character before first opening tag
lostText_.add(text, augs);
return;
}
// is this text whitespace?
boolean whitespace = true;
for (int i = 0; i < text.length; i++) {
if (!Character.isWhitespace(text.ch[text.offset + i])) {
whitespace = false;
break;
}
}
if (!fDocumentFragment) {
// handle bare characters
if (!fSeenRootElement) {
if (whitespace) {
return;
}
forceStartBody();
}
if (whitespace && (fElementStack.top < 2 || endElementsBuffer_.size() == 1)) {
// ignore spaces directly within <html>
return;
}
// handle character content in head
// NOTE: This frequently happens when the document looks like:
// <title>Title</title>
// And here's some text.
else if (!whitespace) {
Info info = fElementStack.peek();
if (info.element.code == HTMLElements.HEAD ||
info.element.code == HTMLElements.HTML) {
String hname = modifyName("head", fNamesElems);
String bname = modifyName("body", fNamesElems);
if (fReportErrors) {
fErrorReporter.reportWarning("HTML2009", new Object[]{hname,bname});
}
forceStartBody();
}
}
}
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.characters(text, augs);
}
} // characters(XMLString,Augmentations)
/** Ignorable whitespace. */
public void ignorableWhitespace(XMLString text, Augmentations augs)
throws XNIException {
characters(text, augs);
} // ignorableWhitespace(XMLString,Augmentations)
/** End element. */
public void endElement(final QName element, final Augmentations augs) throws XNIException {
final boolean forcedEndElement = forcedEndElement_;
// is there anything to do?
if (fSeenRootElementEnd) {
notifyDiscardedEndElement(element, augs);
return;
}
// get element information
HTMLElements.Element elem = getElement(element);
// if we consider outside content, just buffer </body> and </html> to consider them at the very end
if (!fIgnoreOutsideContent &&
(elem.code == HTMLElements.BODY || elem.code == HTMLElements.HTML)) {
endElementsBuffer_.add(new ElementEntry(element, augs));
return;
}
// accept only frame and frameset within frameset
if (fSeenFramesetElement && elem.code != HTMLElements.FRAME && elem.code != HTMLElements.FRAMESET) {
notifyDiscardedEndElement(element, augs);
return;
}
// check for end of document
if (elem.code == HTMLElements.HTML) {
fSeenRootElementEnd = true;
}
else if (fIgnoreOutsideContent) {
if (elem.code == HTMLElements.BODY) {
fSeenBodyElementEnd = true;
}
else if (fSeenBodyElementEnd) {
notifyDiscardedEndElement(element, augs);
return;
}
}
else if (elem.code == HTMLElements.FORM) {
fOpenedForm = false;
}
else if (elem.code == HTMLElements.HEAD && !forcedEndElement) {
// consume </head> first when <body> is reached to retrieve content lost between </head> and <body>
endElementsBuffer_.add(new ElementEntry(element, augs));
return;
}
// empty element
int depth = getElementDepth(elem);
if (depth == -1) {
if (elem.code == HTMLElements.P) {
forceStartElement(element, emptyAttributes(), synthesizedAugs());
endElement(element, augs);
}
else if (!elem.isEmpty()) {
notifyDiscardedEndElement(element, augs);
}
return;
}
// find unbalanced inline elements
if (depth > 1 && elem.isInline()) {
final int size = fElementStack.top;
fInlineStack.top = 0;
for (int i = 0; i < depth - 1; i++) {
final Info info = fElementStack.data[size - i - 1];
final HTMLElements.Element pelem = info.element;
if (pelem.isInline() || pelem.code == HTMLElements.FONT) { // TODO: investigate if only FONT
// NOTE: I don't have to make a copy of the info because
// it will just be popped off of the element stack
// as soon as we close it, anyway.
fInlineStack.push(info);
}
}
}
// close children up to appropriate element
for (int i = 0; i < depth; i++) {
Info info = fElementStack.pop();
if (fReportErrors && i < depth - 1) {
String ename = modifyName(element.rawname, fNamesElems);
String iname = info.qname.rawname;
fErrorReporter.reportWarning("HTML2007", new Object[]{ename,iname});
}
if (fDocumentHandler != null) {
// PATCH: Marc-Andr� Morissette
callEndElement(info.qname, i < depth - 1 ? synthesizedAugs() : augs);
}
}
// re-open inline elements
if (depth > 1) {
int size = fInlineStack.top;
for (int i = 0; i < size; i++) {
final Info info = fInlineStack.pop();
XMLAttributes attributes = info.attributes;
if (fReportErrors) {
String iname = info.qname.rawname;
fErrorReporter.reportWarning("HTML2008", new Object[]{iname});
}
forceStartElement(info.qname, attributes, synthesizedAugs());
}
}
} // endElement(QName,Augmentations)
// @since Xerces 2.1.0
/** Sets the document source. */
public void setDocumentSource(XMLDocumentSource source) {
fDocumentSource = source;
} // setDocumentSource(XMLDocumentSource)
/** Returns the document source. */
public XMLDocumentSource getDocumentSource() {
return fDocumentSource;
} // getDocumentSource():XMLDocumentSource
// removed since Xerces-J 2.3.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
startDocument(locator, encoding, null, augs);
} // startDocument(XMLLocator,String,Augmentations)
/** Start prefix mapping. */
public void startPrefixMapping(String prefix, String uri, Augmentations augs)
throws XNIException {
// check for end of document
if (fSeenRootElementEnd) {
return;
}
// call handler
if (fDocumentHandler != null) {
XercesBridge.getInstance().XMLDocumentHandler_startPrefixMapping(fDocumentHandler, prefix, uri, augs);
}
} // startPrefixMapping(String,String,Augmentations)
/** End prefix mapping. */
public void endPrefixMapping(String prefix, Augmentations augs)
throws XNIException {
// check for end of document
if (fSeenRootElementEnd) {
return;
}
// call handler
if (fDocumentHandler != null) {
XercesBridge.getInstance().XMLDocumentHandler_endPrefixMapping(fDocumentHandler, prefix, augs);
}
} // endPrefixMapping(String,Augmentations)
//
// Protected methods
//
/** Returns an HTML element. */
protected HTMLElements.Element getElement(final QName elementName) {
String name = elementName.rawname;
if (fNamespaces && NamespaceBinder.XHTML_1_0_URI.equals(elementName.uri)) {
int index = name.indexOf(':');
if (index != -1) {
name = name.substring(index+1);
}
}
return HTMLElements.getElement(name);
} // getElement(String):HTMLElements.Element
/** Call document handler start element. */
protected final void callStartElement(QName element, XMLAttributes attrs,
Augmentations augs)
throws XNIException {
fDocumentHandler.startElement(element, attrs, augs);
} // callStartElement(QName,XMLAttributes,Augmentations)
/** Call document handler end element. */
protected final void callEndElement(QName element, Augmentations augs)
throws XNIException {
fDocumentHandler.endElement(element, augs);
} // callEndElement(QName,Augmentations)
/**
* Returns the depth of the open tag associated with the specified
* element name or -1 if no matching element is found.
*
* @param element The element.
*/
protected final int getElementDepth(HTMLElements.Element element) {
final boolean container = element.isContainer();
final short elementCode = element.code;
final boolean tableBodyOrHtml = (elementCode == HTMLElements.TABLE)
|| (elementCode == HTMLElements.BODY) || (elementCode == HTMLElements.HTML);
int depth = -1;
for (int i = fElementStack.top - 1; i >=fragmentContextStackSize_; i--) {
Info info = fElementStack.data[i];
if (info.element.code == element.code) {
depth = fElementStack.top - i;
break;
}
if (!container && info.element.isBlock()) {
break;
}
if (info.element.code == HTMLElements.TABLE && !tableBodyOrHtml) {
return -1; // current element not allowed to close a table
}
}
return depth;
} // getElementDepth(HTMLElements.Element)
/**
* Returns the depth of the open tag associated with the specified
* element parent names or -1 if no matching element is found.
*
* @param parents The parent elements.
*/
protected int getParentDepth(HTMLElements.Element[] parents, short bounds) {
if (parents != null) {
for (int i = fElementStack.top - 1; i >= 0; i--) {
Info info = fElementStack.data[i];
if (info.element.code == bounds) {
break;
}
for (int j = 0; j < parents.length; j++) {
if (info.element.code == parents[j].code) {
return fElementStack.top - i;
}
}
}
}
return -1;
} // getParentDepth(HTMLElements.Element[],short):int
/** Returns a set of empty attributes. */
protected final XMLAttributes emptyAttributes() {
fEmptyAttrs.removeAllAttributes();
return fEmptyAttrs;
} // emptyAttributes():XMLAttributes
/** Returns an augmentations object with a synthesized item added. */
protected final Augmentations synthesizedAugs() {
HTMLAugmentations augs = null;
if (fAugmentations) {
augs = fInfosetAugs;
augs.removeAllItems();
augs.putItem(AUGMENTATIONS, SYNTHESIZED_ITEM);
}
return augs;
} // synthesizedAugs():Augmentations
//
// Protected static methods
//
/** Modifies the given name based on the specified mode. */
protected static final String modifyName(String name, short mode) {
switch (mode) {
case NAMES_UPPERCASE: return name.toUpperCase(Locale.ENGLISH);
case NAMES_LOWERCASE: return name.toLowerCase(Locale.ENGLISH);
}
return name;
} // modifyName(String,short):String
/**
* Converts HTML names string value to constant value.
*
* @see #NAMES_NO_CHANGE
* @see #NAMES_LOWERCASE
* @see #NAMES_UPPERCASE
*/
protected static final short getNamesValue(String value) {
if (value.equals("lower")) {
return NAMES_LOWERCASE;
}
if (value.equals("upper")) {
return NAMES_UPPERCASE;
}
return NAMES_NO_CHANGE;
} // getNamesValue(String):short
//
// Classes
//
/**
* Element info for each start element. This information is used when
* closing unbalanced inline elements. For example:
* <pre>
* <i>unbalanced <b>HTML</i> content</b>
* </pre>
* <p>
* It seems that it is a waste of processing and memory to copy the
* attributes for every start element even if there are no unbalanced
* inline elements in the document. However, if the attributes are
* <em>not</em> saved, then important attributes such as style
* information would be lost.
*
* @author Andy Clark
*/
public static class Info {
//
// Data
//
/** The element. */
public HTMLElements.Element element;
/** The element qualified name. */
public QName qname;
/** The element attributes. */
public XMLAttributes attributes;
//
// Constructors
//
/**
* Creates an element information object.
* <p>
* <strong>Note:</strong>
* This constructor makes a copy of the element information.
*
* @param element The element qualified name.
*/
public Info(HTMLElements.Element element, QName qname) {
this(element, qname, null);
} // <init>(HTMLElements.Element,QName)
/**
* Creates an element information object.
* <p>
* <strong>Note:</strong>
* This constructor makes a copy of the element information.
*
* @param element The element qualified name.
* @param attributes The element attributes.
*/
public Info(HTMLElements.Element element,
QName qname, XMLAttributes attributes) {
this.element = element;
this.qname = new QName(qname);
if (attributes != null) {
int length = attributes.getLength();
if (length > 0) {
QName aqname = new QName();
XMLAttributes newattrs = new XMLAttributesImpl();
for (int i = 0; i < length; i++) {
attributes.getName(i, aqname);
String type = attributes.getType(i);
String value = attributes.getValue(i);
String nonNormalizedValue = attributes.getNonNormalizedValue(i);
boolean specified = attributes.isSpecified(i);
newattrs.addAttribute(aqname, type, value);
newattrs.setNonNormalizedValue(i, nonNormalizedValue);
newattrs.setSpecified(i, specified);
}
this.attributes = newattrs;
}
}
} // <init>(HTMLElements.Element,QName,XMLAttributes)
/**
* Simple representation to make debugging easier
*/
public String toString() {
return super.toString() + qname;
}
} // class Info
/** Unsynchronized stack of element information. */
public static class InfoStack {
//
// Data
//
/** The top of the stack. */
public int top;
/** The stack data. */
public Info[] data = new Info[10];
//
// Public methods
//
/** Pushes element information onto the stack. */
public void push(Info info) {
if (top == data.length) {
Info[] newarray = new Info[top + 10];
System.arraycopy(data, 0, newarray, 0, top);
data = newarray;
}
data[top++] = info;
} // push(Info)
/** Peeks at the top of the stack. */
public Info peek() {
return data[top-1];
} // peek():Info
/** Pops the top item off of the stack. */
public Info pop() {
return data[--top];
} // pop():Info
/**
* Simple representation to make debugging easier
*/
public String toString() {
final StringBuffer sb = new StringBuffer("InfoStack(");
for (int i=top-1; i>=0; --i) {
sb.append(data[i]);
if (i != 0)
sb.append(", ");
}
sb.append(")");
return sb.toString();
}
} // class InfoStack
void setTagBalancingListener(final HTMLTagBalancingListener tagBalancingListener) {
this.tagBalancingListener = tagBalancingListener;
}
/**
* Notifies the tagBalancingListener (if any) of an ignored start element
*/
private void notifyDiscardedStartElement(final QName elem, final XMLAttributes attrs,
final Augmentations augs) {
if (tagBalancingListener != null)
tagBalancingListener.ignoredStartElement(elem, attrs, augs);
}
/**
* Notifies the tagBalancingListener (if any) of an ignored end element
*/
private void notifyDiscardedEndElement(final QName element, final Augmentations augs) {
if (tagBalancingListener != null)
tagBalancingListener.ignoredEndElement(element, augs);
}
/**
* Structure to hold information about an element placed in buffer to be comsumed later
*/
static class ElementEntry {
private final QName name_;
private final Augmentations augs_;
ElementEntry(final QName element, final Augmentations augs) {
name_ = new QName(element);
augs_ = (augs == null) ? null : new HTMLAugmentations(augs);
}
}
} // class HTMLTagBalancer
| true | true | public void startElement(final QName elem, XMLAttributes attrs, final Augmentations augs)
throws XNIException {
fSeenAnything = true;
final boolean isForcedCreation = forcedStartElement_;
forcedStartElement_ = false;
// check for end of document
if (fSeenRootElementEnd) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
// get element information
final HTMLElements.Element element = getElement(elem);
final short elementCode = element.code;
// the creation of some elements like TABLE or SELECT can't be forced. Any others?
if (isForcedCreation && (elementCode == HTMLElements.TABLE || elementCode == HTMLElements.SELECT)) {
return; // don't accept creation
}
// ignore multiple html, head, body elements
if (fSeenRootElement && elementCode == HTMLElements.HTML) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
// accept only frame and frameset within frameset
if (fSeenFramesetElement && elementCode != HTMLElements.FRAME && elementCode != HTMLElements.FRAMESET) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
if (elementCode == HTMLElements.HEAD) {
if (fSeenHeadElement) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fSeenHeadElement = true;
}
else if (elementCode == HTMLElements.FRAMESET) {
// create <head></head> if none was present
if (!fSeenHeadElement) {
final QName head = createQName("head");
forceStartElement(head, null, synthesizedAugs());
endElement(head, synthesizedAugs());
}
consumeBufferedEndElements(); // </head> (if any) has been buffered
fSeenFramesetElement = true;
}
else if (elementCode == HTMLElements.BODY) {
// create <head></head> if none was present
if (!fSeenHeadElement) {
final QName head = createQName("head");
forceStartElement(head, null, synthesizedAugs());
endElement(head, synthesizedAugs());
}
consumeBufferedEndElements(); // </head> (if any) has been buffered
if (fSeenBodyElement) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fSeenBodyElement = true;
}
else if (elementCode == HTMLElements.FORM) {
if (fOpenedForm) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fOpenedForm = true;
}
else if (elementCode == HTMLElements.UNKNOWN) {
consumeBufferedEndElements();
}
// check proper parent
if (element.parent != null) {
final HTMLElements.Element preferedParent = element.parent[0];
if (fDocumentFragment && (preferedParent.code == HTMLElements.HEAD || preferedParent.code == HTMLElements.BODY)) {
// nothing, don't force HEAD or BODY creation for a document fragment
}
else if (!fSeenRootElement && !fDocumentFragment) {
String pname = preferedParent.name;
pname = modifyName(pname, fNamesElems);
if (fReportErrors) {
String ename = elem.rawname;
fErrorReporter.reportWarning("HTML2002", new Object[]{ename,pname});
}
final QName qname = new QName(null, pname, pname, null);
final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
if (!parentCreated) {
if (!isForcedCreation) {
notifyDiscardedStartElement(elem, attrs, augs);
}
return;
}
}
else {
if (preferedParent.code != HTMLElements.HEAD || (!fSeenBodyElement && !fDocumentFragment)) {
int depth = getParentDepth(element.parent, element.bounds);
if (depth == -1) { // no parent found
final String pname = modifyName(preferedParent.name, fNamesElems);
final QName qname = new QName(null, pname, pname, null);
if (fReportErrors) {
String ename = elem.rawname;
fErrorReporter.reportWarning("HTML2004", new Object[]{ename,pname});
}
final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
if (!parentCreated) {
if (!isForcedCreation) {
notifyDiscardedStartElement(elem, attrs, augs);
}
return;
}
}
}
}
}
// if block element, save immediate parent inline elements
int depth = 0;
if (element.flags == 0) {
int length = fElementStack.top;
fInlineStack.top = 0;
for (int i = length - 1; i >= 0; i--) {
Info info = fElementStack.data[i];
if (!info.element.isInline()) {
break;
}
fInlineStack.push(info);
endElement(info.qname, synthesizedAugs());
}
depth = fInlineStack.top;
}
// close previous elements
// all elements close a <script>
// in head, no element has children
if ((fElementStack.top > 1
&& (fElementStack.peek().element.code == HTMLElements.SCRIPT))
|| fElementStack.top > 2 && fElementStack.data[fElementStack.top-2].element.code == HTMLElements.HEAD) {
final Info info = fElementStack.pop();
if (fDocumentHandler != null) {
callEndElement(info.qname, synthesizedAugs());
}
}
if (element.closes != null) {
int length = fElementStack.top;
for (int i = length - 1; i >= 0; i--) {
Info info = fElementStack.data[i];
// does it close the element we're looking at?
if (element.closes(info.element.code)) {
if (fReportErrors) {
String ename = elem.rawname;
String iname = info.qname.rawname;
fErrorReporter.reportWarning("HTML2005", new Object[]{ename,iname});
}
for (int j = length - 1; j >= i; j--) {
info = fElementStack.pop();
if (fDocumentHandler != null) {
// PATCH: Marc-Andr� Morissette
callEndElement(info.qname, synthesizedAugs());
}
}
length = i;
continue;
}
// should we stop searching?
if (info.element.isBlock() || element.isParent(info.element)) {
break;
}
}
}
// TODO: investigate if only table is special here
// table closes all opened inline elements
else if (elementCode == HTMLElements.TABLE) {
for (int i=fElementStack.top-1; i >= 0; i--) {
final Info info = fElementStack.data[i];
if (!info.element.isInline()) {
break;
}
endElement(info.qname, synthesizedAugs());
}
}
// call handler
fSeenRootElement = true;
if (element != null && element.isEmpty()) {
if (attrs == null) {
attrs = emptyAttributes();
}
if (fDocumentHandler != null) {
fDocumentHandler.emptyElement(elem, attrs, augs);
}
}
else {
boolean inline = element != null && element.isInline();
fElementStack.push(new Info(element, elem, inline ? attrs : null));
if (attrs == null) {
attrs = emptyAttributes();
}
if (fDocumentHandler != null) {
callStartElement(elem, attrs, augs);
}
}
// re-open inline elements
for (int i = 0; i < depth; i++) {
Info info = fInlineStack.pop();
forceStartElement(info.qname, info.attributes, synthesizedAugs());
}
if (elementCode == HTMLElements.BODY) {
lostText_.refeed(this);
}
} // startElement(QName,XMLAttributes,Augmentations)
| public void startElement(final QName elem, XMLAttributes attrs, final Augmentations augs)
throws XNIException {
fSeenAnything = true;
final boolean isForcedCreation = forcedStartElement_;
forcedStartElement_ = false;
// check for end of document
if (fSeenRootElementEnd) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
// get element information
final HTMLElements.Element element = getElement(elem);
final short elementCode = element.code;
// the creation of some elements like TABLE or SELECT can't be forced. Any others?
if (isForcedCreation && (elementCode == HTMLElements.TABLE || elementCode == HTMLElements.SELECT)) {
return; // don't accept creation
}
// ignore multiple html, head, body elements
if (fSeenRootElement && elementCode == HTMLElements.HTML) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
// accept only frame and frameset within frameset
if (fSeenFramesetElement && elementCode != HTMLElements.FRAME && elementCode != HTMLElements.FRAMESET) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
if (elementCode == HTMLElements.HEAD) {
if (fSeenHeadElement) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fSeenHeadElement = true;
}
else if (elementCode == HTMLElements.FRAMESET) {
// create <head></head> if none was present
if (!fSeenHeadElement) {
final QName head = createQName("head");
forceStartElement(head, null, synthesizedAugs());
endElement(head, synthesizedAugs());
}
consumeBufferedEndElements(); // </head> (if any) has been buffered
fSeenFramesetElement = true;
}
else if (elementCode == HTMLElements.BODY) {
// create <head></head> if none was present
if (!fSeenHeadElement) {
final QName head = createQName("head");
forceStartElement(head, null, synthesizedAugs());
endElement(head, synthesizedAugs());
}
consumeBufferedEndElements(); // </head> (if any) has been buffered
if (fSeenBodyElement) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fSeenBodyElement = true;
}
else if (elementCode == HTMLElements.FORM) {
if (fOpenedForm) {
notifyDiscardedStartElement(elem, attrs, augs);
return;
}
fOpenedForm = true;
}
else if (elementCode == HTMLElements.UNKNOWN) {
consumeBufferedEndElements();
}
// check proper parent
if (element.parent != null) {
final HTMLElements.Element preferedParent = element.parent[0];
if (fDocumentFragment && (preferedParent.code == HTMLElements.HEAD || preferedParent.code == HTMLElements.BODY)) {
// nothing, don't force HEAD or BODY creation for a document fragment
}
else if (!fSeenRootElement && !fDocumentFragment) {
String pname = preferedParent.name;
pname = modifyName(pname, fNamesElems);
if (fReportErrors) {
String ename = elem.rawname;
fErrorReporter.reportWarning("HTML2002", new Object[]{ename,pname});
}
final QName qname = new QName(null, pname, pname, null);
final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
if (!parentCreated) {
if (!isForcedCreation) {
notifyDiscardedStartElement(elem, attrs, augs);
}
return;
}
}
else {
if (preferedParent.code != HTMLElements.HEAD || (!fSeenBodyElement && !fDocumentFragment)) {
int depth = getParentDepth(element.parent, element.bounds);
if (depth == -1) { // no parent found
final String pname = modifyName(preferedParent.name, fNamesElems);
final QName qname = new QName(null, pname, pname, null);
if (fReportErrors) {
String ename = elem.rawname;
fErrorReporter.reportWarning("HTML2004", new Object[]{ename,pname});
}
final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
if (!parentCreated) {
if (!isForcedCreation) {
notifyDiscardedStartElement(elem, attrs, augs);
}
return;
}
}
}
}
}
// if block element, save immediate parent inline elements
int depth = 0;
if (element.flags == 0) {
int length = fElementStack.top;
fInlineStack.top = 0;
for (int i = length - 1; i >= 0; i--) {
Info info = fElementStack.data[i];
if (!info.element.isInline()) {
break;
}
fInlineStack.push(info);
endElement(info.qname, synthesizedAugs());
}
depth = fInlineStack.top;
}
// close previous elements
// all elements close a <script>
// in head, no element has children
if ((fElementStack.top > 1
&& (fElementStack.peek().element.code == HTMLElements.SCRIPT))
|| fElementStack.top > 2 && fElementStack.data[fElementStack.top-2].element.code == HTMLElements.HEAD) {
final Info info = fElementStack.pop();
if (fDocumentHandler != null) {
callEndElement(info.qname, synthesizedAugs());
}
}
if (element.closes != null) {
int length = fElementStack.top;
for (int i = length - 1; i >= 0; i--) {
Info info = fElementStack.data[i];
// does it close the element we're looking at?
if (element.closes(info.element.code)) {
if (fReportErrors) {
String ename = elem.rawname;
String iname = info.qname.rawname;
fErrorReporter.reportWarning("HTML2005", new Object[]{ename,iname});
}
for (int j = length - 1; j >= i; j--) {
info = fElementStack.pop();
if (fDocumentHandler != null) {
// PATCH: Marc-Andr� Morissette
callEndElement(info.qname, synthesizedAugs());
}
}
length = i;
continue;
}
// should we stop searching?
if (info.element.isBlock() || element.isParent(info.element)) {
break;
}
}
}
// call handler
fSeenRootElement = true;
if (element != null && element.isEmpty()) {
if (attrs == null) {
attrs = emptyAttributes();
}
if (fDocumentHandler != null) {
fDocumentHandler.emptyElement(elem, attrs, augs);
}
}
else {
boolean inline = element != null && element.isInline();
fElementStack.push(new Info(element, elem, inline ? attrs : null));
if (attrs == null) {
attrs = emptyAttributes();
}
if (fDocumentHandler != null) {
callStartElement(elem, attrs, augs);
}
}
// re-open inline elements
for (int i = 0; i < depth; i++) {
Info info = fInlineStack.pop();
forceStartElement(info.qname, info.attributes, synthesizedAugs());
}
if (elementCode == HTMLElements.BODY) {
lostText_.refeed(this);
}
} // startElement(QName,XMLAttributes,Augmentations)
|
diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java
index 4219475fa..9d1b1a128 100644
--- a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java
+++ b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java
@@ -1,465 +1,464 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.graphics.g2d;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import static com.badlogic.gdx.graphics.Texture.TextureWrap.*;
/**
* Loads images from texture atlases created by TexturePacker.<br>
* <br>
* A TextureAtlas must be disposed to free up the resources consumed by the backing textures.
* @author Nathan Sweet
*/
public class TextureAtlas implements Disposable {
static private final String[] tuple = new String[2];
private final HashSet<Texture> textures = new HashSet(4);
private final ArrayList<AtlasRegion> regions;
/**
* Creates an empty atlas to which regions can be added.
*/
public TextureAtlas () {
regions = new ArrayList();
}
/**
* Loads the specified pack file, using the parent directory of the pack file to find the page images.
*/
public TextureAtlas (FileHandle packFile) {
this(packFile, packFile.parent());
}
/**
* @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner.
* @see #TextureAtlas(FileHandle)
*/
public TextureAtlas (FileHandle packFile, boolean flip) {
this(packFile, packFile.parent(), flip);
}
public TextureAtlas (FileHandle packFile, FileHandle imagesDir) {
this(packFile, imagesDir, false);
}
/**
* @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner.
*/
public TextureAtlas (FileHandle packFile, FileHandle imagesDir, boolean flip) {
PriorityQueue<AtlasRegion> sortedRegions = new PriorityQueue(16, indexComparator);
BufferedReader reader = new BufferedReader(new InputStreamReader(packFile.read()), 64);
try {
Texture pageImage = null;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.trim().length() == 0)
pageImage = null;
else if (pageImage == null) {
FileHandle file = imagesDir.child(line);
- // FIXME - Actually load in the requested format.
Format format = Format.valueOf(readValue(reader));
readTuple(reader);
TextureFilter min = TextureFilter.valueOf(tuple[0]);
TextureFilter max = TextureFilter.valueOf(tuple[1]);
String direction = readValue(reader);
TextureWrap repeatX = ClampToEdge;
TextureWrap repeatY = ClampToEdge;
if (direction.equals("x"))
repeatX = Repeat;
else if (direction.equals("y"))
repeatY = Repeat;
else if (direction.equals("xy")) {
repeatX = Repeat;
repeatY = Repeat;
}
- pageImage = new Texture(file, TextureFilter.isMipMap(min) || TextureFilter.isMipMap(max) ? true : false);
+ pageImage = new Texture(file, format, TextureFilter.isMipMap(min) || TextureFilter.isMipMap(max) ? true : false);
pageImage.setFilter(min, max);
pageImage.setWrap(repeatX, repeatY);
textures.add(pageImage);
} else {
boolean rotate = Boolean.valueOf(readValue(reader));
readTuple(reader);
int left = Integer.parseInt(tuple[0]);
int top = Integer.parseInt(tuple[1]);
readTuple(reader);
int width = Integer.parseInt(tuple[0]);
int height = Integer.parseInt(tuple[1]);
AtlasRegion region = new AtlasRegion(pageImage, left, top, width, height);
region.name = line;
region.rotate = rotate;
readTuple(reader);
region.originalWidth = Integer.parseInt(tuple[0]);
region.originalHeight = Integer.parseInt(tuple[1]);
readTuple(reader);
region.offsetX = Integer.parseInt(tuple[0]);
region.offsetY = Integer.parseInt(tuple[1]);
region.index = Integer.parseInt(readValue(reader));
if (flip) region.flip(false, true);
sortedRegions.add(region);
}
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error reading pack file: " + packFile);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
int n = sortedRegions.size();
regions = new ArrayList(n);
for (int i = 0; i < n; i++)
regions.add(sortedRegions.poll());
}
/**
* Adds a region to the atlas. The specified texture will be disposed when the atlas is disposed.
*/
public AtlasRegion addRegion (String name, Texture texture, int x, int y, int width, int height) {
textures.add(texture);
AtlasRegion region = new AtlasRegion(texture, x, y, width, height);
region.name = name;
region.originalWidth = width;
region.originalHeight = height;
region.index = -1;
regions.add(region);
return region;
}
/**
* Adds a region to the atlas. The texture for the specified region will be disposed when the atlas is disposed.
*/
public AtlasRegion addRegion (String name, TextureRegion textureRegion) {
return addRegion(name, textureRegion.texture, textureRegion.getRegionX(), textureRegion.getRegionY(),
textureRegion.getRegionWidth(), textureRegion.getRegionHeight());
}
/**
* Returns all regions in the atlas.
*/
public List<AtlasRegion> getRegions () {
return regions;
}
/**
* Returns the first region found with the specified name. This method uses string comparison to find the region, so the result
* should be cached rather than calling this method multiple times.
* @return The region, or null.
*/
public AtlasRegion findRegion (String name) {
for (int i = 0, n = regions.size(); i < n; i++)
if (regions.get(i).name.equals(name)) return regions.get(i);
return null;
}
/**
* Returns the first region found with the specified name and index. This method uses string comparison to find the region, so
* the result should be cached rather than calling this method multiple times.
* @return The region, or null.
*/
public AtlasRegion findRegion (String name, int index) {
for (int i = 0, n = regions.size(); i < n; i++) {
AtlasRegion region = regions.get(i);
if (!region.name.equals(name)) continue;
if (region.index != index) continue;
return region;
}
return null;
}
/**
* Returns all regions with the specified name, ordered by smallest to largest {@link AtlasRegion#index index}. This method
* uses string comparison to find the regions, so the result should be cached rather than calling this method multiple times.
*/
public List<AtlasRegion> findRegions (String name) {
ArrayList<AtlasRegion> matched = new ArrayList();
for (int i = 0, n = regions.size(); i < n; i++) {
AtlasRegion region = regions.get(i);
if (region.name.equals(name)) matched.add(new AtlasRegion(region));
}
return matched;
}
/**
* Returns all regions in the atlas as sprites. This method creates a new sprite for each region, so the result should be
* stored rather than calling this method multiple times.
* @see #createSprite(String)
*/
public List<Sprite> createSprites () {
ArrayList sprites = new ArrayList(regions.size());
for (int i = 0, n = regions.size(); i < n; i++)
sprites.add(newSprite(regions.get(i)));
return sprites;
}
/**
* Returns the first region found with the specified name as a sprite. If whitespace was stripped from the region when it was
* packed, the sprite is automatically positioned as if whitespace had not been stripped. This method uses string comparison to
* find the region and constructs a new sprite, so the result should be cached rather than calling this method multiple times.
* @return The sprite, or null.
*/
public Sprite createSprite (String name) {
for (int i = 0, n = regions.size(); i < n; i++)
if (regions.get(i).name.equals(name)) return newSprite(regions.get(i));
return null;
}
/**
* Returns the first region found with the specified name and index as a sprite. This method uses string comparison to find the
* region and constructs a new sprite, so the result should be cached rather than calling this method multiple times.
* @return The sprite, or null.
* @see #createSprite(String)
*/
public Sprite createSprite (String name, int index) {
for (int i = 0, n = regions.size(); i < n; i++) {
AtlasRegion region = regions.get(i);
if (!region.name.equals(name)) continue;
if (region.index != index) continue;
return newSprite(regions.get(i));
}
return null;
}
/**
* Returns all regions with the specified name as sprites, ordered by smallest to largest {@link AtlasRegion#index index}. This
* method uses string comparison to find the regions and constructs new sprites, so the result should be cached rather than
* calling this method multiple times.
* @see #createSprite(String)
*/
public List<Sprite> createSprites (String name) {
ArrayList<Sprite> matched = new ArrayList();
for (int i = 0, n = regions.size(); i < n; i++) {
AtlasRegion region = regions.get(i);
if (region.name.equals(name)) matched.add(newSprite(region));
}
return matched;
}
private Sprite newSprite (AtlasRegion region) {
if (region.packedWidth == region.originalWidth && region.packedHeight == region.originalHeight) {
Sprite sprite = new Sprite(region);
if (region.rotate) sprite.rotate90(true);
return sprite;
}
return new AtlasSprite(region);
}
/**
* Releases all resources associated with this TextureAtlas instance. This releases all the textures backing all TextureRegions
* and Sprites, which should no longer be used after calling dispose.
*/
public void dispose () {
for (Texture texture : textures)
texture.dispose();
textures.clear();
}
static private final Comparator<AtlasRegion> indexComparator = new Comparator<AtlasRegion>() {
public int compare (AtlasRegion region1, AtlasRegion region2) {
int i1 = region1.index;
if (i1 == -1) i1 = Integer.MAX_VALUE;
int i2 = region2.index;
if (i2 == -1) i2 = Integer.MAX_VALUE;
return i1 - i2;
}
};
static private String readValue (BufferedReader reader) throws IOException {
String line = reader.readLine();
int colon = line.indexOf(':');
if (colon == -1) throw new GdxRuntimeException("Invalid line: " + line);
return line.substring(colon + 1).trim();
}
static private void readTuple (BufferedReader reader) throws IOException {
String line = reader.readLine();
int colon = line.indexOf(':');
int comma = line.indexOf(',');
if (colon == -1 || comma == -1 || comma < colon + 1) throw new GdxRuntimeException("Invalid line: " + line);
tuple[0] = line.substring(colon + 1, comma).trim();
tuple[1] = line.substring(comma + 1).trim();
}
/**
* Describes the region of a packed image and provides information about the original image before it was packed.
*/
static public class AtlasRegion extends TextureRegion {
/**
* The number at the end of the original image file name, or -1 if none.<br>
* <br>
* When sprites are packed, if the original file name ends with a number, it is stored as the index and is not considered as
* part of the sprite's name. This is useful for keeping animation frames in order.
* @see TextureAtlas#findRegions(String)
*/
public int index;
/**
* The name of the original image file, up to the first underscore. Underscores denote special instructions to the texture
* packer.
*/
public String name;
/**
* The offset from the left of the original image to the left of the packed image, after whitespace was removed for packing.
*/
public float offsetX;
/**
* The offset from the bottom of the original image to the bottom of the packed image, after whitespace was removed for
* packing.
*/
public float offsetY;
/**
* The width of the image, after whitespace was removed for packing.
*/
public int packedWidth;
/**
* The height of the image, after whitespace was removed for packing.
*/
public int packedHeight;
/**
* The width of the image, before whitespace was removed for packing.
*/
public int originalWidth;
/**
* The height of the image, before whitespace was removed for packing.
*/
public int originalHeight;
/**
* If true, the region has been rotated 90 degrees counter clockwise.
*/
public boolean rotate;
public AtlasRegion (Texture texture, int x, int y, int width, int height) {
super(texture, x, y, width, height);
packedWidth = width;
packedHeight = height;
}
public AtlasRegion (AtlasRegion region) {
setRegion(region);
index = region.index;
name = region.name;
offsetX = region.offsetX;
offsetY = region.offsetY;
packedWidth = region.packedWidth;
packedHeight = region.packedHeight;
originalWidth = region.originalWidth;
originalHeight = region.originalHeight;
}
/**
* Flips the region, adjusting the offset so the image appears to be flipped as if no whitespace has been removed for
* packing.
*/
public void flip (boolean x, boolean y) {
super.flip(x, y);
if (x) offsetX = originalWidth - offsetX - packedWidth;
if (y) offsetY = originalHeight - offsetY - packedHeight;
}
}
/**
* A sprite that, if whitespace was stripped from the region when it was packed, is automatically positioned as if whitespace
* had not been stripped.
*/
static public class AtlasSprite extends Sprite {
final AtlasRegion region;
public AtlasSprite (AtlasRegion region) {
this.region = new AtlasRegion(region);
setRegion(region);
if (region.rotate) rotate90(true);
setOrigin(region.originalWidth / 2, region.originalHeight / 2);
super.setBounds(region.offsetX, region.offsetY, Math.abs(region.getRegionWidth()), Math.abs(region.getRegionHeight()));
setColor(1, 1, 1, 1);
}
public void setPosition (float x, float y) {
super.setPosition(x + region.offsetX, y + region.offsetY);
}
public void setBounds (float x, float y, float width, float height) {
super.setBounds(x + region.offsetX, y + region.offsetY, width, height);
}
public void setOrigin (float originX, float originY) {
super.setOrigin(originX + region.offsetX, originY + region.offsetY);
}
public void flip (boolean x, boolean y) {
// Flip texture.
super.flip(x, y);
float oldOffsetX = region.offsetX;
float oldOffsetY = region.offsetY;
// Update x and y offsets.
region.flip(x, y);
// Update position with new offsets.
translate(region.offsetX - oldOffsetX, region.offsetY - oldOffsetY);
}
public float getX () {
return super.getX() - region.offsetX;
}
public float getY () {
return super.getY() - region.offsetY;
}
public AtlasRegion getAtlasRegion () {
return region;
}
}
}
| false | true | public TextureAtlas (FileHandle packFile, FileHandle imagesDir, boolean flip) {
PriorityQueue<AtlasRegion> sortedRegions = new PriorityQueue(16, indexComparator);
BufferedReader reader = new BufferedReader(new InputStreamReader(packFile.read()), 64);
try {
Texture pageImage = null;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.trim().length() == 0)
pageImage = null;
else if (pageImage == null) {
FileHandle file = imagesDir.child(line);
// FIXME - Actually load in the requested format.
Format format = Format.valueOf(readValue(reader));
readTuple(reader);
TextureFilter min = TextureFilter.valueOf(tuple[0]);
TextureFilter max = TextureFilter.valueOf(tuple[1]);
String direction = readValue(reader);
TextureWrap repeatX = ClampToEdge;
TextureWrap repeatY = ClampToEdge;
if (direction.equals("x"))
repeatX = Repeat;
else if (direction.equals("y"))
repeatY = Repeat;
else if (direction.equals("xy")) {
repeatX = Repeat;
repeatY = Repeat;
}
pageImage = new Texture(file, TextureFilter.isMipMap(min) || TextureFilter.isMipMap(max) ? true : false);
pageImage.setFilter(min, max);
pageImage.setWrap(repeatX, repeatY);
textures.add(pageImage);
} else {
boolean rotate = Boolean.valueOf(readValue(reader));
readTuple(reader);
int left = Integer.parseInt(tuple[0]);
int top = Integer.parseInt(tuple[1]);
readTuple(reader);
int width = Integer.parseInt(tuple[0]);
int height = Integer.parseInt(tuple[1]);
AtlasRegion region = new AtlasRegion(pageImage, left, top, width, height);
region.name = line;
region.rotate = rotate;
readTuple(reader);
region.originalWidth = Integer.parseInt(tuple[0]);
region.originalHeight = Integer.parseInt(tuple[1]);
readTuple(reader);
region.offsetX = Integer.parseInt(tuple[0]);
region.offsetY = Integer.parseInt(tuple[1]);
region.index = Integer.parseInt(readValue(reader));
if (flip) region.flip(false, true);
sortedRegions.add(region);
}
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error reading pack file: " + packFile);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
int n = sortedRegions.size();
regions = new ArrayList(n);
for (int i = 0; i < n; i++)
regions.add(sortedRegions.poll());
}
| public TextureAtlas (FileHandle packFile, FileHandle imagesDir, boolean flip) {
PriorityQueue<AtlasRegion> sortedRegions = new PriorityQueue(16, indexComparator);
BufferedReader reader = new BufferedReader(new InputStreamReader(packFile.read()), 64);
try {
Texture pageImage = null;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.trim().length() == 0)
pageImage = null;
else if (pageImage == null) {
FileHandle file = imagesDir.child(line);
Format format = Format.valueOf(readValue(reader));
readTuple(reader);
TextureFilter min = TextureFilter.valueOf(tuple[0]);
TextureFilter max = TextureFilter.valueOf(tuple[1]);
String direction = readValue(reader);
TextureWrap repeatX = ClampToEdge;
TextureWrap repeatY = ClampToEdge;
if (direction.equals("x"))
repeatX = Repeat;
else if (direction.equals("y"))
repeatY = Repeat;
else if (direction.equals("xy")) {
repeatX = Repeat;
repeatY = Repeat;
}
pageImage = new Texture(file, format, TextureFilter.isMipMap(min) || TextureFilter.isMipMap(max) ? true : false);
pageImage.setFilter(min, max);
pageImage.setWrap(repeatX, repeatY);
textures.add(pageImage);
} else {
boolean rotate = Boolean.valueOf(readValue(reader));
readTuple(reader);
int left = Integer.parseInt(tuple[0]);
int top = Integer.parseInt(tuple[1]);
readTuple(reader);
int width = Integer.parseInt(tuple[0]);
int height = Integer.parseInt(tuple[1]);
AtlasRegion region = new AtlasRegion(pageImage, left, top, width, height);
region.name = line;
region.rotate = rotate;
readTuple(reader);
region.originalWidth = Integer.parseInt(tuple[0]);
region.originalHeight = Integer.parseInt(tuple[1]);
readTuple(reader);
region.offsetX = Integer.parseInt(tuple[0]);
region.offsetY = Integer.parseInt(tuple[1]);
region.index = Integer.parseInt(readValue(reader));
if (flip) region.flip(false, true);
sortedRegions.add(region);
}
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error reading pack file: " + packFile);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
int n = sortedRegions.size();
regions = new ArrayList(n);
for (int i = 0; i < n; i++)
regions.add(sortedRegions.poll());
}
|
diff --git a/ListaOnlineXP/exerciselist/java/JavaTester.java b/ListaOnlineXP/exerciselist/java/JavaTester.java
index 0f580eb..2c6e568 100644
--- a/ListaOnlineXP/exerciselist/java/JavaTester.java
+++ b/ListaOnlineXP/exerciselist/java/JavaTester.java
@@ -1,195 +1,195 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class JavaTester {
private String path;
public JavaTester() {
this.path = "";
}
public void setPath(String path) {
this.path = path;
}
public static void main(String[] args) {
String codigo_filename = args[0];
String criterio_filename = args[1];
String sandbox_path = args[2];
String codigo = "";
String criterio = "";
try {
BufferedReader codigo_buffer = new BufferedReader(new FileReader(codigo_filename));
String codigo_line;
while((codigo_line = codigo_buffer.readLine()) != null) {
codigo += codigo_line;
}
codigo_buffer.close();
} catch(IOException e) {
System.out.println("SYSTEM_ERROR!:!Falha ao abrir arquivo de código.");
}
try {
BufferedReader criterio_buffer = new BufferedReader(new FileReader(criterio_filename));
String criterio_line;
while((criterio_line = criterio_buffer.readLine()) != null) {
criterio += criterio_line;
}
criterio_buffer.close();
} catch(IOException e) {
System.out.println("SYSTEM_ERROR!:!Falha ao abrir arquivo de critério.");
}
try {
JavaTester javaTester = new JavaTester();
javaTester.setPath(sandbox_path);
System.out.println(javaTester.executeTest(codigo,criterio));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public synchronized String executeTest(String codigo, String criterio) throws Exception {
// Path
if (!(new File(path).exists())) throw new Exception("SYSTEM_ERROR!:!Diretório de execução não encontrado.");
// ----- Gera o arquivo do aluno ------
// descobre o nome da classe
int pos = codigo.indexOf("class ");
if (pos == -1) return "CODE_ERROR!:!Não há classe definida.";
pos = pos + "class ".length();
while (pos < codigo.length() && codigo.charAt(pos) == ' ') pos++;
int posFim = pos;
while (posFim < codigo.length() &&
(Character.isLetterOrDigit(codigo.charAt(posFim)) || codigo.charAt(posFim) == '_')) posFim++;
if (posFim == pos) return "CODE_ERROR!:!Não há classe definida.";
String nomeClasse = codigo.substring(pos, posFim);
// Compila
File toDelete;
toDelete = new File (path+nomeClasse + ".java");
toDelete.delete();
toDelete = new File (path+nomeClasse + ".class");
toDelete.delete();
String resultCompilacao = Compilar.compilar(path, nomeClasse, codigo);
if (!resultCompilacao.equals("")) {
return "CODE_ERROR!:!Falha ao compilar o código.\n"+resultCompilacao;
}
// Trata o codigo de teste
criterio = StringConverter.replace(criterio, "\r", "");
// Acrescenta parametro String no AssertEquals que não tiver
pos = criterio.indexOf("assert");
while (pos != -1) {
// Encontra o primeiro parametro
while (criterio.charAt(pos) != '(') pos++;
pos++;
posFim = pos;
int qtdeParentesesAberto = 0;
while (qtdeParentesesAberto != 0 || criterio.charAt(posFim) != ',') {
if (criterio.charAt(posFim) == '(') qtdeParentesesAberto++;
if (criterio.charAt(posFim) == ')') qtdeParentesesAberto--;
if (qtdeParentesesAberto > 1000) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o primeiro parâmetro. Excesso de parênteses abertos.";
if (posFim == criterio.length()-1) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o primeiro parâmetro. Fim do arquivo encontrado.";
posFim++;
}
String parametro = criterio.substring(pos, posFim);
// Encontrar o segundo parametro
qtdeParentesesAberto = 0;
posFim++;
while (qtdeParentesesAberto != 0 || (criterio.charAt(posFim) != ',' && criterio.charAt(posFim) != ')')) {
if (criterio.charAt(posFim) == '(') qtdeParentesesAberto++;
if (criterio.charAt(posFim) == ')') qtdeParentesesAberto--;
if (qtdeParentesesAberto > 1000) return "TESTCODE_ERROR!:!roblema no código de teste. Notifique o professor. Não foi possível identificar o último parâmetro. Excesso de parênteses abertos.";
if (posFim == criterio.length()-1) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o último parâmetro. Fim do arquivo encontrado.";
posFim++;
}
if (criterio.charAt(posFim) == ')') {
// Não tem o ultimo parametro
criterio = criterio.substring(0, posFim) + ",\"" + StringConverter.replace(parametro, "\"", "\\\"") + "\"" + criterio.substring(posFim);
}
pos = criterio.indexOf("assert", pos);
}
// Gera o arquivo de teste
String testClass = "RealizaTesteNaClasseSubmetida";
toDelete = new File(path+testClass + ".java");
toDelete.delete();
toDelete = new File (path+testClass + ".class");
toDelete.delete();
generateTestFile(path, testClass+".java", criterio);
resultCompilacao = Compilar.compilar(path, testClass+".java");
if (!resultCompilacao.equals("")) {
if (resultCompilacao.indexOf("cannot find symbol") != -1) {
if (resultCompilacao.indexOf("symbol : class ") != -1) {
String nome = extraiPalavraSeguinte(resultCompilacao, "symbol : class");
return "CODE_ERROR!:!Não foi encontrada a classe "+nome+".";
} else if (resultCompilacao.indexOf("symbol : method") != -1) {
String nomeMetodo = extraiPalavraSeguinte(resultCompilacao, "symbol : method");
String nomeLocal = extraiPalavraSeguinte(resultCompilacao, "location: class ");
return "CODE_ERROR!:!Não foi encontrado o método "+nomeMetodo+" na classe "+nomeLocal+".";
}
} else if (resultCompilacao.indexOf("cannot be applied to ") != -1) {
String mensagem = extraiPalavraSeguinte(resultCompilacao,": ");
return "CODE_ERROR!:!Problema com parâmetros: the method "+mensagem;
} else if (resultCompilacao.indexOf("incompatible types") != -1) {
String found = extraiPalavraSeguinte(resultCompilacao, "found :");
String required = extraiPalavraSeguinte(resultCompilacao, "required: ");
return "CODE_ERROR!:!Tipos de dados incompatíveis. Foi encontrado "+found+" e era requerido "+required+".";
}
- return "CODE_ERROR!:!Falha ao compilar o código de teste.\n"+resultCompilacao;
+ return "TESTCODE_ERROR!:!Falha ao compilar o código de teste. Entre em contato com o professor.\n"+resultCompilacao;
}
// Executa o teste
RuntimeExecutor r = new RuntimeExecutor(3000);
String resp = "";
if (path.startsWith("/")) { // Linux
resp = r.execute("java -cp "+path+" -Djava.security.manager -Dfile.encoding=utf-8 "+testClass, null);
} else { // Windows
resp = r.execute("java -cp \""+path+";\" -Djava.security.manager -Dfile.encoding=utf-8 "+testClass, null); // Para teste stand alone o ; foi necessário
}
toDelete = new File (path+nomeClasse + ".java");
toDelete.delete();
toDelete = new File (path+nomeClasse + ".class");
toDelete.delete();
toDelete = new File (path+"logCompilacao.txt");
toDelete.delete();
return resp;
}
private String extraiPalavraSeguinte(String texto, String inicio) {
int tam = inicio.length();
if (texto.indexOf(inicio) == -1) return null;
int posIni = texto.indexOf(inicio) + tam;
int posFim = texto.indexOf('\n', posIni);
return texto.substring(posIni, posFim);
}
private void generateTestFile(String path, String className, String criterio) throws Exception {
PrintWriter saida = new PrintWriter(new FileWriter(path+className));
BufferedReader template;
try {
template = new BufferedReader(new FileReader(path+"TestTemplate.java"));
} catch (Exception ex) {
throw new Exception ("SYSTEM_ERROR!:!Arquivo TestTemplate.java não encontrado no diretório " + path);
}
String linha;
while ((linha = template.readLine()) != null) {
if (linha.indexOf("/* Insert code here */") != -1) {
saida.append(criterio + "\n");
} else {
saida.append(linha + "\n");
}
}
saida.close();
}
}
| true | true | public synchronized String executeTest(String codigo, String criterio) throws Exception {
// Path
if (!(new File(path).exists())) throw new Exception("SYSTEM_ERROR!:!Diretório de execução não encontrado.");
// ----- Gera o arquivo do aluno ------
// descobre o nome da classe
int pos = codigo.indexOf("class ");
if (pos == -1) return "CODE_ERROR!:!Não há classe definida.";
pos = pos + "class ".length();
while (pos < codigo.length() && codigo.charAt(pos) == ' ') pos++;
int posFim = pos;
while (posFim < codigo.length() &&
(Character.isLetterOrDigit(codigo.charAt(posFim)) || codigo.charAt(posFim) == '_')) posFim++;
if (posFim == pos) return "CODE_ERROR!:!Não há classe definida.";
String nomeClasse = codigo.substring(pos, posFim);
// Compila
File toDelete;
toDelete = new File (path+nomeClasse + ".java");
toDelete.delete();
toDelete = new File (path+nomeClasse + ".class");
toDelete.delete();
String resultCompilacao = Compilar.compilar(path, nomeClasse, codigo);
if (!resultCompilacao.equals("")) {
return "CODE_ERROR!:!Falha ao compilar o código.\n"+resultCompilacao;
}
// Trata o codigo de teste
criterio = StringConverter.replace(criterio, "\r", "");
// Acrescenta parametro String no AssertEquals que não tiver
pos = criterio.indexOf("assert");
while (pos != -1) {
// Encontra o primeiro parametro
while (criterio.charAt(pos) != '(') pos++;
pos++;
posFim = pos;
int qtdeParentesesAberto = 0;
while (qtdeParentesesAberto != 0 || criterio.charAt(posFim) != ',') {
if (criterio.charAt(posFim) == '(') qtdeParentesesAberto++;
if (criterio.charAt(posFim) == ')') qtdeParentesesAberto--;
if (qtdeParentesesAberto > 1000) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o primeiro parâmetro. Excesso de parênteses abertos.";
if (posFim == criterio.length()-1) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o primeiro parâmetro. Fim do arquivo encontrado.";
posFim++;
}
String parametro = criterio.substring(pos, posFim);
// Encontrar o segundo parametro
qtdeParentesesAberto = 0;
posFim++;
while (qtdeParentesesAberto != 0 || (criterio.charAt(posFim) != ',' && criterio.charAt(posFim) != ')')) {
if (criterio.charAt(posFim) == '(') qtdeParentesesAberto++;
if (criterio.charAt(posFim) == ')') qtdeParentesesAberto--;
if (qtdeParentesesAberto > 1000) return "TESTCODE_ERROR!:!roblema no código de teste. Notifique o professor. Não foi possível identificar o último parâmetro. Excesso de parênteses abertos.";
if (posFim == criterio.length()-1) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o último parâmetro. Fim do arquivo encontrado.";
posFim++;
}
if (criterio.charAt(posFim) == ')') {
// Não tem o ultimo parametro
criterio = criterio.substring(0, posFim) + ",\"" + StringConverter.replace(parametro, "\"", "\\\"") + "\"" + criterio.substring(posFim);
}
pos = criterio.indexOf("assert", pos);
}
// Gera o arquivo de teste
String testClass = "RealizaTesteNaClasseSubmetida";
toDelete = new File(path+testClass + ".java");
toDelete.delete();
toDelete = new File (path+testClass + ".class");
toDelete.delete();
generateTestFile(path, testClass+".java", criterio);
resultCompilacao = Compilar.compilar(path, testClass+".java");
if (!resultCompilacao.equals("")) {
if (resultCompilacao.indexOf("cannot find symbol") != -1) {
if (resultCompilacao.indexOf("symbol : class ") != -1) {
String nome = extraiPalavraSeguinte(resultCompilacao, "symbol : class");
return "CODE_ERROR!:!Não foi encontrada a classe "+nome+".";
} else if (resultCompilacao.indexOf("symbol : method") != -1) {
String nomeMetodo = extraiPalavraSeguinte(resultCompilacao, "symbol : method");
String nomeLocal = extraiPalavraSeguinte(resultCompilacao, "location: class ");
return "CODE_ERROR!:!Não foi encontrado o método "+nomeMetodo+" na classe "+nomeLocal+".";
}
} else if (resultCompilacao.indexOf("cannot be applied to ") != -1) {
String mensagem = extraiPalavraSeguinte(resultCompilacao,": ");
return "CODE_ERROR!:!Problema com parâmetros: the method "+mensagem;
} else if (resultCompilacao.indexOf("incompatible types") != -1) {
String found = extraiPalavraSeguinte(resultCompilacao, "found :");
String required = extraiPalavraSeguinte(resultCompilacao, "required: ");
return "CODE_ERROR!:!Tipos de dados incompatíveis. Foi encontrado "+found+" e era requerido "+required+".";
}
return "CODE_ERROR!:!Falha ao compilar o código de teste.\n"+resultCompilacao;
}
// Executa o teste
RuntimeExecutor r = new RuntimeExecutor(3000);
String resp = "";
if (path.startsWith("/")) { // Linux
resp = r.execute("java -cp "+path+" -Djava.security.manager -Dfile.encoding=utf-8 "+testClass, null);
} else { // Windows
resp = r.execute("java -cp \""+path+";\" -Djava.security.manager -Dfile.encoding=utf-8 "+testClass, null); // Para teste stand alone o ; foi necessário
}
toDelete = new File (path+nomeClasse + ".java");
toDelete.delete();
toDelete = new File (path+nomeClasse + ".class");
toDelete.delete();
toDelete = new File (path+"logCompilacao.txt");
toDelete.delete();
return resp;
}
| public synchronized String executeTest(String codigo, String criterio) throws Exception {
// Path
if (!(new File(path).exists())) throw new Exception("SYSTEM_ERROR!:!Diretório de execução não encontrado.");
// ----- Gera o arquivo do aluno ------
// descobre o nome da classe
int pos = codigo.indexOf("class ");
if (pos == -1) return "CODE_ERROR!:!Não há classe definida.";
pos = pos + "class ".length();
while (pos < codigo.length() && codigo.charAt(pos) == ' ') pos++;
int posFim = pos;
while (posFim < codigo.length() &&
(Character.isLetterOrDigit(codigo.charAt(posFim)) || codigo.charAt(posFim) == '_')) posFim++;
if (posFim == pos) return "CODE_ERROR!:!Não há classe definida.";
String nomeClasse = codigo.substring(pos, posFim);
// Compila
File toDelete;
toDelete = new File (path+nomeClasse + ".java");
toDelete.delete();
toDelete = new File (path+nomeClasse + ".class");
toDelete.delete();
String resultCompilacao = Compilar.compilar(path, nomeClasse, codigo);
if (!resultCompilacao.equals("")) {
return "CODE_ERROR!:!Falha ao compilar o código.\n"+resultCompilacao;
}
// Trata o codigo de teste
criterio = StringConverter.replace(criterio, "\r", "");
// Acrescenta parametro String no AssertEquals que não tiver
pos = criterio.indexOf("assert");
while (pos != -1) {
// Encontra o primeiro parametro
while (criterio.charAt(pos) != '(') pos++;
pos++;
posFim = pos;
int qtdeParentesesAberto = 0;
while (qtdeParentesesAberto != 0 || criterio.charAt(posFim) != ',') {
if (criterio.charAt(posFim) == '(') qtdeParentesesAberto++;
if (criterio.charAt(posFim) == ')') qtdeParentesesAberto--;
if (qtdeParentesesAberto > 1000) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o primeiro parâmetro. Excesso de parênteses abertos.";
if (posFim == criterio.length()-1) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o primeiro parâmetro. Fim do arquivo encontrado.";
posFim++;
}
String parametro = criterio.substring(pos, posFim);
// Encontrar o segundo parametro
qtdeParentesesAberto = 0;
posFim++;
while (qtdeParentesesAberto != 0 || (criterio.charAt(posFim) != ',' && criterio.charAt(posFim) != ')')) {
if (criterio.charAt(posFim) == '(') qtdeParentesesAberto++;
if (criterio.charAt(posFim) == ')') qtdeParentesesAberto--;
if (qtdeParentesesAberto > 1000) return "TESTCODE_ERROR!:!roblema no código de teste. Notifique o professor. Não foi possível identificar o último parâmetro. Excesso de parênteses abertos.";
if (posFim == criterio.length()-1) return "TESTCODE_ERROR!:!Problema no código de teste. Notifique o professor. Não foi possível identificar o último parâmetro. Fim do arquivo encontrado.";
posFim++;
}
if (criterio.charAt(posFim) == ')') {
// Não tem o ultimo parametro
criterio = criterio.substring(0, posFim) + ",\"" + StringConverter.replace(parametro, "\"", "\\\"") + "\"" + criterio.substring(posFim);
}
pos = criterio.indexOf("assert", pos);
}
// Gera o arquivo de teste
String testClass = "RealizaTesteNaClasseSubmetida";
toDelete = new File(path+testClass + ".java");
toDelete.delete();
toDelete = new File (path+testClass + ".class");
toDelete.delete();
generateTestFile(path, testClass+".java", criterio);
resultCompilacao = Compilar.compilar(path, testClass+".java");
if (!resultCompilacao.equals("")) {
if (resultCompilacao.indexOf("cannot find symbol") != -1) {
if (resultCompilacao.indexOf("symbol : class ") != -1) {
String nome = extraiPalavraSeguinte(resultCompilacao, "symbol : class");
return "CODE_ERROR!:!Não foi encontrada a classe "+nome+".";
} else if (resultCompilacao.indexOf("symbol : method") != -1) {
String nomeMetodo = extraiPalavraSeguinte(resultCompilacao, "symbol : method");
String nomeLocal = extraiPalavraSeguinte(resultCompilacao, "location: class ");
return "CODE_ERROR!:!Não foi encontrado o método "+nomeMetodo+" na classe "+nomeLocal+".";
}
} else if (resultCompilacao.indexOf("cannot be applied to ") != -1) {
String mensagem = extraiPalavraSeguinte(resultCompilacao,": ");
return "CODE_ERROR!:!Problema com parâmetros: the method "+mensagem;
} else if (resultCompilacao.indexOf("incompatible types") != -1) {
String found = extraiPalavraSeguinte(resultCompilacao, "found :");
String required = extraiPalavraSeguinte(resultCompilacao, "required: ");
return "CODE_ERROR!:!Tipos de dados incompatíveis. Foi encontrado "+found+" e era requerido "+required+".";
}
return "TESTCODE_ERROR!:!Falha ao compilar o código de teste. Entre em contato com o professor.\n"+resultCompilacao;
}
// Executa o teste
RuntimeExecutor r = new RuntimeExecutor(3000);
String resp = "";
if (path.startsWith("/")) { // Linux
resp = r.execute("java -cp "+path+" -Djava.security.manager -Dfile.encoding=utf-8 "+testClass, null);
} else { // Windows
resp = r.execute("java -cp \""+path+";\" -Djava.security.manager -Dfile.encoding=utf-8 "+testClass, null); // Para teste stand alone o ; foi necessário
}
toDelete = new File (path+nomeClasse + ".java");
toDelete.delete();
toDelete = new File (path+nomeClasse + ".class");
toDelete.delete();
toDelete = new File (path+"logCompilacao.txt");
toDelete.delete();
return resp;
}
|
diff --git a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java
index 8af0bfcaa..1a8e046d9 100644
--- a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java
+++ b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java
@@ -1,2492 +1,2491 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.core.model;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IStatusHandler;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.debug.core.model.IStackFrame;
import org.eclipse.debug.core.model.ITerminate;
import org.eclipse.jdt.debug.core.IEvaluationRunnable;
import org.eclipse.jdt.debug.core.IJavaBreakpoint;
import org.eclipse.jdt.debug.core.IJavaObject;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.jdt.debug.core.IJavaVariable;
import org.eclipse.jdt.debug.core.JDIDebugModel;
import org.eclipse.jdt.internal.debug.core.IJDIEventListener;
import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin;
import org.eclipse.jdt.internal.debug.core.StringMatcher;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaBreakpoint;
import com.sun.jdi.ClassNotLoadedException;
import com.sun.jdi.ClassType;
import com.sun.jdi.Field;
import com.sun.jdi.IncompatibleThreadStateException;
import com.sun.jdi.IntegerValue;
import com.sun.jdi.InvalidStackFrameException;
import com.sun.jdi.InvalidTypeException;
import com.sun.jdi.InvocationException;
import com.sun.jdi.Location;
import com.sun.jdi.Method;
import com.sun.jdi.ObjectCollectedException;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.StackFrame;
import com.sun.jdi.ThreadGroupReference;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.VMDisconnectedException;
import com.sun.jdi.Value;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.StepEvent;
import com.sun.jdi.request.EventRequest;
import com.sun.jdi.request.EventRequestManager;
import com.sun.jdi.request.StepRequest;
/**
* Model thread implementation for an underlying
* thread on a VM.
*/
public class JDIThread extends JDIDebugElement implements IJavaThread {
/**
* Constant for the name of the main thread group.
*/
private static final String MAIN_THREAD_GROUP = "main"; //$NON-NLS-1$
/**
* Status code indicating that a request to suspend this thread has timed out
*/
public static final int SUSPEND_TIMEOUT= 161;
/**
* Underlying thread.
*/
private ThreadReference fThread;
/**
* Cache of previous name, used in case thread is garbage collected.
*/
private String fPreviousName;
/**
* Collection of stack frames
*/
private List fStackFrames;
/**
* Underlying thread group, cached on first access.
*/
private ThreadGroupReference fThreadGroup;
/**
* Name of underlying thread group, cached on first access.
*/
private String fThreadGroupName;
/**
* Whether children need to be refreshed. Set to
* <code>true</code> when stack frames are re-used
* on the next suspend.
*/
private boolean fRefreshChildren = true;
/**
* Currently pending step handler, <code>null</code>
* when not performing a step.
*/
private StepHandler fStepHandler= null;
/**
* Whether running.
*/
private boolean fRunning;
/**
* Whether terminated.
*/
private boolean fTerminated;
/**
* whether suspended but without firing the equivalent events.
*/
private boolean fSuspendedQuiet;
/**
* Whether this thread is a system thread.
*/
private boolean fIsSystemThread;
/**
* The collection of breakpoints that caused the last suspend, or
* an empty collection if the thread is not suspended or was not
* suspended by any breakpoint(s).
*/
private List fCurrentBreakpoints = new ArrayList(2);
/**
* Whether this thread is currently performing
* an evaluation. An evaluation may involve a series
* of method invocations.
*/
private boolean fIsPerformingEvaluation= false;
private IEvaluationRunnable fEvaluationRunnable;
/**
* Whether this thread was manually suspended during an
* evaluation.
*/
private boolean fEvaluationInterrupted = false;
/**
* Whether this thread is currently invoking a method.
* Nested method invocations cannot be performed.
*/
private boolean fIsInvokingMethod = false;
/**
* Whether or not this thread is currently honoring
* breakpoints. This flag allows breakpoints to be
* disabled during evaluations.
*/
private boolean fHonorBreakpoints= true;
/**
* The kind of step that was originally requested. Zero or
* more 'secondary steps' may be performed programmatically after
* the original user-requested step, and this field tracks the
* type (step into, over, return) of the original step.
*/
private int fOriginalStepKind;
/**
* The JDI Location from which an original user-requested step began.
*/
private Location fOriginalStepLocation;
/**
* The total stack depth at the time an original (user-requested) step
* is initiated. This is used along with the original step Location
* to determine if a step into comes back to the starting location and
* needs to be 'nudged' forward. Checking the stack depth eliminates
* undesired 'nudging' in recursive methods.
*/
private int fOriginalStepStackDepth;
/**
* Whether step filters should be used for the next step request.
*/
private boolean fUseStepFilters = false;
/**
* Whether or not this thread is currently suspending (user-requested).
*/
private boolean fIsSuspending= false;
private AsyncThread fAsyncThread;
/**
* Creates a new thread on the underlying thread reference
* in the given debug target.
*
* @param target the debug target in which this thread is contained
* @param thread the underlying thread on the VM
* @exception ObjectCollectedException if the underlying thread has been
* garbage collected and cannot be properly initialized
*/
public JDIThread(JDIDebugTarget target, ThreadReference thread) throws ObjectCollectedException {
super(target);
setUnderlyingThread(thread);
initialize();
}
/**
* Thread initialization:<ul>
* <li>Determines if this thread is a system thread</li>
* <li>Sets terminated state to <code>false</code></li>
* <li>Determines suspended state from underlying thread</li>
* <li>Sets this threads stack frames to an empty collection</li>
* </ul>
* @exception ObjectCollectedException if the thread has been garbage
* collected and cannot be initialized
*/
protected void initialize() throws ObjectCollectedException {
fStackFrames= Collections.EMPTY_LIST;
// system thread
try {
determineIfSystemThread();
} catch (DebugException e) {
Throwable underlyingException= e.getStatus().getException();
if (underlyingException instanceof VMDisconnectedException) {
// Threads may be created by the VM at shutdown
// as finalizers. The VM may be disconnected by
// the time we hear about the thread creation.
disconnected();
return;
}
if (underlyingException instanceof ObjectCollectedException) {
throw (ObjectCollectedException)underlyingException;
}
logError(e);
}
// state
setTerminated(false);
setRunning(false);
try {
setRunning(!getUnderlyingThread().isSuspended());
} catch (VMDisconnectedException e) {
disconnected();
return;
} catch (ObjectCollectedException e){
throw e;
} catch (RuntimeException e) {
logError(e);
}
}
/**
* Adds the given breakpoint to the list of breakpoints
* this thread is suspended at
*/
protected void addCurrentBreakpoint(IBreakpoint bp) {
fCurrentBreakpoints.add(bp);
}
/**
* Removes the given breakpoint from the list of breakpoints
* this thread is suspended at (called when a breakpoint is
* deleted, in case we are suspended at that breakpoint)
*/
protected void removeCurrentBreakpoint(IBreakpoint bp) {
fCurrentBreakpoints.remove(bp);
}
/**
* @see org.eclipse.debug.core.model.IThread#getBreakpoints()
*/
public IBreakpoint[] getBreakpoints() {
return (IBreakpoint[])fCurrentBreakpoints.toArray(new IBreakpoint[fCurrentBreakpoints.size()]);
}
/**
* @see ISuspendResume#canResume()
*/
public boolean canResume() {
return isSuspended() && !isSuspendedQuiet() && (!isPerformingEvaluation() || isInvokingMethod()) && !getDebugTarget().isSuspended();
}
/**
* @see ISuspendResume#canSuspend()
*/
public boolean canSuspend() {
return !isSuspended() || isSuspendedQuiet() || (isPerformingEvaluation() && !isInvokingMethod());
}
/**
* @see ITerminate#canTerminate()
*/
public boolean canTerminate() {
return getDebugTarget().canTerminate();
}
/**
* @see IStep#canStepInto()
*/
public boolean canStepInto() {
return canStep();
}
/**
* @see IStep#canStepOver()
*/
public boolean canStepOver() {
return canStep();
}
/**
* @see IStep#canStepReturn()
*/
public boolean canStepReturn() {
return canStep();
}
/**
* Returns whether this thread is in a valid state to
* step.
*
* @return whether this thread is in a valid state to
* step
*/
protected boolean canStep() {
try {
return isSuspended()
&& !isSuspendedQuiet()
&& (!isPerformingEvaluation() || isInvokingMethod())
&& !isStepping()
&& getTopStackFrame() != null
&& !getJavaDebugTarget().isPerformingHotCodeReplace();
} catch (DebugException e) {
return false;
}
}
/**
* Determines and sets whether this thread represents a system thread.
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void determineIfSystemThread() throws DebugException {
fIsSystemThread= false;
ThreadGroupReference tgr= getUnderlyingThreadGroup();
fIsSystemThread = tgr != null;
while (tgr != null) {
String tgn= null;
try {
tgn= tgr.name();
tgr= tgr.parent();
} catch (UnsupportedOperationException e) {
fIsSystemThread = false;
break;
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_determining_if_system_thread"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not reach this line, as
// #targetRequestFailed will throw an exception
return;
}
if (tgn != null && tgn.equals(MAIN_THREAD_GROUP)) {
fIsSystemThread= false;
break;
}
}
}
/**
* NOTE: this method returns a copy of this thread's stack frames.
*
* @see IThread#getStackFrames()
*/
public IStackFrame[] getStackFrames() throws DebugException {
if (isSuspendedQuiet()) {
return new IStackFrame[0];
}
List list = computeStackFrames();
return (IStackFrame[])list.toArray(new IStackFrame[list.size()]);
}
/**
* @see computeStackFrames()
*
* @param refreshChildren whether or not this method should request new stack
* frames from the VM
*/
protected synchronized List computeStackFrames(boolean refreshChildren) throws DebugException {
if (isSuspended()) {
if (isTerminated()) {
fStackFrames = Collections.EMPTY_LIST;
} else if (refreshChildren) {
if (fStackFrames.isEmpty()) {
fStackFrames = createAllStackFrames();
if (fStackFrames.isEmpty()) {
//leave fRefreshChildren == true
//bug 6393
return fStackFrames;
}
}
int stackSize = getUnderlyingFrameCount();
boolean topDown = false;
// what was the last method on the top of the stack
- JDIStackFrame topStackFrame = (JDIStackFrame)fStackFrames.get(0);
- Method lastMethod = topStackFrame.getLastMethod();
+ Method lastMethod = ((JDIStackFrame)fStackFrames.get(0)).getLastMethod();
// what is the method on top of the stack now
if (stackSize > 0) {
Method currMethod = getUnderlyingFrame(0).location().method();
if (currMethod.equals(lastMethod)) {
// preserve frames top down
topDown = true;
}
}
// compute new or removed stack frames
int offset= 0, length= stackSize;
if (length > fStackFrames.size()) {
if (topDown) {
// add new (empty) frames to the bottom of the stack to preserve frames top-down
int num = length - fStackFrames.size();
for (int i = 0; i < num; i++) {
fStackFrames.add(new JDIStackFrame(this, 0));
}
} else {
// add new frames to the top of the stack, preserve bottom up
offset= length - fStackFrames.size();
for (int i= offset - 1; i >= 0; i--) {
JDIStackFrame newStackFrame= new JDIStackFrame(this, 0);
fStackFrames.add(0, newStackFrame);
}
length= fStackFrames.size() - offset;
}
} else if (length < fStackFrames.size()) {
int removed= fStackFrames.size() - length;
if (topDown) {
// remove frames from the bottom of the stack, preserve top-down
for (int i = 0; i < removed; i++) {
fStackFrames.remove(fStackFrames.size() - 1);
}
} else {
// remove frames from the top of the stack, preserve bottom up
for (int i= 0; i < removed; i++) {
fStackFrames.remove(0);
}
}
} else if (length == 0) {
fStackFrames = Collections.EMPTY_LIST;
}
// update frame indicies
for (int i= 0; i < stackSize; i++) {
((JDIStackFrame)fStackFrames.get(i)).setDepth(i);
}
}
fRefreshChildren = false;
} else {
return Collections.EMPTY_LIST;
}
return fStackFrames;
}
/**
* Returns this thread's current stack frames as a list, computing
* them if required. Returns an empty collection if this thread is
* not currently suspended, or this thread is terminated. This
* method should be used internally to get the current stack frames,
* instead of calling <code>#getStackFrames()</code>, which makes a
* copy of the current list.
* <p>
* Before a thread is resumed a call must be made to one of:<ul>
* <li><code>preserveStackFrames()</code></li>
* <li><code>disposeStackFrames()</code></li>
* </ul>
* If stack frames are disposed before a thread is resumed, stack frames
* are completely re-computed on the next call to this method. If stack
* frames are to be preserved, this method will attempt to re-use any stack
* frame objects which represent the same stack frame as on the previous
* suspend. Stack frames are cached until a subsequent call to preserve
* or dispose stack frames.
* </p>
*
* @return list of <code>IJavaStackFrame</code>
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
public List computeStackFrames() throws DebugException {
return computeStackFrames(fRefreshChildren);
}
/**
* @see JDIThread#computeStackFrames()
*
* This method differs from computeStackFrames() in that it
* always requests new stack frames from the VM. As this is
* an expensive operation, this method should only be used
* by clients who know for certain that the stack frames
* on the VM have changed.
*/
public List computeNewStackFrames() throws DebugException {
return computeStackFrames(true);
}
/**
* Helper method for <code>#computeStackFrames()</code> to create all
* underlying stack frames.
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected List createAllStackFrames() throws DebugException {
int stackSize= getUnderlyingFrameCount();
List list= new ArrayList(stackSize);
for (int i = 0; i < stackSize; i++) {
JDIStackFrame newStackFrame= new JDIStackFrame(this, i);
list.add(newStackFrame);
}
return list;
}
/**
* Retrieves and returns the underlying stack frame at the specified depth
*
* @return stack frame
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected StackFrame getUnderlyingFrame(int depth) throws DebugException {
try {
return getUnderlyingThread().frame(depth);
} catch (IncompatibleThreadStateException e) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Unable_to_retrieve_stack_frame_-_thread_not_suspended._1"), e, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$
// execution will not reach this line, as
// #targetRequestFailed will thrown an exception
return null;
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_stack_frames_2"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not reach this line, as
// #targetRequestFailed will thrown an exception
return null;
} catch (InternalError e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_stack_frames_2"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not reach this line, as
// #targetRequestFailed will thrown an exception
return null;
}
}
/**
* Returns the underlying method for the given stack frame
*
* @param frame an underlying JDI stack frame
* @return underlying method
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected Method getUnderlyingMethod(StackFrame frame) throws DebugException {
try {
return frame.location().method();
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_method"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not reach this line, as
// #targetRequestFailed will thrown an exception
return null;
}
}
/**
* Returns the number of frames on the stack from the
* underlying thread.
*
* @return number of frames on the stack
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* <li>This thread is not suspended</li>
* </ul>
*/
protected int getUnderlyingFrameCount() throws DebugException {
try {
return getUnderlyingThread().frameCount();
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_frame_count"), new String[] {e.toString()}), e); //$NON-NLS-1$
} catch (IncompatibleThreadStateException e) {
requestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_frame_count"), new String[] {e.toString()}), e, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$
}
// execution will not reach here - try block will either
// return or exception will be thrown
return -1;
}
/**
* @see IJavaThread#runEvaluation(IEvaluationRunnable, IProgressMonitor, int)
*/
public void runEvaluation(IEvaluationRunnable evaluation, IProgressMonitor monitor, int evaluationDetail, boolean hitBreakpoints) throws DebugException {
if (isPerformingEvaluation()) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Cannot_perform_nested_evaluations"), null, IJavaThread.ERR_NESTED_METHOD_INVOCATION); //$NON-NLS-1$
}
if (!canRunEvaluation()) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Evaluation_failed_-_thread_not_suspended"), null, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$
}
fIsPerformingEvaluation = true;
fEvaluationRunnable= evaluation;
fHonorBreakpoints= hitBreakpoints;
fireResumeEvent(evaluationDetail);
//save and restore current breakpoint information - bug 30837
IBreakpoint[] breakpoints = getBreakpoints();
try {
evaluation.run(this, monitor);
} catch (DebugException e) {
throw e;
} finally {
fIsPerformingEvaluation = false;
fEvaluationRunnable= null;
fHonorBreakpoints= true;
if (getBreakpoints().length == 0 && breakpoints.length > 0) {
for (int i = 0; i < breakpoints.length; i++) {
addCurrentBreakpoint(breakpoints[i]);
}
}
fireSuspendEvent(evaluationDetail);
if (fEvaluationInterrupted && (fAsyncThread == null || fAsyncThread.isEmpty())) {
// @see bug 31585:
// When an evaluation was interrupted & resumed, the launch view does
// not update properly. It cannot know when it is safe to display frames
// since it does not know about queued evaluations. Thus, when the queue
// is empty, we fire a change event to force the view to update.
fEvaluationInterrupted = false;
fireChangeEvent(DebugEvent.CONTENT);
}
}
}
/**
* Returns whether this thread is in a valid state to
* run an evaluation.
*
* @return whether this thread is in a valid state to
* run an evaluation
*/
protected boolean canRunEvaluation() {
// NOTE similar to #canStep, except a quiet suspend state is OK
try {
return isSuspendedQuiet() || (isSuspended()
&& !(isPerformingEvaluation() || isInvokingMethod())
&& !isStepping()
&& getTopStackFrame() != null
&& !getJavaDebugTarget().isPerformingHotCodeReplace());
} catch (DebugException e) {
return false;
}
}
/**
* @see org.eclipse.jdt.debug.core.IJavaThread#queueRunnable(Runnable)
*/
public void queueRunnable(Runnable evaluation) {
if (fAsyncThread == null) {
fAsyncThread= new AsyncThread();
}
fAsyncThread.addRunnable(evaluation);
}
/**
* @see IJavaThread#terminateEvaluation()
*/
public void terminateEvaluation() throws DebugException {
if (canTerminateEvaluation()) {
((ITerminate) fEvaluationRunnable).terminate();
}
}
/**
* @see IJavaThread#canTerminateEvaluation()
*/
public boolean canTerminateEvaluation() {
return fEvaluationRunnable instanceof ITerminate;
}
/**
* Invokes a method on the target, in this thread, and returns the result. Only
* one receiver may be specified - either a class or an object, the other must
* be <code>null</code>. This thread is left suspended after the invocation
* is complete, unless a call is made to <code>abortEvaluation<code> while
* performing a method invocation. In that case, this thread is automatically
* resumed when/if this invocation (eventually) completes.
* <p>
* Method invocations cannot be nested. That is, this method must
* return before another call to this method can be made. This
* method does not return until the invocation is complete.
* Breakpoints can suspend a method invocation, and it is possible
* that an invocation will not complete due to an infinite loop
* or deadlock.
* </p>
* <p>
* Stack frames are preserved during method invocations, unless
* a timeout occurs. Although this thread's state is updated to
* running while performing an evaluation, no debug events are
* fired unless this invocation is interrupted by a breakpoint,
* or the invocation times out.
* </p>
* <p>
* When performing an invocation, the communication timeout with
* the target VM is set to infinite, as the invocation may not
* complete in a timely fashion, if at all. The timeout value
* is reset to its original value when the invocation completes.
* </p>
*
* @param receiverClass the class in the target representing the receiver
* of a static message send, or <code>null</code>
* @param receiverObject the object in the target to be the receiver of
* the message send, or <code>null</code>
* @param method the underlying method to be invoked
* @param args the arguments to invoke the method with (an empty list
* if none)
* @return the result of the method, as an underlying value
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* <li>This thread is not suspended
* (status code <code>IJavaThread.ERR_THREAD_NOT_SUSPENDED</code>)</li>
* <li>This thread is already invoking a method
* (status code <code>IJavaThread.ERR_NESTED_METHOD_INVOCATION</code>)</li>
* <li>This thread is not suspended by a JDI request
* (status code <code>IJavaThread.ERR_INCOMPATIBLE_THREAD_STATE</code>)</li>
* </ul>
*/
protected Value invokeMethod(ClassType receiverClass, ObjectReference receiverObject, Method method, List args, boolean invokeNonvirtual) throws DebugException {
if (receiverClass != null && receiverObject != null) {
throw new IllegalArgumentException(JDIDebugModelMessages.getString("JDIThread.can_only_specify_one_receiver_for_a_method_invocation")); //$NON-NLS-1$
}
Value result= null;
int timeout= getRequestTimeout();
try {
// this is synchronized such that any other operation that
// might be resuming this thread has a chance to complete before
// we determine if it is safe to continue with a method invocation.
// See bugs 6518, 14069
synchronized (this) {
if (!isSuspended()) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Evaluation_failed_-_thread_not_suspended"), null, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$
}
if (isInvokingMethod()) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Cannot_perform_nested_evaluations"), null, IJavaThread.ERR_NESTED_METHOD_INVOCATION); //$NON-NLS-1$
}
// set the request timeout to be infinite
setRequestTimeout(Integer.MAX_VALUE);
setRunning(true);
setInvokingMethod(true);
}
preserveStackFrames();
int flags= ClassType.INVOKE_SINGLE_THREADED;
if (invokeNonvirtual) {
// Superclass method invocation must be performed nonvirtual.
flags |= ObjectReference.INVOKE_NONVIRTUAL;
}
if (receiverClass == null) {
result= receiverObject.invokeMethod(getUnderlyingThread(), method, args, flags);
} else {
result= receiverClass.invokeMethod(getUnderlyingThread(), method, args, flags);
}
} catch (InvalidTypeException e) {
invokeFailed(e, timeout);
} catch (ClassNotLoadedException e) {
invokeFailed(e, timeout);
} catch (IncompatibleThreadStateException e) {
invokeFailed(JDIDebugModelMessages.getString("JDIThread.Thread_must_be_suspended_by_step_or_breakpoint_to_perform_method_invocation_1"), IJavaThread.ERR_INCOMPATIBLE_THREAD_STATE, e, timeout); //$NON-NLS-1$
} catch (InvocationException e) {
invokeFailed(e, timeout);
} catch (RuntimeException e) {
invokeFailed(e, timeout);
}
invokeComplete(timeout);
return result;
}
/**
* Invokes a constructor in this thread, creating a new instance of the given
* class, and returns the result as an object reference.
* This thread is left suspended after the invocation
* is complete.
* <p>
* Method invocations cannot be nested. That is, this method must
* return before another call to this method can be made. This
* method does not return until the invocation is complete.
* Breakpoints can suspend a method invocation, and it is possible
* that an invocation will not complete due to an infinite loop
* or deadlock.
* </p>
* <p>
* Stack frames are preserved during method invocations, unless
* a timeout occurs. Although this thread's state is updated to
* running while performing an evaluation, no debug events are
* fired unless this invocation is interrupted by a breakpoint,
* or the invocation times out.
* </p>
* <p>
* When performing an invocation, the communication timeout with
* the target VM is set to infinite, as the invocation may not
* complete in a timely fashion, if at all. The timeout value
* is reset to its original value when the invocation completes.
* </p>
*
* @param receiverClass the class in the target representing the receiver
* of the 'new' message send
* @param constructor the underlying constructor to be invoked
* @param args the arguments to invoke the constructor with (an empty list
* if none)
* @return a new object reference
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected ObjectReference newInstance(ClassType receiverClass, Method constructor, List args) throws DebugException {
if (isInvokingMethod()) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Cannot_perform_nested_evaluations_2"), null); //$NON-NLS-1$
}
ObjectReference result= null;
int timeout= getRequestTimeout();
try {
// set the request timeout to be infinite
setRequestTimeout(Integer.MAX_VALUE);
setRunning(true);
setInvokingMethod(true);
preserveStackFrames();
result= receiverClass.newInstance(getUnderlyingThread(), constructor, args, ClassType.INVOKE_SINGLE_THREADED);
} catch (InvalidTypeException e) {
invokeFailed(e, timeout);
} catch (ClassNotLoadedException e) {
invokeFailed(e, timeout);
} catch (IncompatibleThreadStateException e) {
invokeFailed(e, timeout);
} catch (InvocationException e) {
invokeFailed(e, timeout);
} catch (RuntimeException e) {
invokeFailed(e, timeout);
}
invokeComplete(timeout);
return result;
}
/**
* Called when an invocation fails. Performs cleanup
* and throws an exception.
*
* @param e the exception that caused the failure
* @param restoreTimeout the communication timeout value,
* in milliseconds, that should be reset
* @see #invokeComplete(int)
* @exception DebugException. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void invokeFailed(Throwable e, int restoreTimeout) throws DebugException {
invokeFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_invoking_method"), new String[] {e.toString()}), DebugException.TARGET_REQUEST_FAILED, e, restoreTimeout); //$NON-NLS-1$
}
/**
* Called when an invocation fails. Performs cleanup
* and throws an exception.
*
* @param message error message
* @param code status code
* @param e the exception that caused the failure
* @param restoreTimeout the communication timeout value,
* in milliseconds, that should be reset
* @see #invokeComplete(int)
* @exception DebugException. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void invokeFailed(String message, int code, Throwable e, int restoreTimeout) throws DebugException {
invokeComplete(restoreTimeout);
requestFailed(message, e, code);
}
/**
* Called when a method invocation has returned, successfully
* or not. This method performs cleanup:<ul>
* <li>Resets the state of this thread to suspended</li>
* <li>Restores the communication timeout value</li>
* <li>Computes the new set of stack frames for this thread</code>
* </ul>
*
* @param restoreTimeout the communication timeout value,
* in milliseconds, that should be reset
* @see #invokeMethod(ClassType, ObjectReference, Method, List)
* @see #newInstance(ClassType, Method, List)
*/
protected void invokeComplete(int restoreTimeout) {
abortStep();
setInvokingMethod(false);
setRunning(false);
setRequestTimeout(restoreTimeout);
// update preserved stack frames
try {
computeStackFrames();
} catch (DebugException e) {
logError(e);
}
}
/**
* @see IThread#getName()
*/
public String getName() throws DebugException {
try {
fPreviousName = getUnderlyingThread().name();
return fPreviousName;
} catch (RuntimeException e) {
// Don't bother reporting the exception when retrieving the name (bug 30785 & bug 33276)
if (e instanceof ObjectCollectedException) {
if (fPreviousName == null) {
return JDIDebugModelMessages.getString("JDIThread.garbage_collected_1"); //$NON-NLS-1$
} else {
return fPreviousName;
}
}
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_name"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not fall through, as
// #targetRequestFailed will thrown an exception
}
return null;
}
/**
* @see IThread#getPriority
*/
public int getPriority() throws DebugException {
// to get the priority, we must get the value from the "priority" field
Field p= null;
try {
p= getUnderlyingThread().referenceType().fieldByName("priority"); //$NON-NLS-1$
if (p == null) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.no_priority_field"), null); //$NON-NLS-1$
}
Value v= getUnderlyingThread().getValue(p);
if (v instanceof IntegerValue) {
return ((IntegerValue)v).value();
} else {
requestFailed(JDIDebugModelMessages.getString("JDIThread.priority_not_an_integer"), null); //$NON-NLS-1$
}
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_priority"), new String[] {e.toString()}), e); //$NON-NLS-1$
}
// execution will not fall through to this line, as
// #targetRequestFailed or #requestFailed will throw
// an exception
return -1;
}
/**
* @see IThread#getTopStackFrame()
*/
public IStackFrame getTopStackFrame() throws DebugException {
List c= computeStackFrames();
if (c.isEmpty()) {
return null;
} else {
return (IStackFrame) c.get(0);
}
}
/**
* A breakpoint has suspended execution of this thread.
* Aborts any step currently in process and fires a
* suspend event.
*
* @param breakpoint the breakpoint that caused the suspend
* @return whether this thread suspended
*/
public boolean handleSuspendForBreakpoint(JavaBreakpoint breakpoint, boolean queueEvent) {
addCurrentBreakpoint(breakpoint);
setSuspendedQuiet(false);
try {
// update state to suspended but don't actually
// suspend unless a registered listener agrees
if (breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_VM) {
((JDIDebugTarget)getDebugTarget()).prepareToSuspendByBreakpoint(breakpoint);
} else {
setRunning(false);
}
// poll listeners
boolean suspend = JDIDebugPlugin.getDefault().fireBreakpointHit(this, breakpoint);
// suspend or resume
if (suspend) {
if (breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_VM) {
((JDIDebugTarget)getDebugTarget()).suspendedByBreakpoint(breakpoint, queueEvent);
}
abortStep();
if (queueEvent) {
queueSuspendEvent(DebugEvent.BREAKPOINT);
} else {
fireSuspendEvent(DebugEvent.BREAKPOINT);
}
} else {
if (breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_VM) {
((JDIDebugTarget)getDebugTarget()).cancelSuspendByBreakpoint(breakpoint);
} else {
setRunning(true);
// dispose cached stack frames so we re-retrieve on the next breakpoint
preserveStackFrames();
}
}
return suspend;
} catch (CoreException e) {
logError(e);
return true;
}
}
/**
* Updates the state of this thread to suspend for
* the given breakpoint but does not fire notification
* of the suspend. Do no abort the current step as the program
* may be resumed quietly and the step may still finish.
*/
public boolean handleSuspendForBreakpointQuiet(JavaBreakpoint breakpoint) {
addCurrentBreakpoint(breakpoint);
setSuspendedQuiet(true);
setRunning(false);
return true;
}
/**
* @see IStep#isStepping()
*/
public boolean isStepping() {
return getPendingStepHandler() != null;
}
/**
* @see ISuspendResume#isSuspended()
*/
public boolean isSuspended() {
return !fRunning && !fTerminated;
}
/**
* @see ISuspendResume#isSuspended()
*/
public boolean isSuspendedQuiet() {
return fSuspendedQuiet;
}
/**
* @see IJavaThread#isSystemThread()
*/
public boolean isSystemThread() {
return fIsSystemThread;
}
/**
* @see IJavaThread#getThreadGroupName()
*/
public String getThreadGroupName() throws DebugException {
if (fThreadGroupName == null) {
ThreadGroupReference tgr= getUnderlyingThreadGroup();
// bug# 20370
if (tgr == null) {
return null;
}
try {
fThreadGroupName = tgr.name();
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_group_name"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not reach this line, as
// #targetRequestFailed will thrown an exception
return null;
}
}
return fThreadGroupName;
}
/**
* @see ITerminate#isTerminated()
*/
public boolean isTerminated() {
return fTerminated;
}
public boolean isOutOfSynch() throws DebugException {
if (isSuspended() && ((JDIDebugTarget)getDebugTarget()).hasHCRFailed()) {
List frames= computeStackFrames();
Iterator iter= frames.iterator();
while (iter.hasNext()) {
if (((JDIStackFrame) iter.next()).isOutOfSynch()) {
return true;
}
}
return false;
} else {
// If the thread is not suspended, there's no way to
// say for certain that it is running out of synch code
return false;
}
}
public boolean mayBeOutOfSynch() throws DebugException {
if (!isSuspended()) {
return ((JDIDebugTarget)getDebugTarget()).hasHCRFailed();
}
return false;
}
/**
* Sets whether this thread is terminated
*
* @param terminated whether this thread is terminated
*/
protected void setTerminated(boolean terminated) {
fTerminated= terminated;
}
/**
* @see ISuspendResume#resume()
*/
public void resume() throws DebugException {
resumeThread(true);
}
/**
* @see ISuspendResume#resume()
*
* Updates the state of this thread to resumed,
* but does not fire notification of the resumption.
*/
public void resumeQuiet() throws DebugException {
resumeThread(false);
}
/**
* @see ISuspendResume#resume()
*
* Updates the state of this thread, but only fires
* notification to listeners if <code>fireNotification</code>
* is <code>true</code>.
*/
private void resumeThread(boolean fireNotification) throws DebugException {
if (!isSuspended() || (isPerformingEvaluation() && !isInvokingMethod())) {
return;
}
try {
setRunning(true);
setSuspendedQuiet(false);
preserveStackFrames();
if (fireNotification) {
fireResumeEvent(DebugEvent.CLIENT_REQUEST);
}
getUnderlyingThread().resume();
} catch (VMDisconnectedException e) {
disconnected();
} catch (RuntimeException e) {
setRunning(false);
fireSuspendEvent(DebugEvent.CLIENT_REQUEST);
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_resuming"), new String[] {e.toString()}), e); //$NON-NLS-1$
}
}
/**
* Sets whether this thread is currently executing.
* When set to <code>true</code>, this thread's current
* breakpoints are cleared.
*
* @param running whether this thread is executing
*/
protected void setRunning(boolean running) {
fRunning = running;
if (running) {
fCurrentBreakpoints.clear();
}
}
protected void setSuspendedQuiet(boolean suspendedQuiet) {
fSuspendedQuiet= suspendedQuiet;
}
/**
* Preserves stack frames to be used on the next suspend event.
* Iterates through all current stack frames, setting their
* state as invalid. This method should be called before this thread
* is resumed, when stack frames are to be re-used when it later
* suspends.
*
* @see computeStackFrames()
*/
protected synchronized void preserveStackFrames() {
fRefreshChildren = true;
Iterator frames = fStackFrames.iterator();
while (frames.hasNext()) {
((JDIStackFrame)frames.next()).setUnderlyingStackFrame(null);
}
}
/**
* Disposes stack frames, to be completely re-computed on
* the next suspend event. This method should be called before
* this thread is resumed when stack frames are not to be re-used
* on the next suspend.
*
* @see computeStackFrames()
*/
protected synchronized void disposeStackFrames() {
fStackFrames= Collections.EMPTY_LIST;
fRefreshChildren = true;
}
/**
* This method is synchronized, such that the step request
* begins before a background evaluation can be performed.
*
* @see IStep#stepInto()
*/
public synchronized void stepInto() throws DebugException {
if (!canStepInto()) {
return;
}
StepHandler handler = new StepIntoHandler();
handler.step();
}
/**
* This method is synchronized, such that the step request
* begins before a background evaluation can be performed.
*
* @see IStep#stepOver()
*/
public synchronized void stepOver() throws DebugException {
if (!canStepOver()) {
return;
}
StepHandler handler = new StepOverHandler();
handler.step();
}
/**
* This method is synchronized, such that the step request
* begins before a background evaluation can be performed.
*
* @see IStep#stepReturn()
*/
public synchronized void stepReturn() throws DebugException {
if (!canStepReturn()) {
return;
}
StepHandler handler = new StepReturnHandler();
handler.step();
}
protected void setOriginalStepKind(int stepKind) {
fOriginalStepKind = stepKind;
}
protected int getOriginalStepKind() {
return fOriginalStepKind;
}
protected void setOriginalStepLocation(Location location) {
fOriginalStepLocation = location;
}
protected Location getOriginalStepLocation() {
return fOriginalStepLocation;
}
protected void setOriginalStepStackDepth(int depth) {
fOriginalStepStackDepth = depth;
}
protected int getOriginalStepStackDepth() {
return fOriginalStepStackDepth;
}
/**
* In cases where a user-requested step into encounters nothing but filtered code
* (static initializers, synthetic methods, etc.), the default JDI behavior is to
* put the instruction pointer back where it was before the step into. This requires
* a second step to move forward. Since this is confusing to the user, we do an
* extra step into in such situations. This method determines when such an extra
* step into is necessary. It compares the current Location to the original
* Location when the user step into was initiated. It also makes sure the stack depth
* now is the same as when the step was initiated.
*/
protected boolean shouldDoExtraStepInto(Location location) throws DebugException {
if (getOriginalStepKind() != StepRequest.STEP_INTO) {
return false;
}
if (getOriginalStepStackDepth() != getUnderlyingFrameCount()) {
return false;
}
Location origLocation = getOriginalStepLocation();
if (origLocation == null) {
return false;
}
// We cannot simply check if the two Locations are equal using the equals()
// method, since this checks the code index within the method. Even if the
// code indices are different, the line numbers may be the same, in which case
// we need to do the extra step into.
Method origMethod = origLocation.method();
Method currMethod = location.method();
if (!origMethod.equals(currMethod)) {
return false;
}
if (origLocation.lineNumber() != location.lineNumber()) {
return false;
}
return true;
}
/**
* @see ISuspendResume#suspend()
*/
public void suspend() throws DebugException {
try {
// Abort any pending step request
abortStep();
setSuspendedQuiet(false);
fEvaluationInterrupted = isPerformingEvaluation();
suspendUnderlyingThread();
} catch (RuntimeException e) {
setRunning(true);
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_suspending"), new String[] {e.toString()}), e); //$NON-NLS-1$
}
}
/**
* Suspends the underlying thread asynchronously and fires notification when
* the underlying thread is suspended.
*/
protected void suspendUnderlyingThread() {
if (fIsSuspending) {
return;
}
fIsSuspending= true;
Thread thread= new Thread(new Runnable() {
public void run() {
try {
getUnderlyingThread().suspend();
int timeout= JDIDebugModel.getPreferences().getInt(JDIDebugModel.PREF_REQUEST_TIMEOUT);
long stop= System.currentTimeMillis() + timeout;
boolean suspended= isUnderlyingThreadSuspended();
while (System.currentTimeMillis() < stop && !suspended) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
suspended= isUnderlyingThreadSuspended();
if (suspended) {
break;
}
}
if (!suspended) {
IStatus status= new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), SUSPEND_TIMEOUT, MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.suspend_timeout"), new String[] {new Integer(timeout).toString()}), null); //$NON-NLS-1$
IStatusHandler handler= DebugPlugin.getDefault().getStatusHandler(status);
if (handler != null) {
try {
handler.handleStatus(status, JDIThread.this);
} catch (CoreException e) {
}
}
}
setRunning(false);
fireSuspendEvent(DebugEvent.CLIENT_REQUEST);
} catch (RuntimeException exception) {
} finally {
fIsSuspending= false;
}
}
});
thread.start();
}
public boolean isUnderlyingThreadSuspended() {
return getUnderlyingThread().isSuspended();
}
/**
* Notifies this thread that it has been suspended due
* to a VM suspend.
*/
protected void suspendedByVM() {
setRunning(false);
setSuspendedQuiet(false);
}
/**
* Notifies this thread that is about to be resumed due
* to a VM resume.
*/
protected void resumedByVM() {
setRunning(true);
preserveStackFrames();
// This method is called *before* the VM is actually resumed.
// To ensure that all threads will fully resume when the VM
// is resumed, make sure the suspend count of each thread
// is no greater than 1. @see Bugs 23328 and 27622
ThreadReference thread= getUnderlyingThread();
while (thread.suspendCount() > 1) {
thread.resume();
}
}
/**
* @see ITerminate#terminate()
*/
public void terminate() throws DebugException {
terminateEvaluation();
getDebugTarget().terminate();
}
/**
* Drops to the given stack frame
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void dropToFrame(IStackFrame frame) throws DebugException {
JDIDebugTarget target= (JDIDebugTarget) getDebugTarget();
if (target.canPopFrames()) {
// JDK 1.4 support
try {
// Pop the drop frame and all frames above it
popFrame(frame);
stepInto();
} catch (RuntimeException exception) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_dropping_to_frame"), new String[] {exception.toString()}),exception); //$NON-NLS-1$
}
} else {
// J9 support
// This block is synchronized, such that the step request
// begins before a background evaluation can be performed.
synchronized (this) {
StepHandler handler = new DropToFrameHandler(frame);
handler.step();
}
}
}
protected void popFrame(IStackFrame frame) throws DebugException {
JDIDebugTarget target= (JDIDebugTarget)getDebugTarget();
if (target.canPopFrames()) {
// JDK 1.4 support
try {
// Pop the frame and all frames above it
StackFrame jdiFrame= null;
int desiredSize= fStackFrames.size() - fStackFrames.indexOf(frame) - 1;
int lastSize= fStackFrames.size() + 1; // Set up to pass the first test
int size= fStackFrames.size();
while (size < lastSize && size > desiredSize) {
// Keep popping frames until the stack stops getting smaller
// or popFrame is gone.
// see Bug 8054
jdiFrame = ((JDIStackFrame) frame).getUnderlyingStackFrame();
preserveStackFrames();
fThread.popFrames(jdiFrame);
lastSize= size;
size= computeStackFrames().size();
}
} catch (IncompatibleThreadStateException exception) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_popping"), new String[] {exception.toString()}),exception); //$NON-NLS-1$
} catch (InvalidStackFrameException exception) {
// InvalidStackFrameException can be thrown when all but the
// deepest frame were popped. Fire a changed notification
// in case this has occured.
fireChangeEvent(DebugEvent.CONTENT);
targetRequestFailed(exception.toString(),exception); //$NON-NLS-1$
} catch (RuntimeException exception) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_popping"), new String[] {exception.toString()}),exception); //$NON-NLS-1$
}
}
}
/**
* Steps until the specified stack frame is the top frame. Provides
* ability to step over/return in the non-top stack frame.
* This method is synchronized, such that the step request
* begins before a background evaluation can be performed.
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected synchronized void stepToFrame(IStackFrame frame) throws DebugException {
if (!canStepReturn()) {
return;
}
StepHandler handler = new StepToFrameHandler(frame);
handler.step();
}
/**
* Aborts the current step, if any.
*/
protected void abortStep() {
StepHandler handler = getPendingStepHandler();
if (handler != null) {
handler.abort();
}
}
/**
* @see IJavaThread#findVariable(String)
*/
public IJavaVariable findVariable(String varName) throws DebugException {
if (isSuspended()) {
try {
IStackFrame[] stackFrames= getStackFrames();
for (int i = 0; i < stackFrames.length; i++) {
IJavaStackFrame sf= (IJavaStackFrame)stackFrames[i];
IJavaVariable var= sf.findVariable(varName);
if (var != null) {
return var;
}
}
} catch (DebugException e) {
// if the thread has since reusmed, return null (no need to report error)
if (e.getStatus().getCode() != IJavaThread.ERR_THREAD_NOT_SUSPENDED) {
throw e;
}
}
}
return null;
}
/**
* Notification this thread has terminated - update state
* and fire a terminate event.
*/
protected void terminated() {
setTerminated(true);
setRunning(false);
fireTerminateEvent();
}
/**
* Returns this thread on the underlying VM which this
* model thread is a proxy to.
*
* @return underlying thread
*/
public ThreadReference getUnderlyingThread() {
return fThread;
}
/**
* Sets the underlying thread that this model object
* is a proxy to.
*
* @param thread underlying thread on target VM
*/
protected void setUnderlyingThread(ThreadReference thread) {
fThread = thread;
}
/**
* Returns this thread's underlying thread group.
*
* @return thread group
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* <li>Retrieving the underlying thread group is not supported
* on the underlying VM</li>
* </ul>
*/
protected ThreadGroupReference getUnderlyingThreadGroup() throws DebugException {
if (fThreadGroup == null) {
try {
fThreadGroup = getUnderlyingThread().threadGroup();
} catch (UnsupportedOperationException e) {
requestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_group"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not reach this line, as
// #requestFailed will throw an exception
return null;
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_group"), new String[] {e.toString()}), e); //$NON-NLS-1$
// execution will not reach this line, as
// #targetRequestFailed will throw an exception
return null;
}
}
return fThreadGroup;
}
/**
* @see IJavaThread#isPerformingEvaluation()
*/
public boolean isPerformingEvaluation() {
return fIsPerformingEvaluation;
}
/**
* Returns whether this thread is currently performing
* a method invokation
*/
public boolean isInvokingMethod() {
return fIsInvokingMethod;
}
/**
* Returns whether this thread is currently ignoring
* breakpoints.
*/
public boolean isIgnoringBreakpoints() {
return !fHonorBreakpoints;
}
/**
* Sets whether this thread is currently invoking a method
*
* @param evaluating whether this thread is currently
* invoking a method
*/
protected void setInvokingMethod(boolean invoking) {
fIsInvokingMethod= invoking;
}
/**
* Sets the step handler currently handling a step
* request.
*
* @param handler the current step handler, or <code>null</code>
* if none
*/
protected void setPendingStepHandler(StepHandler handler) {
fStepHandler = handler;
}
/**
* Returns the step handler currently handling a step
* request, or <code>null</code> if none.
*
* @return step handler, or <code>null</code> if none
*/
protected StepHandler getPendingStepHandler() {
return fStepHandler;
}
/**
* Helper class to perform stepping an a thread.
*/
abstract class StepHandler implements IJDIEventListener {
/**
* Request for stepping in the underlying VM
*/
private StepRequest fStepRequest;
/**
* Initiates a step in the underlying VM by creating a step
* request of the appropriate kind (over, into, return),
* and resuming this thread. When a step is initiated it
* is registered with its thread as a pending step. A pending
* step could be cancelled if a breakpoint suspends execution
* during the step.
* <p>
* This thread's state is set to running and stepping, and
* stack frames are invalidated (but preserved to be re-used
* when the step completes). A resume event with a step detail
* is fired for this thread.
* </p>
* Note this method does nothing if this thread has no stack frames.
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void step() throws DebugException {
JDIStackFrame top = (JDIStackFrame)getTopStackFrame();
if (top == null) {
return;
}
setOriginalStepKind(getStepKind());
Location location = top.getUnderlyingStackFrame().location();
setOriginalStepLocation(location);
setOriginalStepStackDepth(computeStackFrames().size());
setStepRequest(createStepRequest());
setPendingStepHandler(this);
addJDIEventListener(this, getStepRequest());
setRunning(true);
preserveStackFrames();
fireResumeEvent(getStepDetail());
invokeThread();
}
/**
* Resumes the underlying thread to initiate the step.
* By default the thread is resumed. Step handlers that
* require other actions can override this method.
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void invokeThread() throws DebugException {
try {
getUnderlyingThread().resume();
} catch (RuntimeException e) {
stepEnd();
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_stepping"), new String[] {e.toString()}), e); //$NON-NLS-1$
}
}
/**
* Creates and returns a step request specific to this step
* handler. Subclasses must override <code>getStepKind()</code>
* to return the kind of step it implements.
*
* @return step request
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected StepRequest createStepRequest() throws DebugException {
EventRequestManager manager = getEventRequestManager();
if (manager == null) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Unable_to_create_step_request_-_VM_disconnected._1"), null); //$NON-NLS-1$
}
try {
StepRequest request = manager.createStepRequest(getUnderlyingThread(), StepRequest.STEP_LINE, getStepKind());
request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
request.addCountFilter(1);
attachFiltersToStepRequest(request);
request.enable();
return request;
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_creating_step_request"), new String[] {e.toString()}), e); //$NON-NLS-1$
}
// this line will never be executed, as the try block
// will either return, or the catch block will throw
// an exception
return null;
}
/**
* Returns the kind of step this handler implements.
*
* @return one of <code>StepRequest.STEP_INTO</code>,
* <code>StepRequest.STEP_OVER</code>, <code>StepRequest.STEP_OUT</code>
*/
protected abstract int getStepKind();
/**
* Returns the detail for this step event.
*
* @return one of <code>DebugEvent.STEP_INTO</code>,
* <code>DebugEvent.STEP_OVER</code>, <code>DebugEvent.STEP_RETURN</code>
*/
protected abstract int getStepDetail();
/**
* Sets the step request created by this handler in
* the underlying VM. Set to <code>null<code> when
* this handler deletes its request.
*
* @param request step request
*/
protected void setStepRequest(StepRequest request) {
fStepRequest = request;
}
/**
* Returns the step request created by this handler in
* the underlying VM.
*
* @return step request
*/
protected StepRequest getStepRequest() {
return fStepRequest;
}
/**
* Deletes this handler's step request from the underlying VM
* and removes this handler as an event listener.
*/
protected void deleteStepRequest() {
removeJDIEventListener(this, getStepRequest());
try {
EventRequestManager manager = getEventRequestManager();
if (manager != null) {
manager.deleteEventRequest(getStepRequest());
}
setStepRequest(null);
} catch (RuntimeException e) {
logError(e);
}
}
/**
* If step filters are currently switched on and the current location is not a filtered
* location, set all active filters on the step request.
*/
protected void attachFiltersToStepRequest(StepRequest request) {
if (applyStepFilters() && (getJavaDebugTarget().isStepFiltersEnabled() || fUseStepFilters)) {
Location currentLocation= getOriginalStepLocation();
if (currentLocation == null) {
return;
}
//check if the user has already stopped in a filtered location
//is so do not filter @see bug 5587
ReferenceType type= currentLocation.declaringType();
String typeName= type.name();
String[] activeFilters = getJavaDebugTarget().getStepFilters();
for (int i = 0; i < activeFilters.length; i++) {
StringMatcher matcher = new StringMatcher(activeFilters[i], false, false);
if (matcher.match(typeName)) {
return;
}
}
for (int i = 0; i < activeFilters.length; i++) {
request.addClassExclusionFilter(activeFilters[i]);
}
}
}
/**
* Returns whether this step handler should use step
* filters when creating its step request. By default,
* step filters are not used. Subclasses must override
* if/when required.
*
* @return whether this step handler should use step
* filters when creating its step request
*/
protected boolean applyStepFilters() {
return false;
}
/**
* Notification the step request has completed.
* If the current location matches one of the user-specified
* step filter criteria (e.g., synthetic methods, static initializers),
* then continue stepping.
*
* @see IJDIEventListener#handleEvent(Event, JDIDebugTarget)
*/
public boolean handleEvent(Event event, JDIDebugTarget target) {
try {
StepEvent stepEvent = (StepEvent) event;
Location currentLocation = stepEvent.location();
// if the ending step location is filtered and we did not start from
// a filtered location, or if we're back where
// we started on a step into, do another step of the same kind
if (locationShouldBeFiltered(currentLocation) || shouldDoExtraStepInto(currentLocation)) {
setRunning(true);
deleteStepRequest();
createSecondaryStepRequest();
return true;
// otherwise, we're done stepping
} else {
stepEnd();
return false;
}
} catch (DebugException e) {
logError(e);
stepEnd();
return false;
}
}
/**
* Returns <code>true</code> if the StepEvent's Location is a Method that the
* user has indicated (via the step filter preferences) should be
* filtered and the step was not initiated from a filtered location.
* Returns <code>false</code> otherwise.
*/
protected boolean locationShouldBeFiltered(Location location) throws DebugException {
if (applyStepFilters()) {
Location origLocation= getOriginalStepLocation();
if (origLocation != null) {
return !locationIsFiltered(origLocation.method()) && locationIsFiltered(location.method());
}
}
return false;
}
/**
* Returns <code>true</code> if the StepEvent's Location is a Method that the
* user has indicated (via the step filter preferences) should be
* filtered. Returns <code>false</code> otherwise.
*/
protected boolean locationIsFiltered(Method method) {
if (getJavaDebugTarget().isStepFiltersEnabled() || fUseStepFilters) {
boolean filterStatics = getJavaDebugTarget().isFilterStaticInitializers();
boolean filterSynthetics = getJavaDebugTarget().isFilterSynthetics();
boolean filterConstructors = getJavaDebugTarget().isFilterConstructors();
if (!(filterStatics || filterSynthetics || filterConstructors)) {
return false;
}
if ((filterStatics && method.isStaticInitializer()) ||
(filterSynthetics && method.isSynthetic()) ||
(filterConstructors && method.isConstructor()) ) {
return true;
}
}
return false;
}
/**
* Cleans up when a step completes.<ul>
* <li>Thread state is set to suspended.</li>
* <li>Stepping state is set to false</li>
* <li>Stack frames and variables are incrementally updated</li>
* <li>The step request is deleted and removed as
* and event listener</li>
* <li>A suspend event is fired</li>
* </ul>
*/
protected void stepEnd() {
fUseStepFilters = false;
setRunning(false);
deleteStepRequest();
setPendingStepHandler(null);
queueSuspendEvent(DebugEvent.STEP_END);
}
/**
* Creates another step request in the underlying thread of the
* appropriate kind (over, into, return). This thread will
* be resumed by the event dispatcher as this event handler
* will vote to resume suspended threads. When a step is
* initiated it is registered with its thread as a pending
* step. A pending step could be cancelled if a breakpoint
* suspends execution during the step.
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void createSecondaryStepRequest() throws DebugException {
setStepRequest(createStepRequest());
setPendingStepHandler(this);
addJDIEventListener(this, getStepRequest());
}
/**
* Aborts this step request if active. The step event
* request is deleted from the underlying VM.
*/
protected void abort() {
if (getStepRequest() != null) {
deleteStepRequest();
setPendingStepHandler(null);
}
}
}
/**
* Handler for step over requests.
*/
class StepOverHandler extends StepHandler {
/**
* @see StepHandler#getStepKind()
*/
protected int getStepKind() {
return StepRequest.STEP_OVER;
}
/**
* @see StepHandler#getStepDetail()
*/
protected int getStepDetail() {
return DebugEvent.STEP_OVER;
}
}
/**
* Handler for step into requests.
*/
class StepIntoHandler extends StepHandler {
/**
* @see StepHandler#getStepKind()
*/
protected int getStepKind() {
return StepRequest.STEP_INTO;
}
/**
* @see StepHandler#getStepDetail()
*/
protected int getStepDetail() {
return DebugEvent.STEP_INTO;
}
/**
* Returns <code>true</code>. Step filters are applied for
* stepping into new frames.
*
* @see StepHandler#applyStepFilters()
*/
protected boolean applyStepFilters() {
return true;
}
}
/**
* Handler for step return requests.
*/
class StepReturnHandler extends StepHandler {
/**
* @see StepHandler#getStepKind()
*/
protected int getStepKind() {
return StepRequest.STEP_OUT;
}
/**
* @see StepHandler#getStepDetail()
*/
protected int getStepDetail() {
return DebugEvent.STEP_RETURN;
}
}
/**
* Handler for stepping to a specific stack frame
* (stepping in the non-top stack frame). Step returns
* are performed until a specified stack frame is reached
* or the thread is suspended (explicitly, or by a
* breakpoint).
*/
class StepToFrameHandler extends StepReturnHandler {
/**
* The number of frames that should be left on the stack
*/
private int fRemainingFrames;
/**
* Constructs a step handler to step until the specified
* stack frame is reached.
*
* @param frame the stack frame to step to
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected StepToFrameHandler(IStackFrame frame) throws DebugException {
List frames = computeStackFrames();
setRemainingFrames(frames.size() - frames.indexOf(frame));
}
/**
* Sets the number of frames that should be
* remaining on the stack when done.
*
* @param num number of remaining frames
*/
protected void setRemainingFrames(int num) {
fRemainingFrames = num;
}
/**
* Returns number of frames that should be
* remaining on the stack when done
*
* @return number of frames that should be left
*/
protected int getRemainingFrames() {
return fRemainingFrames;
}
/**
* Notification the step request has completed.
* If in the desired frame, complete the step
* request normally. If not in the desired frame,
* another step request is created and this thread
* is resumed.
*
* @see IJDIEventListener#handleEvent(Event, JDIDebugTarget)
*/
public boolean handleEvent(Event event, JDIDebugTarget target) {
try {
int numFrames = getUnderlyingFrameCount();
// tos should not be null
if (numFrames <= getRemainingFrames()) {
stepEnd();
return false;
} else {
// reset running state and keep going
setRunning(true);
deleteStepRequest();
createSecondaryStepRequest();
return true;
}
} catch (DebugException e) {
logError(e);
stepEnd();
return false;
}
}
}
/**
* Handles dropping to a specified frame.
*/
class DropToFrameHandler extends StepReturnHandler {
/**
* The number of frames to drop off the
* stack.
*/
private int fFramesToDrop;
/**
* Constructs a handler to drop to the specified
* stack frame.
*
* @param frame the stack frame to drop to
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected DropToFrameHandler(IStackFrame frame) throws DebugException {
List frames = computeStackFrames();
setFramesToDrop(frames.indexOf(frame));
}
/**
* Sets the number of frames to pop off the stack.
*
* @param num number of frames to pop
*/
protected void setFramesToDrop(int num) {
fFramesToDrop = num;
}
/**
* Returns the number of frames to pop off the stack.
*
* @return remaining number of frames to pop
*/
protected int getFramesToDrop() {
return fFramesToDrop;
}
/**
* To drop a frame or re-enter, the underlying thread is instructed
* to do a return. When the frame count is less than zero, the
* step being performed is a "step return", so a regular invocation
* is performed.
*
* @see StepHandler#invokeThread()
*/
protected void invokeThread() throws DebugException {
if (getFramesToDrop() < 0) {
super.invokeThread();
} else {
try {
org.eclipse.jdi.hcr.ThreadReference hcrThread= (org.eclipse.jdi.hcr.ThreadReference) getUnderlyingThread();
hcrThread.doReturn(null, true);
} catch (RuntimeException e) {
stepEnd();
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString(JDIDebugModelMessages.getString("JDIThread.exception_while_popping_stack_frame")), new String[] {e.toString()}), e); //$NON-NLS-1$
}
}
}
/**
* Notification that the pop has completed. If there are
* more frames to pop, keep going, otherwise re-enter the
* top frame. Returns false, as this handler will resume this
* thread with a special invocation (<code>doReturn</code>).
*
* @see IJDIEventListener#handleEvent(Event, JDIDebugTarget)
* @see #invokeThread()
*/
public boolean handleEvent(Event event, JDIDebugTarget target) {
// pop is complete, update number of frames to drop
setFramesToDrop(getFramesToDrop() - 1);
try {
if (getFramesToDrop() >= -1) {
deleteStepRequest();
doSecondaryStep();
} else {
stepEnd();
}
} catch (DebugException e) {
stepEnd();
logError(e);
}
return false;
}
/**
* Pops a secondary frame off the stack, does a re-enter,
* or a step-into.
*
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected void doSecondaryStep() throws DebugException {
setStepRequest(createStepRequest());
setPendingStepHandler(this);
addJDIEventListener(this, getStepRequest());
invokeThread();
}
/**
* Creates and returns a step request. If there
* are no more frames to drop, a re-enter request
* is made. If the re-enter is complete, a step-into
* request is created.
*
* @return step request
* @exception DebugException if this method fails. Reasons include:
* <ul>
* <li>Failure communicating with the VM. The DebugException's
* status code contains the underlying exception responsible for
* the failure.</li>
* </ul>
*/
protected StepRequest createStepRequest() throws DebugException {
EventRequestManager manager = getEventRequestManager();
if (manager == null) {
requestFailed(JDIDebugModelMessages.getString("JDIThread.Unable_to_create_step_request_-_VM_disconnected._2"), null); //$NON-NLS-1$
}
int num = getFramesToDrop();
if (num > 0) {
return super.createStepRequest();
} else if (num == 0) {
try {
StepRequest request = ((org.eclipse.jdi.hcr.EventRequestManager) manager).createReenterStepRequest(getUnderlyingThread());
request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
request.addCountFilter(1);
request.enable();
return request;
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_creating_step_request"), new String[] {e.toString()}), e); //$NON-NLS-1$
}
} else if (num == -1) {
try {
StepRequest request = manager.createStepRequest(getUnderlyingThread(), StepRequest.STEP_LINE, StepRequest.STEP_INTO);
request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
request.addCountFilter(1);
request.enable();
return request;
} catch (RuntimeException e) {
targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_creating_step_request"), new String[] {e.toString()}), e); //$NON-NLS-1$
}
}
// this line will never be executed, as the try block
// will either return, or the catch block with throw
// an exception
return null;
}
}
/**
* @see IThread#hasStackFrames()
*/
public boolean hasStackFrames() throws DebugException {
try {
return computeStackFrames().size() > 0;
} catch (DebugException e) {
// do not throw an exception if the thread resumed while determining
// whether stack frames are present
if (e.getStatus().getCode() != IJavaThread.ERR_THREAD_NOT_SUSPENDED) {
throw e;
}
}
return false;
}
/**
* @see IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class adapter) {
if (adapter == IJavaThread.class) {
return this;
}
if (adapter == IJavaStackFrame.class) {
try {
return (IJavaStackFrame)getTopStackFrame();
} catch (DebugException e) {
// do nothing if not able to get frame
}
}
return super.getAdapter(adapter);
}
/**
* @see org.eclipse.jdt.debug.core.IJavaThread#hasOwnedMonitors()
*/
public boolean hasOwnedMonitors() throws DebugException {
return isSuspended() && getOwnedMonitors().length > 0;
}
/**
* @see org.eclipse.jdt.debug.core.IJavaThread#getOwnedMonitors()
*/
public IJavaObject[] getOwnedMonitors() throws DebugException {
try {
JDIDebugTarget target= (JDIDebugTarget)getDebugTarget();
List ownedMonitors= getUnderlyingThread().ownedMonitors();
IJavaObject[] javaOwnedMonitors= new IJavaObject[ownedMonitors.size()];
Iterator itr= ownedMonitors.iterator();
int i= 0;
while (itr.hasNext()) {
ObjectReference element = (ObjectReference) itr.next();
javaOwnedMonitors[i]= new JDIObjectValue(target, element);
i++;
}
return javaOwnedMonitors;
} catch (IncompatibleThreadStateException e) {
}
return null;
}
/**
* @see org.eclipse.jdt.debug.core.IJavaThread#getContendedMonitor()
*/
public IJavaObject getContendedMonitor() throws DebugException {
try {
ObjectReference monitor= getUnderlyingThread().currentContendedMonitor();
if (monitor != null) {
return new JDIObjectValue((JDIDebugTarget)getDebugTarget(), monitor);
}
} catch (IncompatibleThreadStateException e) {
}
return null;
}
/**
* @see org.eclipse.debug.core.model.IFilteredStep#canStepWithFilters()
*/
public boolean canStepWithFilters() {
if (canStepInto()) {
String[] filters = getJavaDebugTarget().getStepFilters();
return filters != null && filters.length > 0;
}
return false;
}
/**
* @see org.eclipse.debug.core.model.IFilteredStep#stepWithFilters()
*/
public void stepWithFilters() throws DebugException {
if (!canStepWithFilters()) {
return;
}
fUseStepFilters = true;
stepInto();
}
/**
* Class which managed the queue of runnable associated with this thread.
*/
private class AsyncThread implements Runnable {
private ArrayList fRunnables;
private Thread fThread;
public AsyncThread() {
fRunnables= new ArrayList();
}
public void addRunnable(Runnable runnable) {
synchronized (this) {
fRunnables.add(runnable);
if (fThread == null) {
try {
fThread= new Thread(this, "JDI async thread - " + getName()); //$NON-NLS-1$
} catch (DebugException e) {
JDIDebugPlugin.log(e);
return;
}
fThread.start();
} else {
notify();
}
}
}
/**
* Returns whether the queue is empty
*
* @return boolean
*/
public boolean isEmpty() {
return fRunnables.isEmpty();
}
public void clearQueue() {
synchronized (this) {
fRunnables.clear();
}
}
public void run() {
while (true) {
Runnable nextRunnable= null;
synchronized (this) {
if (fRunnables.isEmpty()) {
try {
wait(5000);
} catch (InterruptedException e1) {
}
}
if (fRunnables.isEmpty()) {
fThread= null;
return;
} else {
nextRunnable= (Runnable)fRunnables.remove(0);
}
}
try {
nextRunnable.run();
} catch (Throwable e) {
JDIDebugPlugin.log(e);
}
}
}
}
}
| true | true | protected synchronized List computeStackFrames(boolean refreshChildren) throws DebugException {
if (isSuspended()) {
if (isTerminated()) {
fStackFrames = Collections.EMPTY_LIST;
} else if (refreshChildren) {
if (fStackFrames.isEmpty()) {
fStackFrames = createAllStackFrames();
if (fStackFrames.isEmpty()) {
//leave fRefreshChildren == true
//bug 6393
return fStackFrames;
}
}
int stackSize = getUnderlyingFrameCount();
boolean topDown = false;
// what was the last method on the top of the stack
JDIStackFrame topStackFrame = (JDIStackFrame)fStackFrames.get(0);
Method lastMethod = topStackFrame.getLastMethod();
// what is the method on top of the stack now
if (stackSize > 0) {
Method currMethod = getUnderlyingFrame(0).location().method();
if (currMethod.equals(lastMethod)) {
// preserve frames top down
topDown = true;
}
}
// compute new or removed stack frames
int offset= 0, length= stackSize;
if (length > fStackFrames.size()) {
if (topDown) {
// add new (empty) frames to the bottom of the stack to preserve frames top-down
int num = length - fStackFrames.size();
for (int i = 0; i < num; i++) {
fStackFrames.add(new JDIStackFrame(this, 0));
}
} else {
// add new frames to the top of the stack, preserve bottom up
offset= length - fStackFrames.size();
for (int i= offset - 1; i >= 0; i--) {
JDIStackFrame newStackFrame= new JDIStackFrame(this, 0);
fStackFrames.add(0, newStackFrame);
}
length= fStackFrames.size() - offset;
}
} else if (length < fStackFrames.size()) {
int removed= fStackFrames.size() - length;
if (topDown) {
// remove frames from the bottom of the stack, preserve top-down
for (int i = 0; i < removed; i++) {
fStackFrames.remove(fStackFrames.size() - 1);
}
} else {
// remove frames from the top of the stack, preserve bottom up
for (int i= 0; i < removed; i++) {
fStackFrames.remove(0);
}
}
} else if (length == 0) {
fStackFrames = Collections.EMPTY_LIST;
}
// update frame indicies
for (int i= 0; i < stackSize; i++) {
((JDIStackFrame)fStackFrames.get(i)).setDepth(i);
}
}
fRefreshChildren = false;
} else {
return Collections.EMPTY_LIST;
}
return fStackFrames;
}
| protected synchronized List computeStackFrames(boolean refreshChildren) throws DebugException {
if (isSuspended()) {
if (isTerminated()) {
fStackFrames = Collections.EMPTY_LIST;
} else if (refreshChildren) {
if (fStackFrames.isEmpty()) {
fStackFrames = createAllStackFrames();
if (fStackFrames.isEmpty()) {
//leave fRefreshChildren == true
//bug 6393
return fStackFrames;
}
}
int stackSize = getUnderlyingFrameCount();
boolean topDown = false;
// what was the last method on the top of the stack
Method lastMethod = ((JDIStackFrame)fStackFrames.get(0)).getLastMethod();
// what is the method on top of the stack now
if (stackSize > 0) {
Method currMethod = getUnderlyingFrame(0).location().method();
if (currMethod.equals(lastMethod)) {
// preserve frames top down
topDown = true;
}
}
// compute new or removed stack frames
int offset= 0, length= stackSize;
if (length > fStackFrames.size()) {
if (topDown) {
// add new (empty) frames to the bottom of the stack to preserve frames top-down
int num = length - fStackFrames.size();
for (int i = 0; i < num; i++) {
fStackFrames.add(new JDIStackFrame(this, 0));
}
} else {
// add new frames to the top of the stack, preserve bottom up
offset= length - fStackFrames.size();
for (int i= offset - 1; i >= 0; i--) {
JDIStackFrame newStackFrame= new JDIStackFrame(this, 0);
fStackFrames.add(0, newStackFrame);
}
length= fStackFrames.size() - offset;
}
} else if (length < fStackFrames.size()) {
int removed= fStackFrames.size() - length;
if (topDown) {
// remove frames from the bottom of the stack, preserve top-down
for (int i = 0; i < removed; i++) {
fStackFrames.remove(fStackFrames.size() - 1);
}
} else {
// remove frames from the top of the stack, preserve bottom up
for (int i= 0; i < removed; i++) {
fStackFrames.remove(0);
}
}
} else if (length == 0) {
fStackFrames = Collections.EMPTY_LIST;
}
// update frame indicies
for (int i= 0; i < stackSize; i++) {
((JDIStackFrame)fStackFrames.get(i)).setDepth(i);
}
}
fRefreshChildren = false;
} else {
return Collections.EMPTY_LIST;
}
return fStackFrames;
}
|
diff --git a/src/org/nutz/mvc/init/UrlMapImpl.java b/src/org/nutz/mvc/init/UrlMapImpl.java
index 9e4e415b4..ce09fdcb7 100644
--- a/src/org/nutz/mvc/init/UrlMapImpl.java
+++ b/src/org/nutz/mvc/init/UrlMapImpl.java
@@ -1,152 +1,156 @@
package org.nutz.mvc.init;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import org.nutz.ioc.Ioc;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.Context;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionInvoker;
import org.nutz.mvc.ActionInvoking;
import org.nutz.mvc.UrlMap;
import org.nutz.mvc.ViewMaker;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Encoding;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.invoker.ActionInvokerImpl;
public class UrlMapImpl implements UrlMap {
private static final Log log = Logs.getLog(UrlMapImpl.class);
private NutConfig config;
private Ioc ioc;
private PathNode<ActionInvoker> root;
private Context context;
public UrlMapImpl(NutConfig config, Context context, Class<?> mainModule) {
this.config = config;
this.ioc = config.getIoc();
this.root = new PathNode<ActionInvoker>();
this.context = context;
this.ok = mainModule.getAnnotation(Ok.class);
this.fail = mainModule.getAnnotation(Fail.class);
this.adaptBy = mainModule.getAnnotation(AdaptBy.class);
this.filters = mainModule.getAnnotation(Filters.class);
this.encoding = mainModule.getAnnotation(Encoding.class);
}
private Ok ok;
private Fail fail;
private AdaptBy adaptBy;
private Filters filters;
private Encoding encoding;
public boolean add(List<ViewMaker> makers, Class<?> moduleType) {
Ok myOk = moduleType.getAnnotation(Ok.class);
if (null == myOk)
myOk = ok;
Fail myFail = moduleType.getAnnotation(Fail.class);
if (null == myFail)
myFail = fail;
AdaptBy myAb = moduleType.getAnnotation(AdaptBy.class);
if (null == myAb)
myAb = adaptBy;
Filters myFlts = moduleType.getAnnotation(Filters.class);
if (null == myFlts)
myFlts = filters;
Encoding myEncoding = moduleType.getAnnotation(Encoding.class);
if (null == myEncoding)
myEncoding = encoding;
// get base url
At baseAt = moduleType.getAnnotation(At.class);
String[] bases;
if (null == baseAt)
bases = Lang.array("");
else if (null == baseAt.value() || baseAt.value().length == 0)
bases = Lang.array("/" + moduleType.getSimpleName().toLowerCase());
- else
+ else {
bases = baseAt.value();
+ for (int i = 0; i < bases.length; i++)
+ if (bases[i] == null || "/".equals(bases[i]))
+ bases[i] = "";
+ }
/*
* looping all methods in the class, if has one @At, this class will be
* take as 'Module'
*/
boolean isModule = false;
for (Method method : moduleType.getMethods()) {
/*
* Make sure the public method, which with @At can be take as the
* enter method
*/
if (!Modifier.isPublic(method.getModifiers()) || !method.isAnnotationPresent(At.class))
continue;
/*
* Then, check the @At
*/
At atAnn = method.getAnnotation(At.class);
isModule = true;
// Create invoker
ActionInvoker invoker = new ActionInvokerImpl( context,
ioc,
makers,
moduleType,
method,
myOk,
myFail,
myAb,
myFlts,
myEncoding);
// Mapping invoker
String actionPath = null;
for (String base : bases) {
String[] paths = atAnn.value();
// The @At without value
if ((paths.length == 1 && Strings.isBlank(paths[0])) || paths.length == 0) {
// Get the action path
actionPath = base + "/" + method.getName().toLowerCase();
root.add(actionPath, invoker);
// Print log
if (log.isDebugEnabled())
log.debug(String.format(" %20s() @(%s)", method.getName(), actionPath));
}
- // More than one value in @At
+ // Have value in @At
else {
for (String at : paths) {
// Get Action
actionPath = base + at;
root.add(actionPath, invoker);
// Print log
if (log.isDebugEnabled())
log.debug(String.format(" %20s() @(%s)", method.getName(), actionPath));
}
}
}
// If @At has 'key', it will store the $actionPath to context
if (!Strings.isBlank(atAnn.key()) && !Strings.isBlank(actionPath))
config.atMap().add(atAnn.key(), actionPath);
}
return isModule;
}
public ActionInvoking get(String path) {
PathInfo<ActionInvoker> info = root.get(path);
String[] args = Strings.splitIgnoreBlank(info.getRemain(), "[/]");
return new ActionInvoking(info, args);
}
}
| false | true | public boolean add(List<ViewMaker> makers, Class<?> moduleType) {
Ok myOk = moduleType.getAnnotation(Ok.class);
if (null == myOk)
myOk = ok;
Fail myFail = moduleType.getAnnotation(Fail.class);
if (null == myFail)
myFail = fail;
AdaptBy myAb = moduleType.getAnnotation(AdaptBy.class);
if (null == myAb)
myAb = adaptBy;
Filters myFlts = moduleType.getAnnotation(Filters.class);
if (null == myFlts)
myFlts = filters;
Encoding myEncoding = moduleType.getAnnotation(Encoding.class);
if (null == myEncoding)
myEncoding = encoding;
// get base url
At baseAt = moduleType.getAnnotation(At.class);
String[] bases;
if (null == baseAt)
bases = Lang.array("");
else if (null == baseAt.value() || baseAt.value().length == 0)
bases = Lang.array("/" + moduleType.getSimpleName().toLowerCase());
else
bases = baseAt.value();
/*
* looping all methods in the class, if has one @At, this class will be
* take as 'Module'
*/
boolean isModule = false;
for (Method method : moduleType.getMethods()) {
/*
* Make sure the public method, which with @At can be take as the
* enter method
*/
if (!Modifier.isPublic(method.getModifiers()) || !method.isAnnotationPresent(At.class))
continue;
/*
* Then, check the @At
*/
At atAnn = method.getAnnotation(At.class);
isModule = true;
// Create invoker
ActionInvoker invoker = new ActionInvokerImpl( context,
ioc,
makers,
moduleType,
method,
myOk,
myFail,
myAb,
myFlts,
myEncoding);
// Mapping invoker
String actionPath = null;
for (String base : bases) {
String[] paths = atAnn.value();
// The @At without value
if ((paths.length == 1 && Strings.isBlank(paths[0])) || paths.length == 0) {
// Get the action path
actionPath = base + "/" + method.getName().toLowerCase();
root.add(actionPath, invoker);
// Print log
if (log.isDebugEnabled())
log.debug(String.format(" %20s() @(%s)", method.getName(), actionPath));
}
// More than one value in @At
else {
for (String at : paths) {
// Get Action
actionPath = base + at;
root.add(actionPath, invoker);
// Print log
if (log.isDebugEnabled())
log.debug(String.format(" %20s() @(%s)", method.getName(), actionPath));
}
}
}
// If @At has 'key', it will store the $actionPath to context
if (!Strings.isBlank(atAnn.key()) && !Strings.isBlank(actionPath))
config.atMap().add(atAnn.key(), actionPath);
}
return isModule;
}
| public boolean add(List<ViewMaker> makers, Class<?> moduleType) {
Ok myOk = moduleType.getAnnotation(Ok.class);
if (null == myOk)
myOk = ok;
Fail myFail = moduleType.getAnnotation(Fail.class);
if (null == myFail)
myFail = fail;
AdaptBy myAb = moduleType.getAnnotation(AdaptBy.class);
if (null == myAb)
myAb = adaptBy;
Filters myFlts = moduleType.getAnnotation(Filters.class);
if (null == myFlts)
myFlts = filters;
Encoding myEncoding = moduleType.getAnnotation(Encoding.class);
if (null == myEncoding)
myEncoding = encoding;
// get base url
At baseAt = moduleType.getAnnotation(At.class);
String[] bases;
if (null == baseAt)
bases = Lang.array("");
else if (null == baseAt.value() || baseAt.value().length == 0)
bases = Lang.array("/" + moduleType.getSimpleName().toLowerCase());
else {
bases = baseAt.value();
for (int i = 0; i < bases.length; i++)
if (bases[i] == null || "/".equals(bases[i]))
bases[i] = "";
}
/*
* looping all methods in the class, if has one @At, this class will be
* take as 'Module'
*/
boolean isModule = false;
for (Method method : moduleType.getMethods()) {
/*
* Make sure the public method, which with @At can be take as the
* enter method
*/
if (!Modifier.isPublic(method.getModifiers()) || !method.isAnnotationPresent(At.class))
continue;
/*
* Then, check the @At
*/
At atAnn = method.getAnnotation(At.class);
isModule = true;
// Create invoker
ActionInvoker invoker = new ActionInvokerImpl( context,
ioc,
makers,
moduleType,
method,
myOk,
myFail,
myAb,
myFlts,
myEncoding);
// Mapping invoker
String actionPath = null;
for (String base : bases) {
String[] paths = atAnn.value();
// The @At without value
if ((paths.length == 1 && Strings.isBlank(paths[0])) || paths.length == 0) {
// Get the action path
actionPath = base + "/" + method.getName().toLowerCase();
root.add(actionPath, invoker);
// Print log
if (log.isDebugEnabled())
log.debug(String.format(" %20s() @(%s)", method.getName(), actionPath));
}
// Have value in @At
else {
for (String at : paths) {
// Get Action
actionPath = base + at;
root.add(actionPath, invoker);
// Print log
if (log.isDebugEnabled())
log.debug(String.format(" %20s() @(%s)", method.getName(), actionPath));
}
}
}
// If @At has 'key', it will store the $actionPath to context
if (!Strings.isBlank(atAnn.key()) && !Strings.isBlank(actionPath))
config.atMap().add(atAnn.key(), actionPath);
}
return isModule;
}
|
diff --git a/marathon-runtime-server/src/net/sourceforge/marathon/component/DefaultComponentResolver.java b/marathon-runtime-server/src/net/sourceforge/marathon/component/DefaultComponentResolver.java
index 120304fa..cf862589 100644
--- a/marathon-runtime-server/src/net/sourceforge/marathon/component/DefaultComponentResolver.java
+++ b/marathon-runtime-server/src/net/sourceforge/marathon/component/DefaultComponentResolver.java
@@ -1,326 +1,327 @@
/*******************************************************************************
*
* Copyright (C) 2010 Jalian Systems Private Ltd.
* Copyright (C) 2010 Contributors to Marathon OSS Project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) 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. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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
*
* Project website: http://www.marathontesting.com
* Help: Marathon help forum @ http://groups.google.com/group/marathon-testing
*
*******************************************************************************/
package net.sourceforge.marathon.component;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.swing.AbstractButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollBar;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.JTree;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.table.JTableHeader;
import javax.swing.text.JTextComponent;
import net.sourceforge.marathon.Constants;
import net.sourceforge.marathon.recorder.WindowMonitor;
/**
* An implementation of {@link ComponentResolver} that handles all standard
* Swing components. If a component can't be handled and if it is in the
* ignoreList a {@link MNullComponent} is created. Otherwise, a
* {@link MUnknownComponent} is created.
*
*/
public class DefaultComponentResolver extends ComponentResolver {
private ArrayList<IgnoreClass> ignoreClasses = new ArrayList<IgnoreClass>();
/**
* Constructs the default component resolver.
*
* @param finder
* @param isRecording
* @param windowMonitor
*/
public DefaultComponentResolver(ComponentFinder finder, boolean isRecording, WindowMonitor windowMonitor) {
super(finder, isRecording, windowMonitor);
initIgnoreClasses();
}
/**
* Initialize the ignoreClasses list.
*/
private void initIgnoreClasses() {
StringTokenizer tokenizer = new StringTokenizer(System.getProperty(Constants.PROP_IGNORE_COMPONENTS, ""), "();:");
while (tokenizer.hasMoreTokens()) {
String className = tokenizer.nextToken();
if (tokenizer.hasMoreTokens())
tokenizer.nextToken();
boolean ignoreChildren = false;
if (tokenizer.hasMoreTokens())
ignoreChildren = Boolean.valueOf(tokenizer.nextToken()).booleanValue();
else {
System.err.println("Warning: IgnoreClasses could not be parsed properly");
}
try {
ignoreClasses.add(new IgnoreClass(className, ignoreChildren));
} catch (ClassNotFoundException e) {
System.err.println("Warning: IgnoreComponents - could not find class for " + className);
}
}
}
/*
* (non-Javadoc)
*
* @see
* net.sourceforge.marathon.component.ComponentResolver#canHandle(java.awt
* .Component)
*
* We handle all components
*/
public boolean canHandle(Component component) {
return true;
}
/*
* (non-Javadoc)
*
* @see
* net.sourceforge.marathon.component.ComponentResolver#canHandle(java.awt
* .Component, java.awt.Point)
*
* We handle all components wherever they are.
*/
public boolean canHandle(Component component, Point location) {
return true;
}
/*
* (non-Javadoc)
*
* @see
* net.sourceforge.marathon.component.ComponentResolver#getComponent(java
* .awt.Component, java.awt.Point)
*/
public Component getComponent(Component component, Point location) {
Component parent = component.getParent();
Component grandparent = parent != null ? parent.getParent() : null;
Component greatgrandparent = grandparent != null ? grandparent.getParent() : null;
Component realComponent = component;
if (getColorChooser(component) != null) {
realComponent = getColorChooser(component);
} else if (getFileChooser(component) != null) {
realComponent = getFileChooser(component);
} else if (component.getClass().getName().indexOf("ScrollableTabPanel") > 0) {
// See: testTabbedPaneWhenInScrollTabLayout
realComponent = grandparent;
} else if (component instanceof JTableHeader) {
} else if (component instanceof JProgressBar) {
} else if (component instanceof JSlider) {
} else if (parent instanceof JTable) {
setLocationForTable((JTable) parent, location);
realComponent = getComponent(parent, location);
} else if (parent instanceof JComboBox) {
realComponent = getComponent(parent, location);
} else if (greatgrandparent instanceof ComboPopup) {
realComponent = null;
if (greatgrandparent instanceof BasicComboPopup)
realComponent = getComponent(((BasicComboPopup) greatgrandparent).getInvoker(), location);
} else if (component instanceof ComboPopup) {
realComponent = null;
if (component instanceof BasicComboPopup)
realComponent = getComponent(((BasicComboPopup) component).getInvoker(), location);
} else if (parent instanceof JSpinner) {
realComponent = parent;
} else if (grandparent instanceof JSpinner) {
realComponent = grandparent;
} else if (grandparent instanceof JTree) {
realComponent = grandparent;
} else if (parent instanceof JTree) {
realComponent = parent;
}
return realComponent;
}
private JColorChooser getColorChooser(Component component) {
Component parent = component;
while (parent != null) {
if (parent instanceof JColorChooser)
return (JColorChooser) parent;
parent = parent.getParent();
}
return null;
}
private JFileChooser getFileChooser(Component component) {
Component parent = component;
while (parent != null) {
if (parent instanceof JFileChooser)
return (JFileChooser) parent;
parent = parent.getParent();
}
return null;
}
/**
* Do we need to ignore this component?
*
* @param component
* @return
*/
private boolean ignoreClass(Component component) {
for (Iterator<IgnoreClass> iter = ignoreClasses.iterator(); iter.hasNext();) {
IgnoreClass element = (IgnoreClass) iter.next();
if (element.matches(component))
return true;
}
return false;
}
/**
* Sets the location to a point the table.
*
* @param table
* @param location
*/
private void setLocationForTable(JTable table, Point location) {
if (location != null) {
Rectangle cellRect = table.getCellRect(table.getEditingRow(), table.getEditingColumn(), false);
location.setLocation(cellRect.getLocation());
}
}
/*
* (non-Javadoc)
*
* @see
* net.sourceforge.marathon.component.ComponentResolver#getMComponent(java
* .awt.Component, java.lang.String, java.lang.Object)
*/
public MComponent getMComponent(Component component, String name, Object obj) {
if (component instanceof JColorChooser) {
return new MColorChooser(component, name, getFinder(), windowMonitor);
} else if (component instanceof JFileChooser) {
return new MFileChooser(component, name, getFinder(), windowMonitor);
} else if (component instanceof JTableHeader) {
JTableHeader header = (JTableHeader) component;
if (obj instanceof Point) {
Point location = (Point) obj;
return new MTableHeaderItem(header, name, header.columnAtPoint(location), getFinder(), windowMonitor);
} else
return new MTableHeaderItem(header, name, obj.toString(), getFinder(), windowMonitor);
} else if (component instanceof JMenu && component.getParent().getClass() != JPopupMenu.class) {
return new MMenu(component, name, getFinder(), windowMonitor);
} else if (component instanceof JProgressBar) {
return new MProgressBar(component, name, getFinder(), windowMonitor);
} else if (component instanceof JSlider) {
return new MSlider(component, name, getFinder(), windowMonitor);
} else if (component instanceof JSpinner) {
return new MSpinner(component, name, getFinder(), windowMonitor);
} else if (component instanceof JLabel) {
return new MLabel((JLabel) component, name, getFinder(), windowMonitor);
} else if (component instanceof JToggleButton) {
return new MToggleButton((JToggleButton) component, name, getFinder(), windowMonitor);
} else if (component instanceof AbstractButton) {
return new MButton((AbstractButton) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTextComponent) {
if (component instanceof JEditorPane)
return new MEditorPane((JEditorPane) component, name, obj, getFinder(), windowMonitor);
return new MTextComponent(component, name, getFinder(), windowMonitor);
} else if (component instanceof JComboBox) {
return new MComboBox((JComboBox) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTabbedPane) {
return new MTabbedPane((JTabbedPane) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTable) {
if (isRecording() && obj == null) {
JTable table = (JTable) component;
Rectangle rect;
if (table.isEditing())
rect = table.getCellRect(table.getEditingRow(), table.getEditingColumn(), false);
else
rect = table.getCellRect(table.getSelectedRow(), table.getSelectedColumn(), false);
if (rect.equals(new Rectangle()))
return new MTable((JTable) component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null) {
return new MTable((JTable) component, name, getFinder(), windowMonitor);
}
}
try {
return new MTableCell((JTable) component, name, obj, getFinder(), windowMonitor);
} catch (ComponentException e) {
if (obj instanceof String)
throw e;
return new MTable((JTable) component, name, getFinder(), windowMonitor);
}
} else if (component instanceof JList) {
+ System.out.println("DefaultComponentResolver.getMComponent(): " + obj);
JList list = (JList) component;
if (isRecording() && obj == null) {
Rectangle rect = list.getCellBounds(list.getSelectedIndex(), list.getSelectedIndex());
if (rect == null)
return new MList(component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
- if (obj == null || list.getModel().getSize() == 0) {
+ if (obj == null) {
return new MList(component, name, getFinder(), windowMonitor);
}
}
return new MListCell((JList) component, name, obj, getFinder(), windowMonitor);
} else if (component instanceof JTree) {
if (isRecording() && obj == null) {
JTree tree = (JTree) component;
int[] rows = tree.getSelectionRows();
if (rows == null || rows.length != 1) {
return new MTree(component, name, getFinder(), windowMonitor);
}
Rectangle rect = tree.getRowBounds(rows[0]);
if (rect == null)
return new MTree(component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null)
return new MTree(component, name, getFinder(), windowMonitor);
}
return new MTreeNode(component, name, obj, getFinder(), windowMonitor);
} else if (component instanceof JScrollBar) {
return new MNullComponent(component, name, getFinder(), windowMonitor);
} else if (ignoreClass(component)) {
return new MNullComponent(component, name, getFinder(), windowMonitor);
} else {
return new MUnknownComponent(component, name, getFinder(), windowMonitor);
}
}
}
| false | true | public MComponent getMComponent(Component component, String name, Object obj) {
if (component instanceof JColorChooser) {
return new MColorChooser(component, name, getFinder(), windowMonitor);
} else if (component instanceof JFileChooser) {
return new MFileChooser(component, name, getFinder(), windowMonitor);
} else if (component instanceof JTableHeader) {
JTableHeader header = (JTableHeader) component;
if (obj instanceof Point) {
Point location = (Point) obj;
return new MTableHeaderItem(header, name, header.columnAtPoint(location), getFinder(), windowMonitor);
} else
return new MTableHeaderItem(header, name, obj.toString(), getFinder(), windowMonitor);
} else if (component instanceof JMenu && component.getParent().getClass() != JPopupMenu.class) {
return new MMenu(component, name, getFinder(), windowMonitor);
} else if (component instanceof JProgressBar) {
return new MProgressBar(component, name, getFinder(), windowMonitor);
} else if (component instanceof JSlider) {
return new MSlider(component, name, getFinder(), windowMonitor);
} else if (component instanceof JSpinner) {
return new MSpinner(component, name, getFinder(), windowMonitor);
} else if (component instanceof JLabel) {
return new MLabel((JLabel) component, name, getFinder(), windowMonitor);
} else if (component instanceof JToggleButton) {
return new MToggleButton((JToggleButton) component, name, getFinder(), windowMonitor);
} else if (component instanceof AbstractButton) {
return new MButton((AbstractButton) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTextComponent) {
if (component instanceof JEditorPane)
return new MEditorPane((JEditorPane) component, name, obj, getFinder(), windowMonitor);
return new MTextComponent(component, name, getFinder(), windowMonitor);
} else if (component instanceof JComboBox) {
return new MComboBox((JComboBox) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTabbedPane) {
return new MTabbedPane((JTabbedPane) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTable) {
if (isRecording() && obj == null) {
JTable table = (JTable) component;
Rectangle rect;
if (table.isEditing())
rect = table.getCellRect(table.getEditingRow(), table.getEditingColumn(), false);
else
rect = table.getCellRect(table.getSelectedRow(), table.getSelectedColumn(), false);
if (rect.equals(new Rectangle()))
return new MTable((JTable) component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null) {
return new MTable((JTable) component, name, getFinder(), windowMonitor);
}
}
try {
return new MTableCell((JTable) component, name, obj, getFinder(), windowMonitor);
} catch (ComponentException e) {
if (obj instanceof String)
throw e;
return new MTable((JTable) component, name, getFinder(), windowMonitor);
}
} else if (component instanceof JList) {
JList list = (JList) component;
if (isRecording() && obj == null) {
Rectangle rect = list.getCellBounds(list.getSelectedIndex(), list.getSelectedIndex());
if (rect == null)
return new MList(component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null || list.getModel().getSize() == 0) {
return new MList(component, name, getFinder(), windowMonitor);
}
}
return new MListCell((JList) component, name, obj, getFinder(), windowMonitor);
} else if (component instanceof JTree) {
if (isRecording() && obj == null) {
JTree tree = (JTree) component;
int[] rows = tree.getSelectionRows();
if (rows == null || rows.length != 1) {
return new MTree(component, name, getFinder(), windowMonitor);
}
Rectangle rect = tree.getRowBounds(rows[0]);
if (rect == null)
return new MTree(component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null)
return new MTree(component, name, getFinder(), windowMonitor);
}
return new MTreeNode(component, name, obj, getFinder(), windowMonitor);
} else if (component instanceof JScrollBar) {
return new MNullComponent(component, name, getFinder(), windowMonitor);
} else if (ignoreClass(component)) {
return new MNullComponent(component, name, getFinder(), windowMonitor);
} else {
return new MUnknownComponent(component, name, getFinder(), windowMonitor);
}
}
| public MComponent getMComponent(Component component, String name, Object obj) {
if (component instanceof JColorChooser) {
return new MColorChooser(component, name, getFinder(), windowMonitor);
} else if (component instanceof JFileChooser) {
return new MFileChooser(component, name, getFinder(), windowMonitor);
} else if (component instanceof JTableHeader) {
JTableHeader header = (JTableHeader) component;
if (obj instanceof Point) {
Point location = (Point) obj;
return new MTableHeaderItem(header, name, header.columnAtPoint(location), getFinder(), windowMonitor);
} else
return new MTableHeaderItem(header, name, obj.toString(), getFinder(), windowMonitor);
} else if (component instanceof JMenu && component.getParent().getClass() != JPopupMenu.class) {
return new MMenu(component, name, getFinder(), windowMonitor);
} else if (component instanceof JProgressBar) {
return new MProgressBar(component, name, getFinder(), windowMonitor);
} else if (component instanceof JSlider) {
return new MSlider(component, name, getFinder(), windowMonitor);
} else if (component instanceof JSpinner) {
return new MSpinner(component, name, getFinder(), windowMonitor);
} else if (component instanceof JLabel) {
return new MLabel((JLabel) component, name, getFinder(), windowMonitor);
} else if (component instanceof JToggleButton) {
return new MToggleButton((JToggleButton) component, name, getFinder(), windowMonitor);
} else if (component instanceof AbstractButton) {
return new MButton((AbstractButton) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTextComponent) {
if (component instanceof JEditorPane)
return new MEditorPane((JEditorPane) component, name, obj, getFinder(), windowMonitor);
return new MTextComponent(component, name, getFinder(), windowMonitor);
} else if (component instanceof JComboBox) {
return new MComboBox((JComboBox) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTabbedPane) {
return new MTabbedPane((JTabbedPane) component, name, getFinder(), windowMonitor);
} else if (component instanceof JTable) {
if (isRecording() && obj == null) {
JTable table = (JTable) component;
Rectangle rect;
if (table.isEditing())
rect = table.getCellRect(table.getEditingRow(), table.getEditingColumn(), false);
else
rect = table.getCellRect(table.getSelectedRow(), table.getSelectedColumn(), false);
if (rect.equals(new Rectangle()))
return new MTable((JTable) component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null) {
return new MTable((JTable) component, name, getFinder(), windowMonitor);
}
}
try {
return new MTableCell((JTable) component, name, obj, getFinder(), windowMonitor);
} catch (ComponentException e) {
if (obj instanceof String)
throw e;
return new MTable((JTable) component, name, getFinder(), windowMonitor);
}
} else if (component instanceof JList) {
System.out.println("DefaultComponentResolver.getMComponent(): " + obj);
JList list = (JList) component;
if (isRecording() && obj == null) {
Rectangle rect = list.getCellBounds(list.getSelectedIndex(), list.getSelectedIndex());
if (rect == null)
return new MList(component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null) {
return new MList(component, name, getFinder(), windowMonitor);
}
}
return new MListCell((JList) component, name, obj, getFinder(), windowMonitor);
} else if (component instanceof JTree) {
if (isRecording() && obj == null) {
JTree tree = (JTree) component;
int[] rows = tree.getSelectionRows();
if (rows == null || rows.length != 1) {
return new MTree(component, name, getFinder(), windowMonitor);
}
Rectangle rect = tree.getRowBounds(rows[0]);
if (rect == null)
return new MTree(component, name, getFinder(), windowMonitor);
obj = new Point((int) rect.getCenterX(), (int) rect.getCenterY());
} else {
if (obj == null)
return new MTree(component, name, getFinder(), windowMonitor);
}
return new MTreeNode(component, name, obj, getFinder(), windowMonitor);
} else if (component instanceof JScrollBar) {
return new MNullComponent(component, name, getFinder(), windowMonitor);
} else if (ignoreClass(component)) {
return new MNullComponent(component, name, getFinder(), windowMonitor);
} else {
return new MUnknownComponent(component, name, getFinder(), windowMonitor);
}
}
|
diff --git a/plugins/chrome-navigation/src/android/ChromeNavigation.java b/plugins/chrome-navigation/src/android/ChromeNavigation.java
index 1c19e9c..45b59e6 100644
--- a/plugins/chrome-navigation/src/android/ChromeNavigation.java
+++ b/plugins/chrome-navigation/src/android/ChromeNavigation.java
@@ -1,33 +1,28 @@
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaPlugin;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
public class ChromeNavigation extends CordovaPlugin {
private static final String LOG_TAG = "ChromeNavigation";
@Override
public boolean onOverrideUrlLoading(String url) {
if (url.startsWith("http:") || url.startsWith("https:")) {
Log.i(LOG_TAG, "Opening URL in external browser: " + url);
Intent systemBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
cordova.getActivity().startActivity(systemBrowserIntent);
return true;
- } else if (url.startsWith("chrome-extension:")) {
- // Assume this is someone refreshing via remote debugger.
- Log.i(LOG_TAG, "location.reload() detected. Reloading via chromeapp.html");
- webView.loadUrl(Config.getStartUrl());
- return true;
}
return false;
}
}
| true | true | public boolean onOverrideUrlLoading(String url) {
if (url.startsWith("http:") || url.startsWith("https:")) {
Log.i(LOG_TAG, "Opening URL in external browser: " + url);
Intent systemBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
cordova.getActivity().startActivity(systemBrowserIntent);
return true;
} else if (url.startsWith("chrome-extension:")) {
// Assume this is someone refreshing via remote debugger.
Log.i(LOG_TAG, "location.reload() detected. Reloading via chromeapp.html");
webView.loadUrl(Config.getStartUrl());
return true;
}
return false;
}
| public boolean onOverrideUrlLoading(String url) {
if (url.startsWith("http:") || url.startsWith("https:")) {
Log.i(LOG_TAG, "Opening URL in external browser: " + url);
Intent systemBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
cordova.getActivity().startActivity(systemBrowserIntent);
return true;
}
return false;
}
|
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java
index db656bd81..1c212bbf4 100644
--- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java
+++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java
@@ -1,400 +1,402 @@
/*
*************************************************************************
* Copyright (c) 2006 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.report.data.adapter.impl;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.querydefn.BaseDataSetDesign;
import org.eclipse.birt.data.engine.api.querydefn.BaseDataSourceDesign;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ColumnDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ComputedColumn;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.ParameterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SortDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ColumnAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ComputedColumnAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ConditionAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ExpressionAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.FilterAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.GroupAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.InputParamBindingAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.JointDataSetAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.OdaDataSetAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.OdaDataSourceAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ParameterAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ScriptDataSetAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ScriptDataSourceAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.SortAdapter;
import org.eclipse.birt.report.model.api.AggregationArgumentHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSetParameterHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSourceHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ScriptDataSetHandle;
import org.eclipse.birt.report.model.api.ScriptDataSourceHandle;
import org.eclipse.birt.report.model.api.SortKeyHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument;
import org.mozilla.javascript.Scriptable;
/**
* An adaptor to create Data Engine request objects based on Model element definitions
*/
public class ModelAdapter implements IModelAdapter
{
private static Logger logger = Logger.getLogger( ModelAdapter.class.getName( ) );
DataSessionContext context;
public ModelAdapter( DataSessionContext context)
{
this.context = context;
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptDataSource(org.eclipse.birt.report.model.api.DataSourceHandle)
*/
public BaseDataSourceDesign adaptDataSource( DataSourceHandle handle ) throws BirtException
{
if ( handle instanceof OdaDataSourceHandle )
{
// If an external top level scope is available (i.e., our
// consumer
// is the report engine), use it to resolve property bindings.
// Otherwise
// property bindings are not resolved
Scriptable propBindingScope = context.hasExternalScope( )
? context.getTopScope( ) : null;
return new OdaDataSourceAdapter( (OdaDataSourceHandle) handle,
propBindingScope );
}
if ( handle instanceof ScriptDataSourceHandle )
{
return new ScriptDataSourceAdapter( (ScriptDataSourceHandle) handle );
}
logger.warning( "handle type: " + (handle == null ? "" : handle.getClass( ).getName( )) ); //$NON-NLS-1$
return null;
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptDataSet(org.eclipse.birt.report.model.api.DataSetHandle)
*/
public BaseDataSetDesign adaptDataSet( DataSetHandle handle ) throws BirtException
{
if ( handle instanceof OdaDataSetHandle )
{
// If an external top level scope is available (i.e., our
// consumer
// is the report engine), use it to resolve property bindings.
// Otherwise
// property bindings are not resolved
Scriptable propBindingScope = context.hasExternalScope( )
? context.getTopScope( ) : null;
return new OdaDataSetAdapter( (OdaDataSetHandle) handle,
propBindingScope,
this );
}
if ( handle instanceof ScriptDataSetHandle )
return new ScriptDataSetAdapter( (ScriptDataSetHandle) handle, this );
if ( handle instanceof JointDataSetHandle )
return new JointDataSetAdapter( (JointDataSetHandle) handle, this );
logger.warning( "handle type: " + (handle == null ? "" : handle.getClass( ).getName( )) ); //$NON-NLS-1$
return null;
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptConditionalExpression(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public ConditionalExpression adaptConditionalExpression(
String mainExpr, String operator, String operand1, String operand2 )
{
return new ConditionAdapter( mainExpr, operator, operand1, operand2);
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptExpression(java.lang.String, java.lang.String)
*/
public ScriptExpression adaptExpression( Expression expr, String dataType )
{
if( expr == null || expr.getStringExpression( ) == null )
return null;
return new ExpressionAdapter( expr, dataType );
}
/* *//**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptExpression(org.eclipse.birt.report.model.api.ComputedColumnHandle)
*//*
public ScriptExpression adaptExpression( ComputedColumnHandle ccHandle )
{
return new ExpressionAdapter( ccHandle );
}
*/
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptFilter(org.eclipse.birt.report.model.api.FilterConditionHandle)
*/
public FilterDefinition adaptFilter( FilterConditionHandle modelFilter )
{
try
{
return new FilterAdapter( this, modelFilter );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptGroup(org.eclipse.birt.report.model.api.GroupHandle)
*/
public GroupDefinition adaptGroup( GroupHandle groupHandle )
{
try
{
return new GroupAdapter( this, groupHandle );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptSort(org.eclipse.birt.report.model.api.SortKeyHandle)
*/
public SortDefinition adaptSort( SortKeyHandle sortHandle )
{
try
{
return new SortAdapter( this, sortHandle );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptSort(java.lang.String, java.lang.String)
*/
public SortDefinition adaptSort( Expression expr, String direction )
{
try
{
return new SortAdapter( this, expr, direction );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptParameter(org.eclipse.birt.report.model.api.DataSetParameterHandle)
*/
public ParameterDefinition adaptParameter( DataSetParameterHandle paramHandle )
{
return new ParameterAdapter( paramHandle );
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptInputParamBinding(org.eclipse.birt.report.model.api.ParamBindingHandle)
*/
public InputParameterBinding adaptInputParamBinding( ParamBindingHandle modelHandle )
{
try
{
return new InputParamBindingAdapter( this, modelHandle);
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#ColumnAdaptor(org.eclipse.birt.report.model.api.ResultSetColumnHandle)
*/
public ColumnDefinition ColumnAdaptor( ResultSetColumnHandle modelColumn )
{
return new ColumnAdapter( modelColumn);
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptComputedColumn(org.eclipse.birt.report.model.api.ComputedColumnHandle)
*/
public ComputedColumn adaptComputedColumn( ComputedColumnHandle modelHandle ) throws AdapterException
{
return new ComputedColumnAdapter( this, modelHandle);
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptBinding(org.eclipse.birt.report.model.api.ComputedColumnHandle)
*/
public IBinding adaptBinding( ComputedColumnHandle handle )
{
try
{
if ( handle == null )
return null;
Binding result = new Binding( handle.getName( ) );
if ( handle.getExpression( ) != null )
{
ScriptExpression expr = this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.EXPRESSION_MEMBER )
.getValue( ),
handle.getDataType( ) );
expr.setGroupName( handle.getAggregateOn( ) );
result.setExpression( expr );
}
- result.setDisplayName( handle.getDisplayName( ) );
+ result.setDisplayName( handle.getExternalizedValue( handle.getDisplayNameID( ),
+ handle.getDisplayName( ),
+ this.context.getDataEngineContext( ).getLocale( ) ) );
result.setDataType( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelDataType( handle.getDataType( ) ) );
result.setAggrFunction( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelAggregationType( handle.getAggregateFunction( ) ) );
result.setFilter( handle.getFilterExpression( ) == null
? null
: this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.FILTER_MEMBER )
.getValue( ),
DesignChoiceConstants.COLUMN_DATA_TYPE_BOOLEAN ) );
populateArgument( result, handle );
populateAggregateOns( result, handle );
return result;
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
*
* @param handle
* @param result
* @throws AdapterException
*/
private void populateAggregateOns( IBinding result,
ComputedColumnHandle handle ) throws AdapterException
{
List aggrOns = handle.getAggregateOnList( );
if ( aggrOns == null )
return;
for ( int i = 0; i < aggrOns.size( ); i++ )
{
try
{
result.addAggregateOn( aggrOns.get( i ).toString( ) );
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
}
/**
*
* @param binding
* @param modelCmptdColumn
* @throws AdapterException
*/
private void populateArgument( IBinding binding,
ComputedColumnHandle modelCmptdColumn ) throws AdapterException
{
Iterator it = modelCmptdColumn.argumentsIterator( );
while ( it != null && it.hasNext( ) )
{
AggregationArgumentHandle arg = (AggregationArgumentHandle) it.next( );
try
{
Expression expr = (Expression)arg.getExpressionProperty( AggregationArgument.VALUE_MEMBER ).getValue( );
binding.addArgument( this.adaptExpression( expr ));
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
}
public ConditionalExpression adaptConditionalExpression(
Expression mainExpr, String operator,
Expression operand1, Expression operand2 )
{
return new ConditionAdapter( this.adaptExpression( mainExpr ), operator, this.adaptExpression( operand1 ), this.adaptExpression( operand2 ));
}
public ScriptExpression adaptExpression( Expression expr )
{
if( expr == null || expr.getStringExpression( ) == null)
return null;
return new ExpressionAdapter( expr );
}
public ScriptExpression adaptExpression( String jsExpr, String dataType )
{
if( jsExpr == null )
return null;
return new ExpressionAdapter( jsExpr, dataType );
}
public ScriptExpression adaptJSExpression( String jsExpr, String dataType )
{
if( jsExpr == null )
return null;
return new ExpressionAdapter( jsExpr, dataType );
}
}
| true | true | public IBinding adaptBinding( ComputedColumnHandle handle )
{
try
{
if ( handle == null )
return null;
Binding result = new Binding( handle.getName( ) );
if ( handle.getExpression( ) != null )
{
ScriptExpression expr = this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.EXPRESSION_MEMBER )
.getValue( ),
handle.getDataType( ) );
expr.setGroupName( handle.getAggregateOn( ) );
result.setExpression( expr );
}
result.setDisplayName( handle.getDisplayName( ) );
result.setDataType( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelDataType( handle.getDataType( ) ) );
result.setAggrFunction( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelAggregationType( handle.getAggregateFunction( ) ) );
result.setFilter( handle.getFilterExpression( ) == null
? null
: this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.FILTER_MEMBER )
.getValue( ),
DesignChoiceConstants.COLUMN_DATA_TYPE_BOOLEAN ) );
populateArgument( result, handle );
populateAggregateOns( result, handle );
return result;
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
| public IBinding adaptBinding( ComputedColumnHandle handle )
{
try
{
if ( handle == null )
return null;
Binding result = new Binding( handle.getName( ) );
if ( handle.getExpression( ) != null )
{
ScriptExpression expr = this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.EXPRESSION_MEMBER )
.getValue( ),
handle.getDataType( ) );
expr.setGroupName( handle.getAggregateOn( ) );
result.setExpression( expr );
}
result.setDisplayName( handle.getExternalizedValue( handle.getDisplayNameID( ),
handle.getDisplayName( ),
this.context.getDataEngineContext( ).getLocale( ) ) );
result.setDataType( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelDataType( handle.getDataType( ) ) );
result.setAggrFunction( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelAggregationType( handle.getAggregateFunction( ) ) );
result.setFilter( handle.getFilterExpression( ) == null
? null
: this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.FILTER_MEMBER )
.getValue( ),
DesignChoiceConstants.COLUMN_DATA_TYPE_BOOLEAN ) );
populateArgument( result, handle );
populateAggregateOns( result, handle );
return result;
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
|
diff --git a/cocos2d-android/src/org/cocos2d/layers/CCTMXMapInfo.java b/cocos2d-android/src/org/cocos2d/layers/CCTMXMapInfo.java
index 463f91c..cdb4c6c 100644
--- a/cocos2d-android/src/org/cocos2d/layers/CCTMXMapInfo.java
+++ b/cocos2d-android/src/org/cocos2d/layers/CCTMXMapInfo.java
@@ -1,461 +1,463 @@
package org.cocos2d.layers;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.cocos2d.config.ccMacros;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.utils.Base64;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
/* CCTMXMapInfo contains the information about the map like:
- Map orientation (hexagonal, isometric or orthogonal)
- Tile size
- Map size
And it also contains:
- Layers (an array of TMXLayerInfo objects)
- Tilesets (an array of TMXTilesetInfo objects)
- ObjectGroups (an array of TMXObjectGroupInfo objects)
This information is obtained from the TMX file.
*/
public class CCTMXMapInfo {
public final static String LOG_TAG = CCTMXMapInfo.class.getSimpleName();
public final static int TMXLayerAttribNone = 1 << 0;
public final static int TMXLayerAttribBase64 = 1 << 1;
public final static int TMXLayerAttribGzip = 1 << 2;
public final static int TMXPropertyNone = 0;
public final static int TMXPropertyMap = 1;
public final static int TMXPropertyLayer= 2;
public final static int TMXPropertyObjectGroup = 3;
public final static int TMXPropertyObject = 4;
public final static int TMXPropertyTile = 5;
protected StringBuilder currentString;
protected boolean storingCharacters;
protected int layerAttribs;
protected int parentElement;
protected int parentGID;
// tmx filename
public String filename;
// map orientation
public int orientation;
// map width & height
public CGSize mapSize;
// tiles width & height
public CGSize tileSize;
// Layers
public ArrayList<CCTMXLayerInfo> layers;
// tilesets
public ArrayList<CCTMXTilesetInfo> tilesets;
// ObjectGroups
public ArrayList<CCTMXObjectGroup> objectGroups;
// properties
public HashMap<String, String> properties;
// tile properties
public HashMap<String, HashMap<String, String>> tileProperties;
/** creates a TMX Format with a tmx file */
public static CCTMXMapInfo formatWithTMXFile(String tmxFile) {
return new CCTMXMapInfo(tmxFile);
}
/** initializes a TMX format witha tmx file */
protected CCTMXMapInfo(String tmxFile) {
super();
tilesets= new ArrayList<CCTMXTilesetInfo>();
layers = new ArrayList<CCTMXLayerInfo>();
filename = tmxFile;
objectGroups = new ArrayList<CCTMXObjectGroup>();
properties = new HashMap<String, String>();
tileProperties = new HashMap<String, HashMap<String, String> >();
// tmp vars
currentString = new StringBuilder();
storingCharacters = false;
layerAttribs = TMXLayerAttribNone;
parentElement = TMXPropertyNone;
parseXMLFile(filename);
}
/* initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */
private void parseXMLFile(String xmlFilename) {
try {
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser parser = saxFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
InputStream is = CCDirector.sharedDirector().getActivity().getResources().getAssets().open(xmlFilename);
BufferedReader in = new BufferedReader(new InputStreamReader(is));
CCTMXXMLParser handler = new CCTMXXMLParser();
reader.setContentHandler(handler);
reader.parse(new InputSource(in));
} catch(Exception e) {
Log.e(LOG_TAG, e.getStackTrace().toString());
}
/*
// we'll do the parsing
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
NSAssert1( ! [parser parserError], @"Error parsing file: %@.", xmlFilename );
[parser release];
*/
}
/*
* Internal TMX parser
*
* IMPORTANT: These classed should not be documented using doxygen strings
* since the user should not use them.
*
*/
class CCTMXXMLParser extends DefaultHandler {
@Override
public void startDocument() {
// myList = new ArrayList<HashMap<String, String>>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (localName.equals("map")) {
String version = attributes.getValue("version");
if (! version.equals("1.0")) {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TMXFormat: Unsupported TMX version: " + version);
}
String orientationStr = attributes.getValue("orientation");
if (orientationStr.equals("orthogonal")) {
orientation = CCTMXTiledMap.CCTMXOrientationOrtho;
} else if (orientationStr.equals("isometric")) {
orientation = CCTMXTiledMap.CCTMXOrientationIso;
} else if (orientationStr.equals("hexagonal")) {
orientation = CCTMXTiledMap.CCTMXOrientationHex;
} else {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TMXFomat: Unsupported orientation: " + orientation);
}
mapSize = CGSize.make(Integer.parseInt(attributes.getValue("width")),
Integer.parseInt(attributes.getValue("height")));
tileSize = CGSize.make(Integer.parseInt(attributes.getValue("tilewidth")),
Integer.parseInt(attributes.getValue("tileheight")));
// The parent element is now "map"
parentElement = TMXPropertyMap;
} else if (localName.equals("tileset")) {
// If this is an external tileset then start parsing that
String externalTilesetFilename = attributes.getValue("source");
if (externalTilesetFilename != null) {
// Tileset file will be relative to the map file. So we need to convert it to an absolute path
String dir = filename.substring(0, filename.lastIndexOf("/"));
externalTilesetFilename = dir + "/" + externalTilesetFilename; // Append path to tileset file
CCTMXMapInfo.this.parseXMLFile(externalTilesetFilename);
} else {
CCTMXTilesetInfo tileset = new CCTMXTilesetInfo();
tileset.name = attributes.getValue("name");
tileset.firstGid = Integer.parseInt(attributes.getValue("firstgid"));
- tileset.spacing = Integer.parseInt(attributes.getValue("spacing"));
- tileset.margin = Integer.parseInt(attributes.getValue("margin"));
- CGSize s = CGSize.zero();
+ String value = attributes.getValue("spacing");
+ tileset.spacing = value== null?0:Integer.parseInt(value);
+ value = attributes.getValue("margin") ;
+ tileset.margin = value== null?0:Integer.parseInt(value);
+ CGSize s = CGSize.zero();
s.width = Integer.parseInt(attributes.getValue("tilewidth"));
s.height = Integer.parseInt(attributes.getValue("tileheight"));
tileset.tileSize = s;
tilesets.add(tileset);
}
} else if (localName.equals("tile")) {
CCTMXTilesetInfo info = tilesets.get(tilesets.size()-1);
HashMap<String, String> dict = new HashMap<String, String>();
parentGID = info.firstGid + Integer.parseInt(attributes.getValue("id"));
tileProperties.put(String.valueOf(parentGID), dict);
parentElement = TMXPropertyTile;
} else if (localName.equals("layer")) {
CCTMXLayerInfo layer = new CCTMXLayerInfo();
layer.name = attributes.getValue("name");
CGSize s = CGSize.zero();
s.width = Integer.parseInt(attributes.getValue("width"));
s.height = Integer.parseInt(attributes.getValue("height"));
layer.layerSize = s;
String visible = attributes.getValue("visible");
layer.visible = visible==null||!(visible.equals("0"));
if (attributes.getValue("opacity") != null) {
layer.opacity = (int) (255 * Float.parseFloat(attributes.getValue("opacity")));
} else {
layer.opacity = 255;
}
try {
int x = Integer.parseInt(attributes.getValue("x"));
int y = Integer.parseInt(attributes.getValue("y"));
layer.offset = CGPoint.ccp(x,y);
} catch (Exception e) {
layer.offset = CGPoint.zero();
}
layers.add(layer);
// The parent element is now "layer"
parentElement = TMXPropertyLayer;
} else if (localName.equals("objectgroup")) {
CCTMXObjectGroup objectGroup = new CCTMXObjectGroup();
objectGroup.groupName = attributes.getValue("name");
CGPoint positionOffset = CGPoint.zero();
positionOffset.x = Integer.parseInt(attributes.getValue("x")) * tileSize.width;
positionOffset.y = Integer.parseInt(attributes.getValue("y")) * tileSize.height;
objectGroup.positionOffset = positionOffset;
objectGroups.add(objectGroup);
// The parent element is now "objectgroup"
parentElement = TMXPropertyObjectGroup;
} else if (localName.equals("image")) {
CCTMXTilesetInfo tileset = tilesets.get(tilesets.size()-1);
// build full path
String imagename = attributes.getValue("source");
int idx = filename.lastIndexOf("/");
if (idx != -1) {
String path = filename.substring(0, idx);
tileset.sourceImage = path + "/" + imagename;
} else {
tileset.sourceImage = imagename;
}
} else if (localName.equals("data")) {
String encoding = attributes.getValue("encoding");
String compression = attributes.getValue("compression");
if (encoding.equals("base64")) {
layerAttribs |= TMXLayerAttribBase64;
storingCharacters = true;
assert (compression==null || compression.equals("gzip")): "TMX: unsupported compression method";
if (compression.equals("gzip")) {
layerAttribs |= TMXLayerAttribGzip;
}
}
assert (layerAttribs != TMXLayerAttribNone): "TMX tile map: Only base64 and/or gzip maps are supported";
} else if (localName.equals("object")) {
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
// The value for "type" was blank or not a valid class name
// Create an instance of TMXObjectInfo to store the object and its properties
HashMap<String, String> dict = new HashMap<String, String>();
// Set the name of the object to the value for "name"
dict.put("name", attributes.getValue("name"));
// Assign all the attributes as key/name pairs in the properties dictionary
dict.put("type", attributes.getValue("type"));
int x = (int) (Integer.parseInt(attributes.getValue("x")) + objectGroup.positionOffset.x);
dict.put("x", String.valueOf(x));
int y = (int) (Integer.parseInt(attributes.getValue("y")) + objectGroup.positionOffset.y);
// Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
y = (int) ((mapSize.height * tileSize.height) - y - Integer.parseInt(attributes.getValue("height")));
dict.put("y", String.valueOf(y));
dict.put("width", attributes.getValue("width"));
dict.put("height", attributes.getValue("height"));
// Add the object to the objectGroup
objectGroup.objects.add(dict);
// The parent element is now "object"
parentElement = TMXPropertyObject;
} else if(localName.equals("property")) {
String name = attributes.getValue("name");
String value= attributes.getValue("value");
if ( parentElement == TMXPropertyNone ) {
ccMacros.CCLOG(LOG_TAG,
"TMX tile map: Parent element is unsupported. Cannot add property named '" + name + "' with value '" + value + "'");
} else if ( parentElement == TMXPropertyMap ) {
// The parent element is the map
properties.put(name, value);
} else if ( parentElement == TMXPropertyLayer ) {
// The parent element is the last layer
CCTMXLayerInfo layer = layers.get(layers.size()-1);
// Add the property to the layer
layer.properties.put(name, value);
} else if ( parentElement == TMXPropertyObjectGroup ) {
// The parent element is the last object group
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
objectGroup.properties.put(name, value);
} else if ( parentElement == TMXPropertyObject ) {
// The parent element is the last object
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
HashMap<String, String> dict = objectGroup.objects.get(objectGroup.objects.size()-1);
dict.put(name, value);
} else if ( parentElement == TMXPropertyTile ) {
HashMap<String, String> dict = tileProperties.get(String.valueOf(parentGID));
dict.put(name, value);
}
}
}
@Override
public void endElement(String uri, String elementName, String qName)
throws SAXException {
if (elementName.equals("data") && (layerAttribs&TMXLayerAttribBase64) != 0) {
storingCharacters = false;
CCTMXLayerInfo layer = layers.get(layers.size()-1);
byte[] buffer = null;
try {
buffer = Base64.decode(currentString.toString());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (buffer == null ) {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TiledMap: decode data error");
return;
}
/*if ((layerAttribs & TMXLayerAttribGzip) != 0) {
try {
byte deflated[] = new byte [1024];
GZIPInputStream gzi = new GZIPInputStream(new ByteArrayInputStream(buffer));
ByteArrayOutputStream out = new ByteArrayOutputStream();
int ln;
while ((ln = gzi.read(deflated)) > 0) {
out.write(deflated, 0, ln);
}
gzi.close();
out.close();
deflated = out.toByteArray();
ByteBuffer b = ByteBuffer.wrap(deflated);
layer.tiles = b.asIntBuffer().array();
} catch (Exception e) {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TiledMap: inflate data error");
return;
}
} else { */
// automatically ungzip, so we can make use of it directly.
try {
ByteBuffer b = ByteBuffer.wrap(buffer);
layer.tiles = b.asIntBuffer();
} catch (Exception e) {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TiledMap: inflate data error");
}
currentString = new StringBuilder();
} else if (elementName.equals("map")) {
// The map element has ended
parentElement = TMXPropertyNone;
} else if (elementName.equals("layer")) {
// The layer element has ended
parentElement = TMXPropertyNone;
} else if (elementName.equals("objectgroup")) {
// The objectgroup element has ended
parentElement = TMXPropertyNone;
} else if (elementName.equals("object")) {
// The object element has ended
parentElement = TMXPropertyNone;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (storingCharacters) {
currentString.append(ch, start, length);
}
}
@Override
public void error(SAXParseException e) {
ccMacros.CCLOG(LOG_TAG, e.getLocalizedMessage());
}
@Override
public void fatalError(SAXParseException e) {
ccMacros.CCLOG(LOG_TAG, e.getLocalizedMessage());
}
}
}
| true | true | public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (localName.equals("map")) {
String version = attributes.getValue("version");
if (! version.equals("1.0")) {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TMXFormat: Unsupported TMX version: " + version);
}
String orientationStr = attributes.getValue("orientation");
if (orientationStr.equals("orthogonal")) {
orientation = CCTMXTiledMap.CCTMXOrientationOrtho;
} else if (orientationStr.equals("isometric")) {
orientation = CCTMXTiledMap.CCTMXOrientationIso;
} else if (orientationStr.equals("hexagonal")) {
orientation = CCTMXTiledMap.CCTMXOrientationHex;
} else {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TMXFomat: Unsupported orientation: " + orientation);
}
mapSize = CGSize.make(Integer.parseInt(attributes.getValue("width")),
Integer.parseInt(attributes.getValue("height")));
tileSize = CGSize.make(Integer.parseInt(attributes.getValue("tilewidth")),
Integer.parseInt(attributes.getValue("tileheight")));
// The parent element is now "map"
parentElement = TMXPropertyMap;
} else if (localName.equals("tileset")) {
// If this is an external tileset then start parsing that
String externalTilesetFilename = attributes.getValue("source");
if (externalTilesetFilename != null) {
// Tileset file will be relative to the map file. So we need to convert it to an absolute path
String dir = filename.substring(0, filename.lastIndexOf("/"));
externalTilesetFilename = dir + "/" + externalTilesetFilename; // Append path to tileset file
CCTMXMapInfo.this.parseXMLFile(externalTilesetFilename);
} else {
CCTMXTilesetInfo tileset = new CCTMXTilesetInfo();
tileset.name = attributes.getValue("name");
tileset.firstGid = Integer.parseInt(attributes.getValue("firstgid"));
tileset.spacing = Integer.parseInt(attributes.getValue("spacing"));
tileset.margin = Integer.parseInt(attributes.getValue("margin"));
CGSize s = CGSize.zero();
s.width = Integer.parseInt(attributes.getValue("tilewidth"));
s.height = Integer.parseInt(attributes.getValue("tileheight"));
tileset.tileSize = s;
tilesets.add(tileset);
}
} else if (localName.equals("tile")) {
CCTMXTilesetInfo info = tilesets.get(tilesets.size()-1);
HashMap<String, String> dict = new HashMap<String, String>();
parentGID = info.firstGid + Integer.parseInt(attributes.getValue("id"));
tileProperties.put(String.valueOf(parentGID), dict);
parentElement = TMXPropertyTile;
} else if (localName.equals("layer")) {
CCTMXLayerInfo layer = new CCTMXLayerInfo();
layer.name = attributes.getValue("name");
CGSize s = CGSize.zero();
s.width = Integer.parseInt(attributes.getValue("width"));
s.height = Integer.parseInt(attributes.getValue("height"));
layer.layerSize = s;
String visible = attributes.getValue("visible");
layer.visible = visible==null||!(visible.equals("0"));
if (attributes.getValue("opacity") != null) {
layer.opacity = (int) (255 * Float.parseFloat(attributes.getValue("opacity")));
} else {
layer.opacity = 255;
}
try {
int x = Integer.parseInt(attributes.getValue("x"));
int y = Integer.parseInt(attributes.getValue("y"));
layer.offset = CGPoint.ccp(x,y);
} catch (Exception e) {
layer.offset = CGPoint.zero();
}
layers.add(layer);
// The parent element is now "layer"
parentElement = TMXPropertyLayer;
} else if (localName.equals("objectgroup")) {
CCTMXObjectGroup objectGroup = new CCTMXObjectGroup();
objectGroup.groupName = attributes.getValue("name");
CGPoint positionOffset = CGPoint.zero();
positionOffset.x = Integer.parseInt(attributes.getValue("x")) * tileSize.width;
positionOffset.y = Integer.parseInt(attributes.getValue("y")) * tileSize.height;
objectGroup.positionOffset = positionOffset;
objectGroups.add(objectGroup);
// The parent element is now "objectgroup"
parentElement = TMXPropertyObjectGroup;
} else if (localName.equals("image")) {
CCTMXTilesetInfo tileset = tilesets.get(tilesets.size()-1);
// build full path
String imagename = attributes.getValue("source");
int idx = filename.lastIndexOf("/");
if (idx != -1) {
String path = filename.substring(0, idx);
tileset.sourceImage = path + "/" + imagename;
} else {
tileset.sourceImage = imagename;
}
} else if (localName.equals("data")) {
String encoding = attributes.getValue("encoding");
String compression = attributes.getValue("compression");
if (encoding.equals("base64")) {
layerAttribs |= TMXLayerAttribBase64;
storingCharacters = true;
assert (compression==null || compression.equals("gzip")): "TMX: unsupported compression method";
if (compression.equals("gzip")) {
layerAttribs |= TMXLayerAttribGzip;
}
}
assert (layerAttribs != TMXLayerAttribNone): "TMX tile map: Only base64 and/or gzip maps are supported";
} else if (localName.equals("object")) {
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
// The value for "type" was blank or not a valid class name
// Create an instance of TMXObjectInfo to store the object and its properties
HashMap<String, String> dict = new HashMap<String, String>();
// Set the name of the object to the value for "name"
dict.put("name", attributes.getValue("name"));
// Assign all the attributes as key/name pairs in the properties dictionary
dict.put("type", attributes.getValue("type"));
int x = (int) (Integer.parseInt(attributes.getValue("x")) + objectGroup.positionOffset.x);
dict.put("x", String.valueOf(x));
int y = (int) (Integer.parseInt(attributes.getValue("y")) + objectGroup.positionOffset.y);
// Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
y = (int) ((mapSize.height * tileSize.height) - y - Integer.parseInt(attributes.getValue("height")));
dict.put("y", String.valueOf(y));
dict.put("width", attributes.getValue("width"));
dict.put("height", attributes.getValue("height"));
// Add the object to the objectGroup
objectGroup.objects.add(dict);
// The parent element is now "object"
parentElement = TMXPropertyObject;
} else if(localName.equals("property")) {
String name = attributes.getValue("name");
String value= attributes.getValue("value");
if ( parentElement == TMXPropertyNone ) {
ccMacros.CCLOG(LOG_TAG,
"TMX tile map: Parent element is unsupported. Cannot add property named '" + name + "' with value '" + value + "'");
} else if ( parentElement == TMXPropertyMap ) {
// The parent element is the map
properties.put(name, value);
} else if ( parentElement == TMXPropertyLayer ) {
// The parent element is the last layer
CCTMXLayerInfo layer = layers.get(layers.size()-1);
// Add the property to the layer
layer.properties.put(name, value);
} else if ( parentElement == TMXPropertyObjectGroup ) {
// The parent element is the last object group
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
objectGroup.properties.put(name, value);
} else if ( parentElement == TMXPropertyObject ) {
// The parent element is the last object
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
HashMap<String, String> dict = objectGroup.objects.get(objectGroup.objects.size()-1);
dict.put(name, value);
} else if ( parentElement == TMXPropertyTile ) {
HashMap<String, String> dict = tileProperties.get(String.valueOf(parentGID));
dict.put(name, value);
}
}
}
| public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (localName.equals("map")) {
String version = attributes.getValue("version");
if (! version.equals("1.0")) {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TMXFormat: Unsupported TMX version: " + version);
}
String orientationStr = attributes.getValue("orientation");
if (orientationStr.equals("orthogonal")) {
orientation = CCTMXTiledMap.CCTMXOrientationOrtho;
} else if (orientationStr.equals("isometric")) {
orientation = CCTMXTiledMap.CCTMXOrientationIso;
} else if (orientationStr.equals("hexagonal")) {
orientation = CCTMXTiledMap.CCTMXOrientationHex;
} else {
ccMacros.CCLOG(LOG_TAG, "cocos2d: TMXFomat: Unsupported orientation: " + orientation);
}
mapSize = CGSize.make(Integer.parseInt(attributes.getValue("width")),
Integer.parseInt(attributes.getValue("height")));
tileSize = CGSize.make(Integer.parseInt(attributes.getValue("tilewidth")),
Integer.parseInt(attributes.getValue("tileheight")));
// The parent element is now "map"
parentElement = TMXPropertyMap;
} else if (localName.equals("tileset")) {
// If this is an external tileset then start parsing that
String externalTilesetFilename = attributes.getValue("source");
if (externalTilesetFilename != null) {
// Tileset file will be relative to the map file. So we need to convert it to an absolute path
String dir = filename.substring(0, filename.lastIndexOf("/"));
externalTilesetFilename = dir + "/" + externalTilesetFilename; // Append path to tileset file
CCTMXMapInfo.this.parseXMLFile(externalTilesetFilename);
} else {
CCTMXTilesetInfo tileset = new CCTMXTilesetInfo();
tileset.name = attributes.getValue("name");
tileset.firstGid = Integer.parseInt(attributes.getValue("firstgid"));
String value = attributes.getValue("spacing");
tileset.spacing = value== null?0:Integer.parseInt(value);
value = attributes.getValue("margin") ;
tileset.margin = value== null?0:Integer.parseInt(value);
CGSize s = CGSize.zero();
s.width = Integer.parseInt(attributes.getValue("tilewidth"));
s.height = Integer.parseInt(attributes.getValue("tileheight"));
tileset.tileSize = s;
tilesets.add(tileset);
}
} else if (localName.equals("tile")) {
CCTMXTilesetInfo info = tilesets.get(tilesets.size()-1);
HashMap<String, String> dict = new HashMap<String, String>();
parentGID = info.firstGid + Integer.parseInt(attributes.getValue("id"));
tileProperties.put(String.valueOf(parentGID), dict);
parentElement = TMXPropertyTile;
} else if (localName.equals("layer")) {
CCTMXLayerInfo layer = new CCTMXLayerInfo();
layer.name = attributes.getValue("name");
CGSize s = CGSize.zero();
s.width = Integer.parseInt(attributes.getValue("width"));
s.height = Integer.parseInt(attributes.getValue("height"));
layer.layerSize = s;
String visible = attributes.getValue("visible");
layer.visible = visible==null||!(visible.equals("0"));
if (attributes.getValue("opacity") != null) {
layer.opacity = (int) (255 * Float.parseFloat(attributes.getValue("opacity")));
} else {
layer.opacity = 255;
}
try {
int x = Integer.parseInt(attributes.getValue("x"));
int y = Integer.parseInt(attributes.getValue("y"));
layer.offset = CGPoint.ccp(x,y);
} catch (Exception e) {
layer.offset = CGPoint.zero();
}
layers.add(layer);
// The parent element is now "layer"
parentElement = TMXPropertyLayer;
} else if (localName.equals("objectgroup")) {
CCTMXObjectGroup objectGroup = new CCTMXObjectGroup();
objectGroup.groupName = attributes.getValue("name");
CGPoint positionOffset = CGPoint.zero();
positionOffset.x = Integer.parseInt(attributes.getValue("x")) * tileSize.width;
positionOffset.y = Integer.parseInt(attributes.getValue("y")) * tileSize.height;
objectGroup.positionOffset = positionOffset;
objectGroups.add(objectGroup);
// The parent element is now "objectgroup"
parentElement = TMXPropertyObjectGroup;
} else if (localName.equals("image")) {
CCTMXTilesetInfo tileset = tilesets.get(tilesets.size()-1);
// build full path
String imagename = attributes.getValue("source");
int idx = filename.lastIndexOf("/");
if (idx != -1) {
String path = filename.substring(0, idx);
tileset.sourceImage = path + "/" + imagename;
} else {
tileset.sourceImage = imagename;
}
} else if (localName.equals("data")) {
String encoding = attributes.getValue("encoding");
String compression = attributes.getValue("compression");
if (encoding.equals("base64")) {
layerAttribs |= TMXLayerAttribBase64;
storingCharacters = true;
assert (compression==null || compression.equals("gzip")): "TMX: unsupported compression method";
if (compression.equals("gzip")) {
layerAttribs |= TMXLayerAttribGzip;
}
}
assert (layerAttribs != TMXLayerAttribNone): "TMX tile map: Only base64 and/or gzip maps are supported";
} else if (localName.equals("object")) {
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
// The value for "type" was blank or not a valid class name
// Create an instance of TMXObjectInfo to store the object and its properties
HashMap<String, String> dict = new HashMap<String, String>();
// Set the name of the object to the value for "name"
dict.put("name", attributes.getValue("name"));
// Assign all the attributes as key/name pairs in the properties dictionary
dict.put("type", attributes.getValue("type"));
int x = (int) (Integer.parseInt(attributes.getValue("x")) + objectGroup.positionOffset.x);
dict.put("x", String.valueOf(x));
int y = (int) (Integer.parseInt(attributes.getValue("y")) + objectGroup.positionOffset.y);
// Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
y = (int) ((mapSize.height * tileSize.height) - y - Integer.parseInt(attributes.getValue("height")));
dict.put("y", String.valueOf(y));
dict.put("width", attributes.getValue("width"));
dict.put("height", attributes.getValue("height"));
// Add the object to the objectGroup
objectGroup.objects.add(dict);
// The parent element is now "object"
parentElement = TMXPropertyObject;
} else if(localName.equals("property")) {
String name = attributes.getValue("name");
String value= attributes.getValue("value");
if ( parentElement == TMXPropertyNone ) {
ccMacros.CCLOG(LOG_TAG,
"TMX tile map: Parent element is unsupported. Cannot add property named '" + name + "' with value '" + value + "'");
} else if ( parentElement == TMXPropertyMap ) {
// The parent element is the map
properties.put(name, value);
} else if ( parentElement == TMXPropertyLayer ) {
// The parent element is the last layer
CCTMXLayerInfo layer = layers.get(layers.size()-1);
// Add the property to the layer
layer.properties.put(name, value);
} else if ( parentElement == TMXPropertyObjectGroup ) {
// The parent element is the last object group
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
objectGroup.properties.put(name, value);
} else if ( parentElement == TMXPropertyObject ) {
// The parent element is the last object
CCTMXObjectGroup objectGroup = objectGroups.get(objectGroups.size()-1);
HashMap<String, String> dict = objectGroup.objects.get(objectGroup.objects.size()-1);
dict.put(name, value);
} else if ( parentElement == TMXPropertyTile ) {
HashMap<String, String> dict = tileProperties.get(String.valueOf(parentGID));
dict.put(name, value);
}
}
}
|
diff --git a/src/main/java/com/cloudbees/service/GameServlet.java b/src/main/java/com/cloudbees/service/GameServlet.java
index 80ad95b..09aac5e 100644
--- a/src/main/java/com/cloudbees/service/GameServlet.java
+++ b/src/main/java/com/cloudbees/service/GameServlet.java
@@ -1,110 +1,111 @@
package com.cloudbees.service;
import java.io.StringWriter;
import javax.servlet.http.HttpServlet;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.StatusType;
import com.cloudbees.model.Game;
import com.google.gson.stream.JsonWriter;
@Path("/game")
public class GameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private MongoDAO dao = new MongoDAO();
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getGame(@PathParam("id") String id ) {
StatusType statusCode = null;
String msg = null;
try {
dao.connect();
msg = dao.getGame( id );
if ( msg != null )
statusCode = Response.Status.OK;
else
// IllegalArgumentException/NullPointerException
statusCode = Response.Status.BAD_REQUEST;
}
catch (Exception e) {
e.printStackTrace();
// Others: Return 500 Internal Server Error
statusCode = Response.Status.INTERNAL_SERVER_ERROR;
}
finally {
dao.getMongo().close();
}
if (statusCode != Response.Status.OK)
return Response.status(statusCode).build();
else
return Response.status(statusCode).entity(msg).build();
}
@POST
@Path("new")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response newGame(Game game) {
StatusType statusCode = null;
String msg = null;
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
try {
dao.connect();
// Create a new game (key = game id)
String id = dao.newGame( game );
if (id == null) {
// Return 400 Bad Request
statusCode = Response.Status.BAD_REQUEST;
} else {
writer.beginObject();
writer.name("id").value( id );
writer.endObject();
writer.close();
statusCode = Response.Status.OK;
msg = sw.toString();
}
}
catch (Exception e) {
e.printStackTrace();
// Return 500 Internal Server Error
statusCode = Response.Status.INTERNAL_SERVER_ERROR;
}
finally {
- //dao.getMongo().close();
+ // Investigate
+ dao.getMongo().close();
}
if (statusCode != Response.Status.OK)
return Response.status(statusCode).build();
else
return Response.status(statusCode).entity(msg).build();
}
public MongoDAO getDao() {
return dao;
}
public void setDao(MongoDAO dao) {
this.dao = dao;
}
}
| true | true | public Response newGame(Game game) {
StatusType statusCode = null;
String msg = null;
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
try {
dao.connect();
// Create a new game (key = game id)
String id = dao.newGame( game );
if (id == null) {
// Return 400 Bad Request
statusCode = Response.Status.BAD_REQUEST;
} else {
writer.beginObject();
writer.name("id").value( id );
writer.endObject();
writer.close();
statusCode = Response.Status.OK;
msg = sw.toString();
}
}
catch (Exception e) {
e.printStackTrace();
// Return 500 Internal Server Error
statusCode = Response.Status.INTERNAL_SERVER_ERROR;
}
finally {
//dao.getMongo().close();
}
if (statusCode != Response.Status.OK)
return Response.status(statusCode).build();
else
return Response.status(statusCode).entity(msg).build();
}
| public Response newGame(Game game) {
StatusType statusCode = null;
String msg = null;
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
try {
dao.connect();
// Create a new game (key = game id)
String id = dao.newGame( game );
if (id == null) {
// Return 400 Bad Request
statusCode = Response.Status.BAD_REQUEST;
} else {
writer.beginObject();
writer.name("id").value( id );
writer.endObject();
writer.close();
statusCode = Response.Status.OK;
msg = sw.toString();
}
}
catch (Exception e) {
e.printStackTrace();
// Return 500 Internal Server Error
statusCode = Response.Status.INTERNAL_SERVER_ERROR;
}
finally {
// Investigate
dao.getMongo().close();
}
if (statusCode != Response.Status.OK)
return Response.status(statusCode).build();
else
return Response.status(statusCode).entity(msg).build();
}
|
diff --git a/src/com/edinarobotics/zephyr/parts/ShooterComponents.java b/src/com/edinarobotics/zephyr/parts/ShooterComponents.java
index 16213cf..c4c6853 100644
--- a/src/com/edinarobotics/zephyr/parts/ShooterComponents.java
+++ b/src/com/edinarobotics/zephyr/parts/ShooterComponents.java
@@ -1,89 +1,91 @@
package com.edinarobotics.zephyr.parts;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Relay;
/**
*The wrapper for the shooter components, contains the 2 jaguars driving the shooter
* along with the rotating jaguar and the piston.
*/
public class ShooterComponents {
public static final int ROTATE_RIGHT_SIGN = 1;
public static final int ROTATE_LEFT_SIGN = -1;
private Jaguar shooterLeftJaguar;
private Jaguar shooterRightJaguar;
private Jaguar shooterRotator;
private Relay ballLoadPiston;
private DigitalInput leftLimitSwitch;
private DigitalInput rightLimitSwitch;
private Encoder encoder;
/*
* Constructs shooterLeftJaguar, shooterRightJaguar, shooterRotator and ballLoadPiston
* with leftJaguar, rightJaguar, rotator and piston respectively.
*/
public ShooterComponents(int leftJaguar, int rightJaguar, int rotator, int piston,
int leftLimitSwitch, int rightLimitSwitch, int encoderA, int encoderB){
shooterLeftJaguar = new Jaguar(leftJaguar);
shooterRightJaguar = new Jaguar(rightJaguar);
shooterRotator = new Jaguar(rotator);
ballLoadPiston = new Relay(piston);
this.leftLimitSwitch = new DigitalInput(leftLimitSwitch);
this.rightLimitSwitch = new DigitalInput(rightLimitSwitch);
this.encoder = new Encoder(encoderA, encoderB);
+ encoder.setReverseDirection(true);
+ encoder.setDistancePerPulse(18518);
encoder.start();
}
/*
* sets the shooterLeftJaguar to speed and shooterRightJaguar to -speed
*/
public void setSpeed(double speed){
shooterLeftJaguar.set(-speed);
shooterRightJaguar.set(speed);
}
/*
* Sets the rotator to speed
*/
public void rotate(double speed){
if((sgn(speed) == ROTATE_LEFT_SIGN && leftLimitSwitch.get()) ||
(sgn(speed) == ROTATE_RIGHT_SIGN) && rightLimitSwitch.get()){
//Limit switches are pressed, stop rotating.
shooterRotator.set(0);
return;
}
shooterRotator.set(speed);
}
/*
* Sets the piston up if position is true, else it lowers it.
*/
public void firePiston(boolean position){
ballLoadPiston.set((position ? Relay.Value.kForward :Relay.Value.kReverse));
}
/**
* Returns the encoder attached to the shooter.
* @return The {@link Encoder} object that can be used to access the encoder
* attached to the shooter.
*/
public Encoder getEncoder(){
return encoder;
}
/**
* A very simple implementation of the sgn function. Returns
* {@code 1},{@code -1} or {@code 0} representing the sign of the number.
* @param num The number whose sign will be returned.
* @return {@code -1} if the number is negative,
* {@code 0} if the number is 0, or {@code 1} if the number is positive.
*/
private int sgn(double num){
if(num>0){
return 1;
}
else if(num<0){
return -1;
}
return 0;
}
}
| true | true | public ShooterComponents(int leftJaguar, int rightJaguar, int rotator, int piston,
int leftLimitSwitch, int rightLimitSwitch, int encoderA, int encoderB){
shooterLeftJaguar = new Jaguar(leftJaguar);
shooterRightJaguar = new Jaguar(rightJaguar);
shooterRotator = new Jaguar(rotator);
ballLoadPiston = new Relay(piston);
this.leftLimitSwitch = new DigitalInput(leftLimitSwitch);
this.rightLimitSwitch = new DigitalInput(rightLimitSwitch);
this.encoder = new Encoder(encoderA, encoderB);
encoder.start();
}
| public ShooterComponents(int leftJaguar, int rightJaguar, int rotator, int piston,
int leftLimitSwitch, int rightLimitSwitch, int encoderA, int encoderB){
shooterLeftJaguar = new Jaguar(leftJaguar);
shooterRightJaguar = new Jaguar(rightJaguar);
shooterRotator = new Jaguar(rotator);
ballLoadPiston = new Relay(piston);
this.leftLimitSwitch = new DigitalInput(leftLimitSwitch);
this.rightLimitSwitch = new DigitalInput(rightLimitSwitch);
this.encoder = new Encoder(encoderA, encoderB);
encoder.setReverseDirection(true);
encoder.setDistancePerPulse(18518);
encoder.start();
}
|
diff --git a/src/web/org/openmrs/web/controller/user/UserFormController.java b/src/web/org/openmrs/web/controller/user/UserFormController.java
index 3da286b4..8f8ab63a 100644
--- a/src/web/org/openmrs/web/controller/user/UserFormController.java
+++ b/src/web/org/openmrs/web/controller/user/UserFormController.java
@@ -1,352 +1,352 @@
/**
* 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 java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Person;
import org.openmrs.Role;
import org.openmrs.User;
import org.openmrs.api.PasswordException;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.openmrs.propertyeditor.ConceptEditor;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.web.WebConstants;
import org.openmrs.web.controller.person.PersonFormController;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
/**
* User-specific form controller. Creates the model/view etc for editing users.
*
* @see org.openmrs.web.controller.person.PersonFormController
*/
public class UserFormController extends PersonFormController {
/** Logger for this class and subclasses */
protected static final Log log = LogFactory.getLog(UserFormController.class);
/**
* Allows for other Objects to be used as values in input tags. Normally, only strings and lists
* are expected
*
* @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
* org.springframework.web.bind.ServletRequestDataBinder)
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true));
binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(Context.getDateFormat(), true));
binder.registerCustomEditor(org.openmrs.Concept.class, new ConceptEditor());
}
/**
* @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
User user = (User) obj;
UserService us = Context.getUserService();
MessageSourceAccessor msa = getMessageSourceAccessor();
String action = request.getParameter("action");
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (msa.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return new ModelAndView(new RedirectView(request.getContextPath() + "/index.htm"));
} else if (msa.getMessage("User.delete").equals(action)) {
us.purgeUser(user);
return new ModelAndView(new RedirectView(getSuccessView()));
} else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
String password = request.getParameter("userFormPassword");
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
String confirm = request.getParameter("confirm");
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
- OpenmrsUtil.validatePassword(user.getUsername(), password, String.valueOf(user.getUserId()));
+ OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
// add Roles to user (because spring can't handle lists as properties...)
String[] roles = request.getParameterValues("roleStrings");
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
/* TODO check if user can delete privilege
Collection<Collection> lists = OpenmrsUtil.compareLists(user.getRoles(), set);
Collection toDel = (Collection)lists.toArray()[1];
for (Object o : toDel) {
Role r = (Role)o;
for (Privilege p : r.getPrivileges())
if (!user.hasPrivilege(p.getPrivilege()))
throw new APIException("Privilege required: " + p.getPrivilege());
}
*/
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
}
return super.processFormSubmission(request, response, user, errors);
}
/**
* The onSubmit function receives the form/command object that was modified by the input form
* and saves it to the db
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
User user = (User) obj;
String view = getFormView();
if (Context.isAuthenticated()) {
UserService us = Context.getUserService();
String password = request.getParameter("userFormPassword");
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
Map<String, String> properties = user.getUserProperties();
if (properties == null)
properties = new HashMap<String, String>();
Boolean newChangePassword = false;
String chk = request.getParameter(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD);
if (chk != null)
newChangePassword = true;
if (!newChangePassword.booleanValue() && properties.containsKey(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD)) {
properties.remove(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD);
}
if (newChangePassword.booleanValue()) {
properties.put(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD, newChangePassword.toString());
}
String[] keys = request.getParameterValues("property");
String[] values = request.getParameterValues("value");
if (keys != null && values != null) {
for (int x = 0; x < keys.length; x++) {
String key = keys[x];
String val = values[x];
properties.put(key, val);
}
}
user.setUserProperties(properties);
if (isNewUser(user))
us.saveUser(user, password);
else {
us.saveUser(user, null);
if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
if (log.isDebugEnabled())
log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser());
us.changePassword(user, password);
}
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
view = getSuccessView();
}
return new ModelAndView(new RedirectView(view));
}
/**
* This is called prior to displaying a form for the first time. It tells Spring the
* form/command object to load into the request
*
* @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
* @should get empty form with valid user
*/
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
User user = null;
if (Context.isAuthenticated()) {
UserService us = Context.getUserService();
String userId = request.getParameter("userId");
Integer id = null;
if (userId != null) {
try {
id = Integer.valueOf(userId);
user = us.getUser(id);
}
catch (NumberFormatException numberError) {
log.warn("Invalid userId supplied: '" + userId + "'", numberError);
}
catch (ObjectRetrievalFailureException noUserEx) {
// pass through to the null check
}
// if no user was found
if (user == null) {
try {
Person person = Context.getPersonService().getPerson(id);
user = new User(person);
}
catch (ObjectRetrievalFailureException noPersonEx) {
log.warn("There is no user or person with id: '" + userId + "'", noPersonEx);
throw new ServletException("There is no user or person with id: '" + userId + "'");
}
}
}
}
if (user == null) {
user = new User();
String name = request.getParameter("addName");
if (name != null) {
String gender = request.getParameter("addGender");
String date = request.getParameter("addBirthdate");
String age = request.getParameter("addAge");
getMiniPerson(user, name, gender, date, age);
}
}
setupFormBackingObject(user);
return user;
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
* java.lang.Object, org.springframework.validation.Errors)
*/
protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors errors) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
User user = (User) obj;
List<Role> roles = Context.getUserService().getAllRoles();
if (roles == null)
roles = new Vector<Role>();
for (String s : OpenmrsConstants.AUTO_ROLES()) {
Role r = new Role(s);
roles.remove(r);
}
if (Context.isAuthenticated()) {
map.put("roles", roles);
if (user.getUserId() == null || Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS))
;
map.put("modifyPasswords", true);
map.put("changePasswordName", OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD);
String s = user.getUserProperty(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD);
map.put("changePassword", new Boolean(s).booleanValue());
map.put("isNewUser", isNewUser(user));
}
super.setupReferenceData(map, user);
return map;
}
/**
* Superficially determines if this form is being filled out for a new user (basically just
* looks for a primary key (user_id)
*
* @param user
* @return true/false if this user is new
*/
private Boolean isNewUser(User user) {
return user == null ? true : user.getUserId() == null;
}
}
| true | true | protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
User user = (User) obj;
UserService us = Context.getUserService();
MessageSourceAccessor msa = getMessageSourceAccessor();
String action = request.getParameter("action");
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (msa.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return new ModelAndView(new RedirectView(request.getContextPath() + "/index.htm"));
} else if (msa.getMessage("User.delete").equals(action)) {
us.purgeUser(user);
return new ModelAndView(new RedirectView(getSuccessView()));
} else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
String password = request.getParameter("userFormPassword");
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
String confirm = request.getParameter("confirm");
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, String.valueOf(user.getUserId()));
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
// add Roles to user (because spring can't handle lists as properties...)
String[] roles = request.getParameterValues("roleStrings");
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
/* TODO check if user can delete privilege
Collection<Collection> lists = OpenmrsUtil.compareLists(user.getRoles(), set);
Collection toDel = (Collection)lists.toArray()[1];
for (Object o : toDel) {
Role r = (Role)o;
for (Privilege p : r.getPrivileges())
if (!user.hasPrivilege(p.getPrivilege()))
throw new APIException("Privilege required: " + p.getPrivilege());
}
*/
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
}
return super.processFormSubmission(request, response, user, errors);
}
| protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
User user = (User) obj;
UserService us = Context.getUserService();
MessageSourceAccessor msa = getMessageSourceAccessor();
String action = request.getParameter("action");
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (msa.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return new ModelAndView(new RedirectView(request.getContextPath() + "/index.htm"));
} else if (msa.getMessage("User.delete").equals(action)) {
us.purgeUser(user);
return new ModelAndView(new RedirectView(getSuccessView()));
} else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
String password = request.getParameter("userFormPassword");
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
String confirm = request.getParameter("confirm");
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
// add Roles to user (because spring can't handle lists as properties...)
String[] roles = request.getParameterValues("roleStrings");
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
/* TODO check if user can delete privilege
Collection<Collection> lists = OpenmrsUtil.compareLists(user.getRoles(), set);
Collection toDel = (Collection)lists.toArray()[1];
for (Object o : toDel) {
Role r = (Role)o;
for (Privilege p : r.getPrivileges())
if (!user.hasPrivilege(p.getPrivilege()))
throw new APIException("Privilege required: " + p.getPrivilege());
}
*/
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
}
return super.processFormSubmission(request, response, user, errors);
}
|
diff --git a/bundles/org.eclipse.wst.xsl.core/src/org/eclipse/wst/xsl/core/resolver/ResolverExtension.java b/bundles/org.eclipse.wst.xsl.core/src/org/eclipse/wst/xsl/core/resolver/ResolverExtension.java
index cb8a4d1..61c7a73 100644
--- a/bundles/org.eclipse.wst.xsl.core/src/org/eclipse/wst/xsl/core/resolver/ResolverExtension.java
+++ b/bundles/org.eclipse.wst.xsl.core/src/org/eclipse/wst/xsl/core/resolver/ResolverExtension.java
@@ -1,146 +1,147 @@
/*******************************************************************************
* Copyright (c) 2008 Jesper Steen Moeller 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:
* Jesper Steen Moeller - XSL core plugin
*******************************************************************************/
package org.eclipse.wst.xsl.core.resolver;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.wst.common.uriresolver.internal.provisional.URIResolverExtension;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.eclipse.wst.xsl.core.Messages;
import org.eclipse.wst.xsl.core.XSLCorePlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class ResolverExtension implements URIResolverExtension {
private static final Double DEFAULT_XSLT_VERSION = 1.0;
private static final String SCHEMA_BASE_URI = "platform:/plugin/" + XSLCorePlugin.PLUGIN_ID + "/xslt-schemas"; //$NON-NLS-1$ //$NON-NLS-2$
private static final String XSLT_1_0_PATH = SCHEMA_BASE_URI + "/xslt-1.0.xsd"; //$NON-NLS-1$
private static final String XSLT_2_0_PATH = SCHEMA_BASE_URI + "/xslt-2.0.xsd"; //$NON-NLS-1$
private static final String XSLT_STYLESHEET = "stylesheet"; //$NON-NLS-1$
private static final String XSLT_TEMPLATE = "template"; //$NON-NLS-1$
private static final String XSLT_VERSION = "version"; //$NON-NLS-1$
public ResolverExtension() {
}
public String resolve(IFile file, String baseLocation, String publicId,
String systemId) {
// Is someone looking for "our" schema?
if (! XSLCorePlugin.XSLT_NS.equals(publicId)) {
// Not this time, return right away
return null;
}
String version = null;
- version = peekVersionAttributeFromSSE(file);
+ if (file != null)
+ version = peekVersionAttributeFromSSE(file);
if (version == null)
version = peekVersionFromFile(file, baseLocation);
if (version == null)
return null;
Double versionNumber = null;
try {
versionNumber = Double.valueOf(version);
} catch (Throwable t) {
// Not interested
}
if (versionNumber == null) {
versionNumber = DEFAULT_XSLT_VERSION;
}
// We carelessly ditch the fraction part
int intVersion = versionNumber.intValue();
if (intVersion == 1) {
return XSLT_1_0_PATH;
} else if (intVersion == 2) {
return XSLT_2_0_PATH;
}
else return null;
}
private String peekVersionFromFile(IFile file, String baseLocation) {
XSLVersionHandler handler = new XSLVersionHandler();
try {
handler.parseContents(file != null ? createInputSource(file) : createInputSource(baseLocation));
} catch (SAXException se) {
XSLCorePlugin.log(se);
// drop through, since this is almost to be expected
} catch (IOException ioe) {
XSLCorePlugin.log(new CoreException(XSLCorePlugin.newErrorStatus("Can't parse XSL document", ioe))); //$NON-NLS-1$
// drop through, since this is not really a show-stopper
} catch (ParserConfigurationException pce) {
// some bad thing happened - force this describer to be disabled
String message = Messages.XSLCorePlugin_parserConfiguration;
XSLCorePlugin.log(new Status(IStatus.ERROR, XSLCorePlugin.PLUGIN_ID, 0, message, pce));
throw new RuntimeException(message);
// drop through, since this is not really a show-stopper
} catch (CoreException ce) {
XSLCorePlugin.log(ce);
// drop through, since this is not really a show-stopper
}
String versionX = handler.getVersionAttribute();
return versionX;
}
private String peekVersionAttributeFromSSE(IFile file) {
IModelManager manager = StructuredModelManager.getModelManager();
if (manager != null) {
String id = manager.calculateId(file);
IStructuredModel model = manager.getExistingModelForRead(id);
try {
if (model instanceof IDOMModel) {
Document doc = ((IDOMModel)model).getDocument();
if (doc != null && doc.getDocumentElement() != null) {
Element documentElement = doc.getDocumentElement();
if (XSLT_STYLESHEET.equals(documentElement.getLocalName()) ||
XSLT_TEMPLATE.equals(documentElement.getLocalName())) {
return documentElement.getAttribute(XSLT_VERSION);
} else return ""; //$NON-NLS-1$
}
}
} finally {
model.releaseFromRead();
}
}
return null;
}
private InputSource createInputSource(String systemId) throws CoreException {
return new InputSource(systemId);
}
private InputSource createInputSource(IFile file) throws CoreException {
InputSource src = new InputSource(file.getContents());
src.setSystemId(file.getLocationURI().toString());
return src;
}
}
| true | true | public String resolve(IFile file, String baseLocation, String publicId,
String systemId) {
// Is someone looking for "our" schema?
if (! XSLCorePlugin.XSLT_NS.equals(publicId)) {
// Not this time, return right away
return null;
}
String version = null;
version = peekVersionAttributeFromSSE(file);
if (version == null)
version = peekVersionFromFile(file, baseLocation);
if (version == null)
return null;
Double versionNumber = null;
try {
versionNumber = Double.valueOf(version);
} catch (Throwable t) {
// Not interested
}
if (versionNumber == null) {
versionNumber = DEFAULT_XSLT_VERSION;
}
// We carelessly ditch the fraction part
int intVersion = versionNumber.intValue();
if (intVersion == 1) {
return XSLT_1_0_PATH;
} else if (intVersion == 2) {
return XSLT_2_0_PATH;
}
else return null;
}
| public String resolve(IFile file, String baseLocation, String publicId,
String systemId) {
// Is someone looking for "our" schema?
if (! XSLCorePlugin.XSLT_NS.equals(publicId)) {
// Not this time, return right away
return null;
}
String version = null;
if (file != null)
version = peekVersionAttributeFromSSE(file);
if (version == null)
version = peekVersionFromFile(file, baseLocation);
if (version == null)
return null;
Double versionNumber = null;
try {
versionNumber = Double.valueOf(version);
} catch (Throwable t) {
// Not interested
}
if (versionNumber == null) {
versionNumber = DEFAULT_XSLT_VERSION;
}
// We carelessly ditch the fraction part
int intVersion = versionNumber.intValue();
if (intVersion == 1) {
return XSLT_1_0_PATH;
} else if (intVersion == 2) {
return XSLT_2_0_PATH;
}
else return null;
}
|
diff --git a/javasrc/src/org/ccnx/ccn/test/profiles/security/access/group/GroupAccessControlTestRepo.java b/javasrc/src/org/ccnx/ccn/test/profiles/security/access/group/GroupAccessControlTestRepo.java
index 035bdd235..88e16217d 100644
--- a/javasrc/src/org/ccnx/ccn/test/profiles/security/access/group/GroupAccessControlTestRepo.java
+++ b/javasrc/src/org/ccnx/ccn/test/profiles/security/access/group/GroupAccessControlTestRepo.java
@@ -1,63 +1,63 @@
/**
* 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.profiles.security.access.group;
import junit.framework.Assert;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.io.CCNFileInputStream;
import org.ccnx.ccn.io.RepositoryFileOutputStream;
import org.ccnx.ccn.profiles.security.access.group.ACL;
import org.ccnx.ccn.protocol.ContentName;
import org.junit.BeforeClass;
import org.junit.Test;
public class GroupAccessControlTestRepo {
static ContentName acName;
static ContentName fileName;
static byte content[] = "the network is built around me".getBytes();
/**
* Create a new root of an access controlled namespace in the repo
* and write a file out there
*/
@BeforeClass
public static void createAC() throws Exception {
// mark the namespace as under access control
- ACL acl = new ACL();
+ // ACL acl = new ACL();
acName = ContentName.fromNative("/parc.com/ac_repo");
// NamespaceManager.Root.create(acName, acl, SaveType.REPOSITORY, CCNHandle.getHandle());
// create a file in the namespace under access control
fileName = ContentName.fromNative(acName, "/test.txt");
CCNHandle h = CCNHandle.getHandle();
RepositoryFileOutputStream os = new RepositoryFileOutputStream(fileName, h);
os.write(content);
os.close();
h.close();
}
@Test
public void read() throws Exception {
CCNFileInputStream is = new CCNFileInputStream(fileName);
byte received[] = new byte[content.length];
Assert.assertEquals(is.read(received), content.length);
Assert.assertTrue(DataUtils.arrayEquals(content, received));
}
}
| true | true | public static void createAC() throws Exception {
// mark the namespace as under access control
ACL acl = new ACL();
acName = ContentName.fromNative("/parc.com/ac_repo");
// NamespaceManager.Root.create(acName, acl, SaveType.REPOSITORY, CCNHandle.getHandle());
// create a file in the namespace under access control
fileName = ContentName.fromNative(acName, "/test.txt");
CCNHandle h = CCNHandle.getHandle();
RepositoryFileOutputStream os = new RepositoryFileOutputStream(fileName, h);
os.write(content);
os.close();
h.close();
}
| public static void createAC() throws Exception {
// mark the namespace as under access control
// ACL acl = new ACL();
acName = ContentName.fromNative("/parc.com/ac_repo");
// NamespaceManager.Root.create(acName, acl, SaveType.REPOSITORY, CCNHandle.getHandle());
// create a file in the namespace under access control
fileName = ContentName.fromNative(acName, "/test.txt");
CCNHandle h = CCNHandle.getHandle();
RepositoryFileOutputStream os = new RepositoryFileOutputStream(fileName, h);
os.write(content);
os.close();
h.close();
}
|
diff --git a/src/org/mozilla/javascript/NativeArray.java b/src/org/mozilla/javascript/NativeArray.java
index 87a2daa4..ecec663f 100644
--- a/src/org/mozilla/javascript/NativeArray.java
+++ b/src/org/mozilla/javascript/NativeArray.java
@@ -1,1204 +1,1204 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* 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.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Mike McCabe
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
/**
* This class implements the Array native object.
* @author Norris Boyd
* @author Mike McCabe
*/
public class NativeArray extends IdScriptable {
/*
* Optimization possibilities and open issues:
* - Long vs. double schizophrenia. I suspect it might be better
* to use double throughout.
* - Most array operations go through getElem or setElem (defined
* in this file) to handle the full 2^32 range; it might be faster
* to have versions of most of the loops in this file for the
* (infinitely more common) case of indices < 2^31.
* - Functions that need a new Array call "new Array" in the
* current scope rather than using a hardwired constructor;
* "Array" could be redefined. It turns out that js calls the
* equivalent of "new Array" in the current scope, except that it
* always gets at least an object back, even when Array == null.
*/
static void init(Context cx, Scriptable scope, boolean sealed)
{
NativeArray obj = new NativeArray();
obj.prototypeFlag = true;
obj.addAsPrototype(MAX_PROTOTYPE_ID, cx, scope, sealed);
}
/**
* Zero-parameter constructor: just used to create Array.prototype
*/
private NativeArray()
{
dense = null;
this.length = 0;
}
public NativeArray(long length)
{
int intLength = (int) length;
if (intLength == length && intLength > 0) {
if (intLength > maximumDenseLength)
intLength = maximumDenseLength;
dense = new Object[intLength];
for (int i=0; i < intLength; i++)
dense[i] = NOT_FOUND;
}
this.length = length;
}
public NativeArray(Object[] array)
{
dense = array;
this.length = array.length;
}
public String getClassName()
{
return "Array";
}
protected int getIdAttributes(int id)
{
if (id == Id_length) {
return DONTENUM | PERMANENT;
}
return super.getIdAttributes(id);
}
protected Object getIdValue(int id)
{
if (id == Id_length) {
return wrap_double(length);
}
return super.getIdValue(id);
}
protected void setIdValue(int id, Object value)
{
if (id == Id_length) {
setLength(value); return;
}
super.setIdValue(id, value);
}
public int methodArity(int methodId)
{
if (prototypeFlag) {
switch (methodId) {
case Id_constructor: return 1;
case Id_toString: return 0;
case Id_toLocaleString: return 1;
case Id_join: return 1;
case Id_reverse: return 0;
case Id_sort: return 1;
case Id_push: return 1;
case Id_pop: return 1;
case Id_shift: return 1;
case Id_unshift: return 1;
case Id_splice: return 1;
case Id_concat: return 1;
case Id_slice: return 1;
}
}
return super.methodArity(methodId);
}
public Object execMethod
(int methodId, IdFunction f,
Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
throws JavaScriptException
{
if (prototypeFlag) {
switch (methodId) {
case Id_constructor:
return jsConstructor(cx, scope, args, f, thisObj == null);
case Id_toString:
return js_toString(cx, thisObj, args);
case Id_toLocaleString:
return js_toLocaleString(cx, thisObj, args);
case Id_join:
return js_join(cx, thisObj, args);
case Id_reverse:
return js_reverse(cx, thisObj, args);
case Id_sort:
return js_sort(cx, scope, thisObj, args);
case Id_push:
return js_push(cx, thisObj, args);
case Id_pop:
return js_pop(cx, thisObj, args);
case Id_shift:
return js_shift(cx, thisObj, args);
case Id_unshift:
return js_unshift(cx, thisObj, args);
case Id_splice:
return js_splice(cx, scope, thisObj, args);
case Id_concat:
return js_concat(cx, scope, thisObj, args);
case Id_slice:
return js_slice(cx, thisObj, args);
}
}
return super.execMethod(methodId, f, cx, scope, thisObj, args);
}
public Object get(int index, Scriptable start)
{
if (dense != null && 0 <= index && index < dense.length)
return dense[index];
return super.get(index, start);
}
public boolean has(int index, Scriptable start)
{
if (dense != null && 0 <= index && index < dense.length)
return dense[index] != NOT_FOUND;
return super.has(index, start);
}
// if id is an array index (ECMA 15.4.0), return the number,
// otherwise return -1L
private static long toArrayIndex(String id)
{
double d = ScriptRuntime.toNumber(id);
if (d == d) {
long index = ScriptRuntime.toUint32(d);
if (index == d && index != 4294967295L) {
// Assume that ScriptRuntime.toString(index) is the same
// as java.lang.Long.toString(index) for long
if (Long.toString(index).equals(id)) {
return index;
}
}
}
return -1;
}
public void put(String id, Scriptable start, Object value)
{
super.put(id, start, value);
if (start == this) {
// If the object is sealed, super will throw exception
long index = toArrayIndex(id);
if (index >= length) {
length = index + 1;
}
}
}
public void put(int index, Scriptable start, Object value)
{
if (start == this && !isSealed()
&& dense != null && 0 <= index && index < dense.length)
{
// If start == this && sealed, super will throw exception
dense[index] = value;
} else {
super.put(index, start, value);
}
if (start == this) {
// only set the array length if given an array index (ECMA 15.4.0)
if (this.length <= index) {
// avoid overflowing index!
this.length = (long)index + 1;
}
}
}
public void delete(int index)
{
if (!isSealed()
&& dense != null && 0 <= index && index < dense.length)
{
dense[index] = NOT_FOUND;
} else {
super.delete(index);
}
}
public Object[] getIds()
{
Object[] superIds = super.getIds();
if (dense == null) { return superIds; }
int N = dense.length;
long currentLength = length;
if (N > currentLength) {
N = (int)currentLength;
}
if (N == 0) { return superIds; }
int shift = superIds.length;
Object[] ids = new Object[shift + N];
// Make a copy of dense to be immune to removing
// of array elems from other thread when calculating presentCount
System.arraycopy(dense, 0, ids, shift, N);
int presentCount = 0;
for (int i = 0; i != N; ++i) {
// Replace existing elements by their indexes
if (ids[shift + i] != NOT_FOUND) {
ids[shift + presentCount] = new Integer(i);
++presentCount;
}
}
if (presentCount != N) {
// dense contains deleted elems, need to shrink the result
Object[] tmp = new Object[shift + presentCount];
System.arraycopy(ids, shift, tmp, shift, presentCount);
ids = tmp;
}
System.arraycopy(superIds, 0, ids, 0, shift);
return ids;
}
public Object getDefaultValue(Class hint)
{
if (hint == ScriptRuntime.NumberClass) {
Context cx = Context.getContext();
if (cx.getLanguageVersion() == Context.VERSION_1_2)
return new Long(length);
}
return super.getDefaultValue(hint);
}
/**
* See ECMA 15.4.1,2
*/
private static Object jsConstructor(Context cx, Scriptable scope,
Object[] args, IdFunction ctorObj,
boolean inNewExpr)
throws JavaScriptException
{
if (!inNewExpr) {
// FunctionObject.construct will set up parent, proto
return ctorObj.construct(cx, scope, args);
}
if (args.length == 0)
return new NativeArray();
// Only use 1 arg as first element for version 1.2; for
// any other version (including 1.3) follow ECMA and use it as
// a length.
if (cx.getLanguageVersion() == cx.VERSION_1_2) {
return new NativeArray(args);
} else {
Object arg0 = args[0];
if (args.length > 1 || !(arg0 instanceof Number)) {
return new NativeArray(args);
} else {
long len = ScriptRuntime.toUint32(arg0);
if (len != ((Number)arg0).doubleValue())
throw Context.reportRuntimeError0("msg.arraylength.bad");
return new NativeArray(len);
}
}
}
public long getLength() {
return length;
}
/** @deprecated Use {@link #getLength()} instead. */
public long jsGet_length() {
return getLength();
}
private void setLength(Object val) {
/* XXX do we satisfy this?
* 15.4.5.1 [[Put]](P, V):
* 1. Call the [[CanPut]] method of A with name P.
* 2. If Result(1) is false, return.
* ?
*/
double d = ScriptRuntime.toNumber(val);
long longVal = ScriptRuntime.toUint32(d);
if (longVal != d)
throw Context.reportRuntimeError0("msg.arraylength.bad");
if (longVal < length) {
// remove all properties between longVal and length
if (length - longVal > 0x1000) {
// assume that the representation is sparse
Object[] e = getIds(); // will only find in object itself
for (int i=0; i < e.length; i++) {
Object id = e[i];
if (id instanceof String) {
// > MAXINT will appear as string
String strId = (String)id;
long index = toArrayIndex(strId);
if (index >= longVal)
delete(strId);
} else {
int index = ((Integer)id).intValue();
if (index >= longVal)
delete(index);
}
}
} else {
// assume a dense representation
for (long i = longVal; i < length; i++) {
deleteElem(this, i);
}
}
}
length = longVal;
}
/* Support for generic Array-ish objects. Most of the Array
* functions try to be generic; anything that has a length
* property is assumed to be an array.
* getLengthProperty returns 0 if obj does not have the length property
* or its value is not convertible to a number.
*/
static long getLengthProperty(Scriptable obj) {
// These will both give numeric lengths within Uint32 range.
if (obj instanceof NativeString) {
return ((NativeString)obj).getLength();
} else if (obj instanceof NativeArray) {
return ((NativeArray)obj).getLength();
} else if (!(obj instanceof Scriptable)) {
return 0;
}
return ScriptRuntime.toUint32(ScriptRuntime
.getProp(obj, "length", obj));
}
/* Utility functions to encapsulate index > Integer.MAX_VALUE
* handling. Also avoids unnecessary object creation that would
* be necessary to use the general ScriptRuntime.get/setElem
* functions... though this is probably premature optimization.
*/
private static void deleteElem(Scriptable target, long index) {
int i = (int)index;
if (i == index) { target.delete(i); }
else { target.delete(Long.toString(index)); }
}
private static Object getElem(Scriptable target, long index) {
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
return ScriptRuntime.getStrIdElem(target, id);
} else {
return ScriptRuntime.getElem(target, (int)index);
}
}
private static void setElem(Scriptable target, long index, Object value) {
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
ScriptRuntime.setStrIdElem(target, id, value, target);
} else {
ScriptRuntime.setElem(target, (int)index, value);
}
}
private static String js_toString(Context cx, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
return toStringHelper(cx, thisObj,
cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE),
false);
}
private static String js_toLocaleString(Context cx, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
return toStringHelper(cx, thisObj, false, true);
}
private static String toStringHelper(Context cx, Scriptable thisObj,
boolean toSource, boolean toLocale)
throws JavaScriptException
{
/* It's probably redundant to handle long lengths in this
* function; StringBuffers are limited to 2^31 in java.
*/
long length = getLengthProperty(thisObj);
StringBuffer result = new StringBuffer(256);
// whether to return '4,unquoted,5' or '[4, "quoted", 5]'
String separator;
if (toSource) {
result.append('[');
separator = ", ";
} else {
separator = ",";
}
boolean haslast = false;
long i = 0;
boolean toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap(31);
} else {
toplevel = false;
iterating = cx.iterating.has(thisObj);
}
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.put(thisObj, 0); // stop recursion.
for (i = 0; i < length; i++) {
if (i > 0) result.append(separator);
Object elem = getElem(thisObj, i);
if (elem == null || elem == Undefined.instance) {
haslast = false;
continue;
}
haslast = true;
if (elem instanceof String) {
String s = (String)elem;
if (toSource) {
result.append('\"');
result.append(ScriptRuntime.escapeString(s));
result.append('\"');
} else {
result.append(s);
}
} else {
if (toLocale && elem != Undefined.instance &&
elem != null)
{
Scriptable obj = ScriptRuntime.
toObject(cx, thisObj, elem);
Object tls = ScriptRuntime.
getProp(obj, "toLocaleString", thisObj);
elem = ScriptRuntime.call(cx, tls, elem,
ScriptRuntime.emptyArgs);
}
result.append(ScriptRuntime.toString(elem));
}
}
}
} finally {
if (toplevel) {
cx.iterating = null;
}
}
if (toSource) {
//for [,,].length behavior; we want toString to be symmetric.
if (!haslast && i > 0)
result.append(", ]");
else
result.append(']');
}
return result.toString();
}
/**
* See ECMA 15.4.4.3
*/
private static String js_join(Context cx, Scriptable thisObj,
Object[] args)
{
StringBuffer result = new StringBuffer();
String separator;
long length = getLengthProperty(thisObj);
// if no args, use "," as separator
if ((args.length < 1) || (args[0] == Undefined.instance)) {
separator = ",";
} else {
separator = ScriptRuntime.toString(args[0]);
}
for (long i=0; i < length; i++) {
if (i > 0)
result.append(separator);
Object temp = getElem(thisObj, i);
if (temp == null || temp == Undefined.instance)
continue;
result.append(ScriptRuntime.toString(temp));
}
return result.toString();
}
/**
* See ECMA 15.4.4.4
*/
private static Scriptable js_reverse(Context cx, Scriptable thisObj,
Object[] args)
{
long len = getLengthProperty(thisObj);
long half = len / 2;
for(long i=0; i < half; i++) {
long j = len - i - 1;
Object temp1 = getElem(thisObj, i);
Object temp2 = getElem(thisObj, j);
setElem(thisObj, i, temp2);
setElem(thisObj, j, temp1);
}
return thisObj;
}
/**
* See ECMA 15.4.4.5
*/
private static Scriptable js_sort(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
long length = getLengthProperty(thisObj);
if (length <= 1) { return thisObj; }
Object compare;
Object[] cmpBuf;
if (args.length > 0 && Undefined.instance != args[0]) {
// sort with given compare function
compare = args[0];
cmpBuf = new Object[2]; // Buffer for cmp arguments
} else {
// sort with default compare
compare = null;
cmpBuf = null;
}
// Should we use the extended sort function, or the faster one?
if (length >= Integer.MAX_VALUE) {
heapsort_extended(cx, scope, thisObj, length, compare, cmpBuf);
}
else {
int ilength = (int)length;
// copy the JS array into a working array, so it can be
// sorted cheaply.
Object[] working = new Object[ilength];
for (int i = 0; i != ilength; ++i) {
working[i] = getElem(thisObj, i);
}
heapsort(cx, scope, working, ilength, compare, cmpBuf);
// copy the working array back into thisObj
for (int i = 0; i != ilength; ++i) {
setElem(thisObj, i, working[i]);
}
}
return thisObj;
}
// Return true only if x > y
private static boolean isBigger(Context cx, Scriptable scope,
Object x, Object y,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
if (check) {
if (cmp == null) {
if (cmpBuf != null) Context.codeBug();
} else {
if (cmpBuf == null || cmpBuf.length != 2) Context.codeBug();
}
}
Object undef = Undefined.instance;
// sort undefined to end
if (undef == y) {
return false; // x can not be bigger then undef
} else if (undef == x) {
return true; // y != undef here, so x > y
}
if (cmp == null) {
// if no cmp function supplied, sort lexicographically
String a = ScriptRuntime.toString(x);
String b = ScriptRuntime.toString(y);
return a.compareTo(b) > 0;
}
else {
// assemble args and call supplied JS cmp function
cmpBuf[0] = x;
cmpBuf[1] = y;
Object ret = ScriptRuntime.call(cx, cmp, null, cmpBuf, scope);
double d = ScriptRuntime.toNumber(ret);
// XXX what to do when cmp function returns NaN? ECMA states
// that it's then not a 'consistent compararison function'... but
// then what do we do? Back out and start over with the generic
// cmp function when we see a NaN? Throw an error?
// for now, just ignore it:
return d > 0;
}
}
/** Heapsort implementation.
* See "Introduction to Algorithms" by Cormen, Leiserson, Rivest for details.
* Adjusted for zero based indexes.
*/
private static void heapsort(Context cx, Scriptable scope,
Object[] array, int length,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
if (check && length <= 1) Context.codeBug();
// Build heap
for (int i = length / 2; i != 0;) {
--i;
Object pivot = array[i];
heapify(cx, scope, pivot, array, i, length, cmp, cmpBuf);
}
// Sort heap
for (int i = length; i != 1;) {
--i;
Object pivot = array[i];
array[i] = array[0];
heapify(cx, scope, pivot, array, 0, i, cmp, cmpBuf);
}
}
/** pivot and child heaps of i should be made into heap starting at i,
* original array[i] is never used to have less array access during sorting.
*/
private static void heapify(Context cx, Scriptable scope,
Object pivot, Object[] array, int i, int end,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
for (;;) {
int child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = array[child];
if (child + 1 < end) {
Object nextVal = array[child + 1];
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
array[i] = childVal;
i = child;
}
array[i] = pivot;
}
/** Version of heapsort that call getElem/setElem on target to query/assign
* array elements instead of Java array access
*/
private static void heapsort_extended(Context cx, Scriptable scope,
Scriptable target, long length,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
if (check && length <= 1) Context.codeBug();
// Build heap
for (long i = length / 2; i != 0;) {
--i;
Object pivot = getElem(target, i);
heapify_extended(cx, scope, pivot, target, i, length, cmp, cmpBuf);
}
// Sort heap
for (long i = length; i != 1;) {
--i;
Object pivot = getElem(target, i);
setElem(target, i, getElem(target, 0));
heapify_extended(cx, scope, pivot, target, 0, i, cmp, cmpBuf);
}
}
private static void heapify_extended(Context cx, Scriptable scope,
Object pivot, Scriptable target,
long i, long end,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
for (;;) {
long child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = getElem(target, child);
if (child + 1 < end) {
Object nextVal = getElem(target, child + 1);
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
setElem(target, i, childVal);
i = child;
}
setElem(target, i, pivot);
}
/**
* Non-ECMA methods.
*/
private static Object js_push(Context cx, Scriptable thisObj,
Object[] args)
{
long length = getLengthProperty(thisObj);
for (int i = 0; i < args.length; i++) {
setElem(thisObj, length + i, args[i]);
}
length += args.length;
Double lengthObj = new Double(length);
ScriptRuntime.setProp(thisObj, "length", lengthObj, thisObj);
/*
* If JS1.2, follow Perl4 by returning the last thing pushed.
* Otherwise, return the new array length.
*/
if (cx.getLanguageVersion() == Context.VERSION_1_2)
// if JS1.2 && no arguments, return undefined.
return args.length == 0
? Context.getUndefinedValue()
: args[args.length - 1];
else
return lengthObj;
}
private static Object js_pop(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
long length = getLengthProperty(thisObj);
if (length > 0) {
length--;
// Get the to-be-deleted property's value.
result = getElem(thisObj, length);
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Context.getUndefinedValue();
}
// necessary to match js even when length < 0; js pop will give a
// length property to any target it is called on.
ScriptRuntime.setProp(thisObj, "length", new Double(length), thisObj);
return result;
}
private static Object js_shift(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
long length = getLengthProperty(thisObj);
if (length > 0) {
long i = 0;
length--;
// Get the to-be-deleted property's value.
result = getElem(thisObj, i);
/*
* Slide down the array above the first element. Leave i
* set to point to the last element.
*/
if (length > 0) {
for (i = 1; i <= length; i++) {
Object temp = getElem(thisObj, i);
setElem(thisObj, i - 1, temp);
}
}
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Context.getUndefinedValue();
}
ScriptRuntime.setProp(thisObj, "length", new Double(length), thisObj);
return result;
}
private static Object js_unshift(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
double length = (double)getLengthProperty(thisObj);
int argc = args.length;
if (args.length > 0) {
/* Slide up the array to make room for args at the bottom */
if (length > 0) {
for (long last = (long)length - 1; last >= 0; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + argc, temp);
}
}
/* Copy from argv to the bottom of the array. */
for (int i = 0; i < args.length; i++) {
setElem(thisObj, i, args[i]);
}
/* Follow Perl by returning the new array length. */
length += args.length;
ScriptRuntime.setProp(thisObj, "length",
new Double(length), thisObj);
}
return new Long((long)length);
}
private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
Object result = ScriptRuntime.newObject(cx, scope, "Array", null);
int argc = args.length;
if (argc == 0)
return result;
long length = getLengthProperty(thisObj);
/* Convert the first argument into a starting index. */
- long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
+ long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(thisObj, begin);
} else {
for (long last = begin; last != end; last++) {
Scriptable resultArray = (Scriptable)result;
Object temp = getElem(thisObj, last);
setElem(resultArray, last - begin, temp);
}
}
} else if (count == 0
&& cx.getLanguageVersion() == Context.VERSION_1_2)
{
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Context.getUndefinedValue();
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
ScriptRuntime.setProp(thisObj, "length",
new Double(length + delta), thisObj);
return result;
}
/*
* See Ecma 262v3 15.4.4.4
*/
private static Scriptable js_concat(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
// create an empty Array to return.
scope = getTopLevelScope(scope);
Function ctor = ScriptRuntime.getExistingCtor(cx, scope, "Array");
Scriptable result = ctor.construct(cx, scope, ScriptRuntime.emptyArgs);
long length;
long slot = 0;
/* Put the target in the result array; only add it as an array
* if it looks like one.
*/
if (ScriptRuntime.instanceOf(scope, thisObj, ctor)) {
length = getLengthProperty(thisObj);
// Copy from the target object into the result
for (slot = 0; slot < length; slot++) {
Object temp = getElem(thisObj, slot);
setElem(result, slot, temp);
}
} else {
setElem(result, slot++, thisObj);
}
/* Copy from the arguments into the result. If any argument
* has a numeric length property, treat it as an array and add
* elements separately; otherwise, just copy the argument.
*/
for (int i = 0; i < args.length; i++) {
if (ScriptRuntime.instanceOf(scope, args[i], ctor)) {
// ScriptRuntime.instanceOf => instanceof Scriptable
Scriptable arg = (Scriptable)args[i];
length = getLengthProperty(arg);
for (long j = 0; j < length; j++, slot++) {
Object temp = getElem(arg, j);
setElem(result, slot, temp);
}
} else {
setElem(result, slot++, args[i]);
}
}
return result;
}
private Scriptable js_slice(Context cx, Scriptable thisObj,
Object[] args)
{
Scriptable scope = getTopLevelScope(this);
Scriptable result = ScriptRuntime.newObject(cx, scope, "Array", null);
long length = getLengthProperty(thisObj);
long begin, end;
if (args.length == 0) {
begin = 0;
end = length;
} else {
begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
if (args.length == 1) {
end = length;
} else {
end = toSliceIndex(ScriptRuntime.toInteger(args[1]), length);
}
}
for (long slot = begin; slot < end; slot++) {
Object temp = getElem(thisObj, slot);
setElem(result, slot - begin, temp);
}
return result;
}
private static long toSliceIndex(double value, long length) {
long result;
if (value < 0.0) {
if (value + length < 0.0) {
result = 0;
} else {
result = (long)(value + length);
}
} else if (value > length) {
result = length;
} else {
result = (long)value;
}
return result;
}
protected String getIdName(int id)
{
if (id == Id_length) { return "length"; }
if (prototypeFlag) {
switch (id) {
case Id_constructor: return "constructor";
case Id_toString: return "toString";
case Id_toLocaleString: return "toLocaleString";
case Id_join: return "join";
case Id_reverse: return "reverse";
case Id_sort: return "sort";
case Id_push: return "push";
case Id_pop: return "pop";
case Id_shift: return "shift";
case Id_unshift: return "unshift";
case Id_splice: return "splice";
case Id_concat: return "concat";
case Id_slice: return "slice";
}
}
return null;
}
private static final int
Id_length = 1,
MAX_INSTANCE_ID = 1;
{ setMaxId(MAX_INSTANCE_ID); }
protected int mapNameToId(String s)
{
if (s.equals("length")) { return Id_length; }
else if (prototypeFlag) {
return toPrototypeId(s);
}
return 0;
}
// #string_id_map#
private static int toPrototypeId(String s)
{
int id;
// #generated# Last update: 2001-04-23 11:46:01 GMT+02:00
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 3: X="pop";id=Id_pop; break L;
case 4: c=s.charAt(0);
if (c=='j') { X="join";id=Id_join; }
else if (c=='p') { X="push";id=Id_push; }
else if (c=='s') { X="sort";id=Id_sort; }
break L;
case 5: c=s.charAt(1);
if (c=='h') { X="shift";id=Id_shift; }
else if (c=='l') { X="slice";id=Id_slice; }
break L;
case 6: c=s.charAt(0);
if (c=='c') { X="concat";id=Id_concat; }
else if (c=='l') { X="length";id=Id_length; }
else if (c=='s') { X="splice";id=Id_splice; }
break L;
case 7: c=s.charAt(0);
if (c=='r') { X="reverse";id=Id_reverse; }
else if (c=='u') { X="unshift";id=Id_unshift; }
break L;
case 8: X="toString";id=Id_toString; break L;
case 11: X="constructor";id=Id_constructor; break L;
case 14: X="toLocaleString";id=Id_toLocaleString; break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
return id;
}
private static final int
Id_constructor = MAX_INSTANCE_ID + 1,
Id_toString = MAX_INSTANCE_ID + 2,
Id_toLocaleString = MAX_INSTANCE_ID + 3,
Id_join = MAX_INSTANCE_ID + 4,
Id_reverse = MAX_INSTANCE_ID + 5,
Id_sort = MAX_INSTANCE_ID + 6,
Id_push = MAX_INSTANCE_ID + 7,
Id_pop = MAX_INSTANCE_ID + 8,
Id_shift = MAX_INSTANCE_ID + 9,
Id_unshift = MAX_INSTANCE_ID + 10,
Id_splice = MAX_INSTANCE_ID + 11,
Id_concat = MAX_INSTANCE_ID + 12,
Id_slice = MAX_INSTANCE_ID + 13,
MAX_PROTOTYPE_ID = MAX_INSTANCE_ID + 13;
// #/string_id_map#
private long length;
private Object[] dense;
private static final int maximumDenseLength = 10000;
private boolean prototypeFlag;
private static final boolean check = true && Context.check;
}
| true | true | private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
Object result = ScriptRuntime.newObject(cx, scope, "Array", null);
int argc = args.length;
if (argc == 0)
return result;
long length = getLengthProperty(thisObj);
/* Convert the first argument into a starting index. */
long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(thisObj, begin);
} else {
for (long last = begin; last != end; last++) {
Scriptable resultArray = (Scriptable)result;
Object temp = getElem(thisObj, last);
setElem(resultArray, last - begin, temp);
}
}
} else if (count == 0
&& cx.getLanguageVersion() == Context.VERSION_1_2)
{
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Context.getUndefinedValue();
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
ScriptRuntime.setProp(thisObj, "length",
new Double(length + delta), thisObj);
return result;
}
| private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
Object result = ScriptRuntime.newObject(cx, scope, "Array", null);
int argc = args.length;
if (argc == 0)
return result;
long length = getLengthProperty(thisObj);
/* Convert the first argument into a starting index. */
long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(thisObj, begin);
} else {
for (long last = begin; last != end; last++) {
Scriptable resultArray = (Scriptable)result;
Object temp = getElem(thisObj, last);
setElem(resultArray, last - begin, temp);
}
}
} else if (count == 0
&& cx.getLanguageVersion() == Context.VERSION_1_2)
{
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Context.getUndefinedValue();
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
ScriptRuntime.setProp(thisObj, "length",
new Double(length + delta), thisObj);
return result;
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/panels/assertions/AddAssertionPanel.java b/src/java/com/eviware/soapui/impl/wsdl/panels/assertions/AddAssertionPanel.java
index cd925fb04..509da0da4 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/panels/assertions/AddAssertionPanel.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/panels/assertions/AddAssertionPanel.java
@@ -1,603 +1,603 @@
/*
* soapUI, copyright (C) 2004-2012 smartbear.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.panels.assertions;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import javax.swing.AbstractAction;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.impl.rest.RestService;
import com.eviware.soapui.impl.wsdl.WsdlInterface;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.actions.project.SimpleDialog;
import com.eviware.soapui.impl.wsdl.support.HelpUrls;
import com.eviware.soapui.impl.wsdl.teststeps.assertions.TestAssertionRegistry;
import com.eviware.soapui.impl.wsdl.teststeps.assertions.recent.RecentAssertionHandler;
import com.eviware.soapui.model.ModelItem;
import com.eviware.soapui.model.iface.Interface;
import com.eviware.soapui.model.support.ModelSupport;
import com.eviware.soapui.model.testsuite.Assertable;
import com.eviware.soapui.model.testsuite.TestAssertion;
import com.eviware.soapui.settings.AssertionDescriptionSettings;
import com.eviware.soapui.support.UISupport;
import com.eviware.soapui.support.action.swing.ActionList;
import com.eviware.soapui.support.action.swing.DefaultActionList;
import com.eviware.soapui.support.components.JXToolBar;
import com.eviware.soapui.support.components.SimpleForm;
import com.l2fprod.common.swing.renderer.DefaultCellRenderer;
public class AddAssertionPanel extends SimpleDialog
{
/**
*
*/
private static final long serialVersionUID = 5770245094548607912L;
//Changed categoriesList to a table to be able to disable rows from the list
private CategoriesListTable categoriesListTable;
private AssertionsListTable assertionsTable;
private Assertable assertable;
public static final String NO_PROPERTY_SELECTED = "<No Property>";
private AddAssertionAction addAssertionAction;
private AssertionsListTableModel assertionsListTableModel;
private AssertionCategoriesTableModel categoriesTableModel;
public AssertionsListTableModel getAssertionsListTableModel()
{
return assertionsListTableModel;
}
// private JPanel assertionListPanel;
private SortedSet<AssertionListEntry> assertions;
private ListSelectionListener selectionListener;
private LinkedHashMap<String, SortedSet<AssertionListEntry>> categoriesAssertionsMap;
private SimpleForm assertionsForm;
private JCheckBox hideDescCB;
private AssertionEntryRenderer assertionEntryRenderer = new AssertionEntryRenderer();
private CategoryListRenderer categoriesListRenderer = new CategoryListRenderer();
private InternalHideDescListener hideDescListener = new InternalHideDescListener();
protected RecentAssertionHandler recentAssertionHandler = new RecentAssertionHandler();
private AssertionListMouseAdapter mouseAdapter = new AssertionListMouseAdapter();
private String selectedCategory;
public AddAssertionPanel( Assertable assertable )
{
super( "Add Assertion", "Select the source property and which assertion to apply below ",
HelpUrls.ADD_ASSERTION_PANEL );
this.assertable = assertable;
assertionEntryRenderer.setAssertable( assertable );
categoriesListRenderer.setAssertable( assertable );
selectionListener = new InternalListSelectionListener();
categoriesAssertionsMap = AssertionCategoryMapping
.getCategoriesAssertionsMap( assertable, recentAssertionHandler );
// load interfaces or have a issue with table and cell renderer
WsdlProject project = ( WsdlProject )ModelSupport.getModelItemProject( assertable.getModelItem() );
for( Interface inf : project.getInterfaceList() )
try
{
if( inf instanceof WsdlInterface )
( ( WsdlInterface )inf ).getWsdlContext().loadIfNecessary();
else
( ( RestService )inf ).getDefinitionContext().loadIfNecessary();
}
catch( Exception e )
{
// TODO Improve this
e.printStackTrace();
}
}
public RecentAssertionHandler getRecentAssertionHandler()
{
return recentAssertionHandler;
}
public AssertionEntryRenderer getAssertionEntryRenderer()
{
return assertionEntryRenderer;
}
public String getSelectedCategory()
{
return selectedCategory;
}
protected String getSelectedPropertyName()
{
return NO_PROPERTY_SELECTED;
}
public void setAssertable( Assertable assertable )
{
this.assertable = assertable;
}
public Assertable getAssertable()
{
return assertable;
}
@Override
protected Component buildContent()
{
JPanel mainPanel = new JPanel( new BorderLayout() );
JSplitPane splitPane = UISupport.createHorizontalSplit( buildCategoriesList(), buildAssertionsList() );
splitPane.setDividerLocation( 220 );
getAssertionsTable().setSelectable( true );
JXToolBar toolbar = UISupport.createSmallToolbar();
hideDescCB = new JCheckBox( "Hide descriptions" );
hideDescCB.setOpaque( false );
hideDescCB.addItemListener( hideDescListener );
hideDescCB
.setSelected( SoapUI.getSettings().getBoolean( AssertionDescriptionSettings.SHOW_ASSERTION_DESCRIPTION ) );
toolbar.add( new JLabel( "Assertions" ) );
toolbar.addGlue();
toolbar.add( hideDescCB );
mainPanel.add( toolbar, BorderLayout.NORTH );
mainPanel.add( splitPane, BorderLayout.CENTER );
return mainPanel;
}
public AssertionListMouseAdapter getMouseAdapter()
{
return mouseAdapter;
}
protected Component buildAssertionsList()
{
assertionsForm = new SimpleForm();
assertionsListTableModel = new AssertionsListTableModel();
assertionsTable = new AssertionsListTable( assertionsListTableModel );
int selectedRow = categoriesListTable.getSelectedRow();
String category = ( String )categoriesListTable.getModel().getValueAt( selectedRow, 0 );
if( category != null && categoriesAssertionsMap.containsKey( category ) )
{
assertions = categoriesAssertionsMap.get( category );
assertionsListTableModel.setListEntriesSet( assertions );
}
assertionsTable.setTableHeader( null );
assertionsTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
assertionsTable.getSelectionModel().addListSelectionListener( selectionListener );
assertionsTable.setEditable( false );
assertionsTable.setGridColor( Color.BLACK );
assertionsTable.addMouseListener( mouseAdapter );
assertionsTable.getColumnModel().getColumn( 0 ).setCellRenderer( assertionEntryRenderer );
assertionsForm.addComponent( assertionsTable );
return new JScrollPane( assertionsForm.getPanel() );
}
private Component buildCategoriesList()
{
JPanel panel = new JPanel( new BorderLayout() );
categoriesTableModel = new AssertionCategoriesTableModel();
categoriesTableModel.setLisetEntriesSet( categoriesAssertionsMap.keySet() );
categoriesListTable = new CategoriesListTable( categoriesTableModel );
categoriesListTable.setTableHeader( null );
categoriesListTable.setEditable( false );
categoriesListTable.setGridColor( Color.BLACK );
categoriesListTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
categoriesListTable.getSelectionModel().setSelectionInterval( 0, 0 );
renderAssertions();
populateSelectableCategoriesIndexes();
categoriesListTable.getSelectionModel().addListSelectionListener( new ListSelectionListener()
{
@Override
public void valueChanged( ListSelectionEvent arg0 )
{
renderAssertionsTable();
}
} );
categoriesListTable.getColumnModel().getColumn( 0 ).setCellRenderer( categoriesListRenderer );
panel.add( new JScrollPane( categoriesListTable ) );
return panel;
}
protected void renderAssertionsTable()
{
int selectedRow = categoriesListTable.getSelectedRow();
if( selectedRow > -1 )
{
selectedCategory = ( String )categoriesListTable.getModel().getValueAt( selectedRow, 0 );
if( selectedCategory != null && categoriesAssertionsMap.containsKey( selectedCategory ) )
{
assertions = categoriesAssertionsMap.get( selectedCategory );
assertionsListTableModel.setListEntriesSet( assertions );
renderAssertions();
populateNonSelectableAssertionIndexes();
assertionsListTableModel.fireTableDataChanged();
}
}
}
protected void renderCategoriesTable()
{
categoriesListRenderer.setAssertable( getAssertable() );
populateSelectableCategoriesIndexes();
categoriesTableModel.fireTableDataChanged();
}
protected void renderAssertions()
{
}
protected void populateNonSelectableAssertionIndexes()
{
getAssertionsTable().setSelectable( true );
SortedSet<AssertionListEntry> assertionsList = getCategoriesAssertionsMap().get( getSelectedCategory() );
List<Integer> assertionsIndexList = new ArrayList<Integer>();
for( int i = 0; i < assertionsList.size(); i++ )
{
AssertionListEntry assertionListEntry = ( AssertionListEntry )assertionsList.toArray()[i];
if( !isAssertionApplicable( assertionListEntry.getTypeId() ) )
assertionsIndexList.add( i );
}
getAssertionsTable().setNonSelectableIndexes( assertionsIndexList );
}
protected void populateSelectableCategoriesIndexes()
{
getCategoriesListTable().setSelectable( true );
List<Integer> categoriesIndexList = new ArrayList<Integer>();
Set<String> ctgs = getCategoriesAssertionsMap().keySet();
for( int j = 0; j < ctgs.size(); j++ )
{
String selCat = ( String )ctgs.toArray()[j];
SortedSet<AssertionListEntry> assertionsList = getCategoriesAssertionsMap().get( selCat );
for( int i = 0; i < assertionsList.size(); i++ )
{
AssertionListEntry assertionListEntry = ( AssertionListEntry )assertionsList.toArray()[i];
if( isAssertionApplicable( assertionListEntry.getTypeId() ) )
{
categoriesIndexList.add( j );
break;
}
}
}
getCategoriesListTable().setSelectableIndexes( categoriesIndexList );
}
protected boolean isAssertionApplicable( String assertionType )
{
return TestAssertionRegistry.getInstance().canAssert( assertionType, assertable );
}
protected boolean isAssertionApplicable( String assertionType, ModelItem modelItem, String property )
{
//property is only used for adding assertions with selecting source and property,
//therefore here can be empty string, but gets its meaning in Override of this method
return TestAssertionRegistry.getInstance().canAssert( assertionType, assertable );
}
protected void enableCategoriesList( boolean enable )
{
categoriesListTable.setEnabled( enable );
}
@Override
protected boolean handleOk()
{
setVisible( false );
int selectedRow = assertionsTable.getSelectedRow();
String selection = ( ( AssertionListEntry )assertionsListTableModel.getValueAt( selectedRow, 0 ) ).getName();
if( selection == null )
return false;
if( !TestAssertionRegistry.getInstance().canAddMultipleAssertions( selection, assertable ) )
{
UISupport.showErrorMessage( "This assertion can only be added once" );
return false;
}
TestAssertion assertion = assertable.addAssertion( selection );
if( assertion == null )
{
UISupport.showErrorMessage( "Failed to add assertion" );
return false;
}
recentAssertionHandler.add( selection );
if( assertion.isConfigurable() )
{
assertion.configure();
return true;
}
return true;
}
@Override
public ActionList buildActions( String url, boolean okAndCancel )
{
DefaultActionList actions = new DefaultActionList( "Actions" );
if( url != null )
actions.addAction( new HelpAction( url ) );
addAssertionAction = new AddAssertionAction();
actions.addAction( addAssertionAction );
if( okAndCancel )
{
actions.addAction( new CancelAction() );
actions.setDefaultAction( addAssertionAction );
}
return actions;
}
protected final class AddAssertionAction extends AbstractAction
{
/**
*
*/
private static final long serialVersionUID = 4741995448420710392L;
public AddAssertionAction()
{
super( "Add" );
setEnabled( false );
}
public void actionPerformed( ActionEvent e )
{
handleOk();
}
}
private class InternalListSelectionListener implements ListSelectionListener
{
@Override
public void valueChanged( ListSelectionEvent e )
{
if( assertionsTable.getSelectedRow() >= 0 )
{
addAssertionAction.setEnabled( true );
}
else
{
addAssertionAction.setEnabled( false );
}
}
}
private class InternalHideDescListener implements ItemListener
{
@Override
public void itemStateChanged( ItemEvent arg0 )
{
assertionsTable.getColumnModel().getColumn( 0 ).setCellRenderer( assertionEntryRenderer );
assertionsListTableModel.fireTableDataChanged();
SoapUI.getSettings().setBoolean( AssertionDescriptionSettings.SHOW_ASSERTION_DESCRIPTION,
arg0.getStateChange() == ItemEvent.SELECTED );
}
}
public void release()
{
assertionsTable.getSelectionModel().removeListSelectionListener( selectionListener );
assertionsTable.removeMouseListener( mouseAdapter );
hideDescCB.removeItemListener( hideDescListener );
}
protected class AssertionEntryRenderer extends DefaultCellRenderer
{
/**
*
*/
private static final long serialVersionUID = -6843334509897580699L;
private Assertable assertable;
private Font boldFont;
public void setAssertable( Assertable assertable )
{
this.assertable = assertable;
}
@Override
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column )
{
boldFont = getFont().deriveFont( Font.BOLD );
AssertionListEntry entry = ( AssertionListEntry )value;
String type = TestAssertionRegistry.getInstance().getAssertionTypeForName( entry.getName() );
boolean canAssert = false;
boolean disable = true;
JLabel label;
JTextArea descText;
JLabel disabledInfo;
if( type != null && assertable != null && assertable.getModelItem() != null )
{
canAssert = isAssertionApplicable( type, assertable.getModelItem(), getSelectedPropertyName() );
disable = !categoriesListTable.isEnabled() || !canAssert;
}
String str = entry.getName();
label = new JLabel( str );
label.setFont( boldFont );
descText = new JTextArea( ( ( AssertionListEntry )value ).getDescription() );
descText.setSize( new Dimension( 80, 20 ) );
descText.setLineWrap( true );
descText.setWrapStyleWord( true );
- descText.setOpaque( true );
disabledInfo = new JLabel( "Not applicable with selected Source and Property" );
+ descText.setFont( disabledInfo.getFont() );
if( disable )
{
label.setForeground( Color.LIGHT_GRAY );
descText.setForeground( Color.LIGHT_GRAY );
disabledInfo.setForeground( Color.LIGHT_GRAY );
}
SimpleForm form = new SimpleForm();
form.addComponent( label );
if( !isHideDescriptionSelected() )
{
form.addComponent( descText );
// if( disable )
// {
// form.addComponent( disabledInfo );
// }
getAssertionsTable().setRowHeight( 70 );
}
else
{
if( disable )
{
form.addComponent( disabledInfo );
}
getAssertionsTable().setRowHeight( 40 );
}
if( isSelected )
{
descText.setBackground( Color.LIGHT_GRAY );
form.getPanel().setBackground( Color.LIGHT_GRAY );
}
else
{
descText.setBackground( Color.WHITE );
form.getPanel().setBackground( Color.WHITE );
}
return form.getPanel();
}
}
protected class CategoryListRenderer extends DefaultCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Assertable assertable;
public void setAssertable( Assertable assertable )
{
this.assertable = assertable;
}
@Override
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column )
{
String categoryName = ( String )value;
boolean disabled = true;
Font boldFont = getFont().deriveFont( Font.BOLD );
SortedSet<AssertionListEntry> assertions = categoriesAssertionsMap.get( categoryName );
for( AssertionListEntry assertionListEntry : assertions )
{
if( isAssertionApplicable( assertionListEntry.getTypeId() ) )
{
disabled = false;
break;
}
}
JLabel label = new JLabel( categoryName );
SimpleForm form = new SimpleForm();
form.addComponent( label );
label.setFont( boldFont );
if( disabled || !( ( CategoriesListTable )table ).isSelectable( row ) )
{
label.setForeground( Color.GRAY );
}
if( isSelected )
{
form.getPanel().setBackground( Color.LIGHT_GRAY );
}
else
{
form.getPanel().setBackground( Color.WHITE );
}
return form.getPanel();
}
}
protected boolean isHideDescriptionSelected()
{
return hideDescCB.isSelected();
}
@Override
protected void beforeShow()
{
setSize( new Dimension( 650, 500 ) );
}
public void setCategoriesAssertionsMap( LinkedHashMap<String, SortedSet<AssertionListEntry>> categoriesAssertionsMap )
{
this.categoriesAssertionsMap = categoriesAssertionsMap;
}
public LinkedHashMap<String, SortedSet<AssertionListEntry>> getCategoriesAssertionsMap()
{
return categoriesAssertionsMap;
}
public class AssertionListMouseAdapter extends MouseAdapter
{
@Override
public void mouseClicked( MouseEvent e )
{
if( e.getClickCount() == 2 && !assertionsTable.getSelectionModel().isSelectionEmpty() )
{
handleOk();
}
}
}
public AssertionsListTable getAssertionsTable()
{
return assertionsTable;
}
public CategoriesListTable getCategoriesListTable()
{
return categoriesListTable;
}
public AddAssertionAction getAddAssertionAction()
{
return addAssertionAction;
}
public void setSelectionListener( ListSelectionListener selectionListener )
{
this.selectionListener = selectionListener;
}
}
| false | true | public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column )
{
boldFont = getFont().deriveFont( Font.BOLD );
AssertionListEntry entry = ( AssertionListEntry )value;
String type = TestAssertionRegistry.getInstance().getAssertionTypeForName( entry.getName() );
boolean canAssert = false;
boolean disable = true;
JLabel label;
JTextArea descText;
JLabel disabledInfo;
if( type != null && assertable != null && assertable.getModelItem() != null )
{
canAssert = isAssertionApplicable( type, assertable.getModelItem(), getSelectedPropertyName() );
disable = !categoriesListTable.isEnabled() || !canAssert;
}
String str = entry.getName();
label = new JLabel( str );
label.setFont( boldFont );
descText = new JTextArea( ( ( AssertionListEntry )value ).getDescription() );
descText.setSize( new Dimension( 80, 20 ) );
descText.setLineWrap( true );
descText.setWrapStyleWord( true );
descText.setOpaque( true );
disabledInfo = new JLabel( "Not applicable with selected Source and Property" );
if( disable )
{
label.setForeground( Color.LIGHT_GRAY );
descText.setForeground( Color.LIGHT_GRAY );
disabledInfo.setForeground( Color.LIGHT_GRAY );
}
SimpleForm form = new SimpleForm();
form.addComponent( label );
if( !isHideDescriptionSelected() )
{
form.addComponent( descText );
// if( disable )
// {
// form.addComponent( disabledInfo );
// }
getAssertionsTable().setRowHeight( 70 );
}
else
{
if( disable )
{
form.addComponent( disabledInfo );
}
getAssertionsTable().setRowHeight( 40 );
}
if( isSelected )
{
descText.setBackground( Color.LIGHT_GRAY );
form.getPanel().setBackground( Color.LIGHT_GRAY );
}
else
{
descText.setBackground( Color.WHITE );
form.getPanel().setBackground( Color.WHITE );
}
return form.getPanel();
}
| public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column )
{
boldFont = getFont().deriveFont( Font.BOLD );
AssertionListEntry entry = ( AssertionListEntry )value;
String type = TestAssertionRegistry.getInstance().getAssertionTypeForName( entry.getName() );
boolean canAssert = false;
boolean disable = true;
JLabel label;
JTextArea descText;
JLabel disabledInfo;
if( type != null && assertable != null && assertable.getModelItem() != null )
{
canAssert = isAssertionApplicable( type, assertable.getModelItem(), getSelectedPropertyName() );
disable = !categoriesListTable.isEnabled() || !canAssert;
}
String str = entry.getName();
label = new JLabel( str );
label.setFont( boldFont );
descText = new JTextArea( ( ( AssertionListEntry )value ).getDescription() );
descText.setSize( new Dimension( 80, 20 ) );
descText.setLineWrap( true );
descText.setWrapStyleWord( true );
disabledInfo = new JLabel( "Not applicable with selected Source and Property" );
descText.setFont( disabledInfo.getFont() );
if( disable )
{
label.setForeground( Color.LIGHT_GRAY );
descText.setForeground( Color.LIGHT_GRAY );
disabledInfo.setForeground( Color.LIGHT_GRAY );
}
SimpleForm form = new SimpleForm();
form.addComponent( label );
if( !isHideDescriptionSelected() )
{
form.addComponent( descText );
// if( disable )
// {
// form.addComponent( disabledInfo );
// }
getAssertionsTable().setRowHeight( 70 );
}
else
{
if( disable )
{
form.addComponent( disabledInfo );
}
getAssertionsTable().setRowHeight( 40 );
}
if( isSelected )
{
descText.setBackground( Color.LIGHT_GRAY );
form.getPanel().setBackground( Color.LIGHT_GRAY );
}
else
{
descText.setBackground( Color.WHITE );
form.getPanel().setBackground( Color.WHITE );
}
return form.getPanel();
}
|
diff --git a/jse/src/main/java/com/alonsoruibal/chess/bitboard/MagicNumbersGenerator.java b/jse/src/main/java/com/alonsoruibal/chess/bitboard/MagicNumbersGenerator.java
index 6bf1a43..471a176 100644
--- a/jse/src/main/java/com/alonsoruibal/chess/bitboard/MagicNumbersGenerator.java
+++ b/jse/src/main/java/com/alonsoruibal/chess/bitboard/MagicNumbersGenerator.java
@@ -1,126 +1,126 @@
package com.alonsoruibal.chess.bitboard;
import java.util.Random;
/**
* Generates magic numbers without postmask!!!! by try and error
*
* @author rui
*/
public class MagicNumbersGenerator {
public final static Random random = new Random(System.currentTimeMillis());
/**
* Generates a randon number with few bits
*
* @return
*/
private long randomFewbits() {
return random.nextLong() & random.nextLong() & random.nextLong() & random.nextLong() & random.nextLong();
}
/**
* Fills pieces from a mask. Neccesary for magic generation variable bits is
* the mask bytes number index goes from 0 to 2^bits
*/
private long generatePieces(int index, int bits, long mask) {
int i;
long lsb;
long result = 0L;
for (i = 0; i < bits; i++) {
lsb = mask & (-mask);
mask ^= lsb; // Deactivates lsb bit of the mask to get next bit next
// time
if ((index & (1 << i)) != 0)
result |= lsb; // if bit is set to 1
}
return result;
}
/**
* Routine to generate our own magic bits
*
* @param index
* of the square
* @param m
* bits needed
* @param bishop
* is a bishop or rook?
* @return
*/
long findMagics(byte index, byte m, boolean bishop) {
long mask, magic;
long attack[] = new long[4096];
long block[] = new long[4096];
long magicAttack[] = new long[4096];
int i, j, k, n;
boolean fail;
BitboardAttacksMagic attacks = (BitboardAttacksMagic) BitboardAttacks.getInstance();
mask = (bishop ? attacks.bishopMask[index] : attacks.rookMask[index]);
// System.out.println("mask:\n" + BitboardUtils.toString(mask));
// Fill Attack tables, those are very big!
n = BitboardUtils.popCount(mask);
for (i = 0; i < (1 << n); i++) {
block[i] = generatePieces(i, n, mask);
// System.out.println("b:\n" + BitboardUtils.toString(block[i]));
- attack[i] = bishop ? bbAttacks.getBishopShiftAttacks(BitboardUtils.index2Square(index), block[i]) : bbAttacks.getRookShiftAttacks(
+ attack[i] = bishop ? attacks.getBishopShiftAttacks(BitboardUtils.index2Square(index), block[i]) : attacks.getRookShiftAttacks(
BitboardUtils.index2Square(index), block[i]);
// System.out.println("attack:\n" +
// BitboardUtils.toString(attack[i]));
}
for (k = 0; k < 1000000000; k++) {
// test new magic
magic = randomFewbits();
if (BitboardUtils.popCount((mask * magic) & 0xFF00000000000000L) < 6)
continue;
// First, empty magic attack table
for (i = 0; i < 4096; i++)
magicAttack[i] = 0L;
for (i = 0, fail = false; !fail && (i < (1 << n)); i++) {
j = BitboardAttacksMagic.magicTransform(block[i], magic, m);
if (magicAttack[j] == 0L) {
magicAttack[j] = attack[i];
} else if (magicAttack[j] != attack[i]) {
fail = true;
}
// Verifies that using a postmask is not necessary
if (attack[i] != (attack[i] & (bishop ? attacks.bishop[index] : attacks.rook[index]))) {
fail = true;
}
}
if (!fail)
return magic;
}
System.out.println("Error!\n");
return 0L;
}
public static void main(String args[]) {
byte index;
MagicNumbersGenerator magic = new MagicNumbersGenerator();
System.out.print("public final static long rookMagicNumber[] = {");
for (index = 0; index < 64; index++) {
System.out.print("0x" + Long.toHexString(magic.findMagics(index, BitboardAttacksMagic.rookShiftBits[index], false)) + "L"
+ (index != 63 ? ", " : ""));
}
System.out.println("};");
System.out.print("public final static long bishopMagicNumber[] = {");
for (index = 0; index < 64; index++) {
System.out.print("0x" + Long.toHexString(magic.findMagics(index, BitboardAttacksMagic.bishopShiftBits[index], true)) + "L"
+ (index != 63 ? ", " : ""));
}
System.out.println("};");
}
}
| true | true | long findMagics(byte index, byte m, boolean bishop) {
long mask, magic;
long attack[] = new long[4096];
long block[] = new long[4096];
long magicAttack[] = new long[4096];
int i, j, k, n;
boolean fail;
BitboardAttacksMagic attacks = (BitboardAttacksMagic) BitboardAttacks.getInstance();
mask = (bishop ? attacks.bishopMask[index] : attacks.rookMask[index]);
// System.out.println("mask:\n" + BitboardUtils.toString(mask));
// Fill Attack tables, those are very big!
n = BitboardUtils.popCount(mask);
for (i = 0; i < (1 << n); i++) {
block[i] = generatePieces(i, n, mask);
// System.out.println("b:\n" + BitboardUtils.toString(block[i]));
attack[i] = bishop ? bbAttacks.getBishopShiftAttacks(BitboardUtils.index2Square(index), block[i]) : bbAttacks.getRookShiftAttacks(
BitboardUtils.index2Square(index), block[i]);
// System.out.println("attack:\n" +
// BitboardUtils.toString(attack[i]));
}
for (k = 0; k < 1000000000; k++) {
// test new magic
magic = randomFewbits();
if (BitboardUtils.popCount((mask * magic) & 0xFF00000000000000L) < 6)
continue;
// First, empty magic attack table
for (i = 0; i < 4096; i++)
magicAttack[i] = 0L;
for (i = 0, fail = false; !fail && (i < (1 << n)); i++) {
j = BitboardAttacksMagic.magicTransform(block[i], magic, m);
if (magicAttack[j] == 0L) {
magicAttack[j] = attack[i];
} else if (magicAttack[j] != attack[i]) {
fail = true;
}
// Verifies that using a postmask is not necessary
if (attack[i] != (attack[i] & (bishop ? attacks.bishop[index] : attacks.rook[index]))) {
fail = true;
}
}
if (!fail)
return magic;
}
System.out.println("Error!\n");
return 0L;
}
| long findMagics(byte index, byte m, boolean bishop) {
long mask, magic;
long attack[] = new long[4096];
long block[] = new long[4096];
long magicAttack[] = new long[4096];
int i, j, k, n;
boolean fail;
BitboardAttacksMagic attacks = (BitboardAttacksMagic) BitboardAttacks.getInstance();
mask = (bishop ? attacks.bishopMask[index] : attacks.rookMask[index]);
// System.out.println("mask:\n" + BitboardUtils.toString(mask));
// Fill Attack tables, those are very big!
n = BitboardUtils.popCount(mask);
for (i = 0; i < (1 << n); i++) {
block[i] = generatePieces(i, n, mask);
// System.out.println("b:\n" + BitboardUtils.toString(block[i]));
attack[i] = bishop ? attacks.getBishopShiftAttacks(BitboardUtils.index2Square(index), block[i]) : attacks.getRookShiftAttacks(
BitboardUtils.index2Square(index), block[i]);
// System.out.println("attack:\n" +
// BitboardUtils.toString(attack[i]));
}
for (k = 0; k < 1000000000; k++) {
// test new magic
magic = randomFewbits();
if (BitboardUtils.popCount((mask * magic) & 0xFF00000000000000L) < 6)
continue;
// First, empty magic attack table
for (i = 0; i < 4096; i++)
magicAttack[i] = 0L;
for (i = 0, fail = false; !fail && (i < (1 << n)); i++) {
j = BitboardAttacksMagic.magicTransform(block[i], magic, m);
if (magicAttack[j] == 0L) {
magicAttack[j] = attack[i];
} else if (magicAttack[j] != attack[i]) {
fail = true;
}
// Verifies that using a postmask is not necessary
if (attack[i] != (attack[i] & (bishop ? attacks.bishop[index] : attacks.rook[index]))) {
fail = true;
}
}
if (!fail)
return magic;
}
System.out.println("Error!\n");
return 0L;
}
|
diff --git a/src/com/dmdirc/addons/ui_swing/UIUtilities.java b/src/com/dmdirc/addons/ui_swing/UIUtilities.java
index 88f2d342..d90931a2 100644
--- a/src/com/dmdirc/addons/ui_swing/UIUtilities.java
+++ b/src/com/dmdirc/addons/ui_swing/UIUtilities.java
@@ -1,438 +1,443 @@
/*
* Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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 com.dmdirc.addons.ui_swing;
import com.dmdirc.addons.ui_swing.actions.RedoAction;
import com.dmdirc.addons.ui_swing.actions.UndoAction;
import com.dmdirc.addons.ui_swing.components.DMDircUndoableEditListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.util.ReturnableThread;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import net.miginfocom.layout.PlatformDefaults;
/**
* UI constants.
*/
public final class UIUtilities {
/** Size of a large border. */
public static final int LARGE_BORDER = 10;
/** Size of a small border. */
public static final int SMALL_BORDER = 5;
/** Standard button size. */
public static final Dimension BUTTON_SIZE = new Dimension(100, 25);
/** Not intended to be instatiated. */
private UIUtilities() {
}
/**
* Adds an undo manager and associated key bindings to the specified text
* component.
*
* @param component component Text component to add an undo manager to
*/
public static void addUndoManager(final JTextComponent component) {
final UndoManager undoManager = new UndoManager();
// Listen for undo and redo events
component.getDocument().addUndoableEditListener(
new DMDircUndoableEditListener(undoManager));
// Create an undo action and add it to the text component
component.getActionMap().put("Undo", new UndoAction(undoManager));
// Bind the undo action to ctl-Z
component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
// Create a redo action and add it to the text component
component.getActionMap().put("Redo", new RedoAction(undoManager));
// Bind the redo action to ctl-Y
component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
}
/**
* Initialises any settings required by this UI (this is always called
* before any aspect of the UI is instansiated).
*
* @throws UnsupportedOperationException If unable to switch to the system
* look and feel
*/
public static void initUISettings() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (ClassNotFoundException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (UnsupportedLookAndFeelException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (IllegalAccessException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
}
UIManager.put("swing.useSystemFontSettings", true);
if (getTabbedPaneOpaque()) {
// If this is set on windows then .setOpaque seems to be ignored
// and still used as true
UIManager.put("TabbedPane.contentOpaque", false);
}
UIManager.put("swing.boldMetal", false);
UIManager.put("InternalFrame.useTaskBar", false);
UIManager.put("SplitPaneDivider.border",
BorderFactory.createEmptyBorder());
UIManager.put("Tree.scrollsOnExpand", true);
UIManager.put("Tree.scrollsHorizontallyAndVertically", true);
UIManager.put("SplitPane.border", BorderFactory.createEmptyBorder());
UIManager.put("SplitPane.dividerSize", (int) PlatformDefaults.
getPanelInsets(0).getValue());
UIManager.put("TreeUI", "javax.swing.plaf.metal.MetalTreeUI");
+ if ("com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(UIManager
+ .getLookAndFeel().getClass().getName())) {
+ UIManager.put("TitledBorder.titleColor", UIManager.getColor(
+ "Label.foreground"));
+ }
PlatformDefaults.setDefaultRowAlignmentBaseline(false);
}
/**
* Returns the class name of the look and feel from its display name.
*
* @param displayName Look and feel display name
*
* @return Look and feel class name or a zero length string
*/
public static String getLookAndFeel(final String displayName) {
if (displayName == null || displayName.isEmpty() ||
"Native".equals(displayName)) {
return UIManager.getSystemLookAndFeelClassName();
}
final StringBuilder classNameBuilder = new StringBuilder();
for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if (laf.getName().equals(displayName)) {
classNameBuilder.append(laf.getClassName());
break;
}
}
if (classNameBuilder.length() == 0) {
classNameBuilder.append(UIManager.getSystemLookAndFeelClassName());
}
return classNameBuilder.toString();
}
/**
* Invokes and waits for the specified runnable, executed on the EDT.
*
* @param runnable Thread to be executed
*/
public static void invokeAndWait(final Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (InterruptedException ex) {
//Ignore
} catch (InvocationTargetException ex) {
Logger.appError(ErrorLevel.HIGH, "Unable to execute thread.", ex);
}
}
}
/**
* Invokes and waits for the specified runnable, executed on the EDT.
*
* @param <T> The return type of the returnable thread
* @param returnable Thread to be executed
* @return Result from the compelted thread
*/
public static <T> T invokeAndWait(final ReturnableThread<T> returnable) {
if (SwingUtilities.isEventDispatchThread()) {
returnable.run();
} else {
try {
SwingUtilities.invokeAndWait(returnable);
} catch (InterruptedException ex) {
//Ignore
} catch (InvocationTargetException ex) {
Logger.appError(ErrorLevel.HIGH, "Unable to execute thread.", ex);
}
}
return returnable.getObject();
}
/**
* Queues the runnable to be executed on the EDT.
*
* @param runnable Runnable to be executed.
*/
public static void invokeLater(final Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
SwingUtilities.invokeLater(runnable);
}
}
/**
* Check if we are using one of the Windows Look and Feels
*
* @return True iff the current LAF is "Windows" or "Windows Classic"
*/
public static boolean isWindowsUI() {
final String uiname = UIManager.getLookAndFeel().getClass().getName();
final String windows =
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
final String classic =
"com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
return windows.equals(uiname) || classic.equals(uiname);
}
/**
* Get the value to pass to set Opaque on items being added to a JTabbedPane
*
* @return True iff the current LAF is not Windows or OS X.
* @since 0.6
*/
public static boolean getTabbedPaneOpaque() {
final String uiname = UIManager.getLookAndFeel().getClass().getName();
final String windows =
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
final String nimbus = "sun.swing.plaf.nimbus.NimbusLookAndFeel";
return !(windows.equals(uiname) || Apple.isAppleUI() || nimbus.equals(
uiname));
}
/**
* Get the DOWN_MASK for the command/ctrl key.
*
* @return on OSX this returns META_DOWN_MASK, else CTRL_DOWN_MASK
* @since 0.6
*/
public static int getCtrlDownMask() {
return Apple.isAppleUI() ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK;
}
/**
* Get the MASK for the command/ctrl key.
*
* @return on OSX this returns META_MASK, else CTRL_MASK
* @since 0.6
*/
public static int getCtrlMask() {
return Apple.isAppleUI() ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK;
}
/**
* Check if the command/ctrl key is pressed down.
*
* @param e The KeyEvent to check
* @return on OSX this returns e.isMetaDown(), else e.isControlDown()
* @since 0.6
*/
public static boolean isCtrlDown(final KeyEvent e) {
return Apple.isAppleUI() ? e.isMetaDown() : e.isControlDown();
}
/**
* Clips a string if its longer than the specified width.
*
* @param component Component containing string
* @param string String to check
* @param avaiableWidth Available Width
*
* @return String (clipped if required)
*/
public static String clipStringifNeeded(final JComponent component,
final String string, final int avaiableWidth) {
if ((string == null) || (string.equals(""))) {
return "";
}
final FontMetrics fm = component.getFontMetrics(component.getFont());
final int width = SwingUtilities.computeStringWidth(fm, string);
if (width > avaiableWidth) {
return clipString(component, string, avaiableWidth);
}
return string;
}
/**
* Clips the passed string .
*
* @param component Component containing string
* @param string String to check
* @param avaiableWidth Available Width
*
* @return String (clipped if required)
*/
public static String clipString(final JComponent component,
final String string, final int avaiableWidth) {
if ((string == null) || (string.equals(""))) {
return "";
}
final FontMetrics fm = component.getFontMetrics(component.getFont());
final String clipString = "...";
int width = SwingUtilities.computeStringWidth(fm, clipString);
int nChars = 0;
for (int max = string.length(); nChars < max; nChars++) {
width += fm.charWidth(string.charAt(nChars));
if (width > avaiableWidth) {
break;
}
}
return string.substring(0, nChars) + clipString;
}
/**
* Resets the scroll pane to 0,0.
*
* @param scrollPane Scrollpane to reset
*
* @since 0.6.3m1
*/
public static void resetScrollPane(final JScrollPane scrollPane) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
scrollPane.getHorizontalScrollBar().setValue(0);
scrollPane.getVerticalScrollBar().setValue(0);
}
});
}
/**
* Paints the background, either from the config setting or the background
* colour of the textpane.
*
* @param g Graphics object to draw onto
* @param bounds
* @param backgroundImage
* @param backgroundOption
*/
public static void paintBackground(final Graphics2D g,
final Rectangle bounds,
final Image backgroundImage,
final BackgroundOption backgroundOption) {
if (backgroundImage != null) {
switch (backgroundOption) {
case TILED:
paintTiledBackground(g, bounds, backgroundImage);
break;
case SCALE:
paintStretchedBackground(g, bounds, backgroundImage);
break;
case SCALE_ASPECT_RATIO:
paintStretchedAspectRatioBackground(g, bounds, backgroundImage);
break;
case CENTER:
paintCenterBackground(g, bounds, backgroundImage);
break;
default:
break;
}
} else {
paintNoBackground(g, bounds);
}
}
private static void paintNoBackground(final Graphics2D g, final Rectangle bounds) {
g.fill(bounds);
}
private static void paintStretchedBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
g.drawImage(backgroundImage, 0, 0, bounds.width, bounds.height, null);
}
private static void paintCenterBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
final int x = (bounds.width / 2) - (backgroundImage.getWidth(null) / 2);
final int y = (bounds.height / 2) - (backgroundImage.getHeight(null) / 2);
g.drawImage(backgroundImage, x, y, backgroundImage.getWidth(null),
backgroundImage.getHeight(null), null);
}
private static void paintStretchedAspectRatioBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
final double widthratio = bounds.width
/ (double) backgroundImage.getWidth(null);
final double heightratio = bounds.height
/ (double) backgroundImage.getHeight(null);
final double ratio = Math.min(widthratio, heightratio);
final int width = (int) (backgroundImage.getWidth(null) * ratio);
final int height = (int) (backgroundImage.getWidth(null) * ratio);
final int x = (bounds.width / 2) - (width / 2);
final int y = (bounds.height / 2) - (height / 2);
g.drawImage(backgroundImage, x, y, width, height, null);
}
private static void paintTiledBackground(final Graphics2D g,
final Rectangle bounds, final Image backgroundImage) {
final int width = backgroundImage.getWidth(null);
final int height = backgroundImage.getHeight(null);
if (width <= 0 || height <= 0) {
// ARG!
return;
}
for (int x = 0; x < bounds.width; x += width) {
for (int y = 0; y < bounds.height; y += height) {
g.drawImage(backgroundImage, x, y, width, height, null);
}
}
}
}
| true | true | public static void initUISettings() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (ClassNotFoundException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (UnsupportedLookAndFeelException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (IllegalAccessException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
}
UIManager.put("swing.useSystemFontSettings", true);
if (getTabbedPaneOpaque()) {
// If this is set on windows then .setOpaque seems to be ignored
// and still used as true
UIManager.put("TabbedPane.contentOpaque", false);
}
UIManager.put("swing.boldMetal", false);
UIManager.put("InternalFrame.useTaskBar", false);
UIManager.put("SplitPaneDivider.border",
BorderFactory.createEmptyBorder());
UIManager.put("Tree.scrollsOnExpand", true);
UIManager.put("Tree.scrollsHorizontallyAndVertically", true);
UIManager.put("SplitPane.border", BorderFactory.createEmptyBorder());
UIManager.put("SplitPane.dividerSize", (int) PlatformDefaults.
getPanelInsets(0).getValue());
UIManager.put("TreeUI", "javax.swing.plaf.metal.MetalTreeUI");
PlatformDefaults.setDefaultRowAlignmentBaseline(false);
}
| public static void initUISettings() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (ClassNotFoundException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (UnsupportedLookAndFeelException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
} catch (IllegalAccessException ex) {
throw new UnsupportedOperationException("Unable to switch to the " +
"system look and feel", ex);
}
UIManager.put("swing.useSystemFontSettings", true);
if (getTabbedPaneOpaque()) {
// If this is set on windows then .setOpaque seems to be ignored
// and still used as true
UIManager.put("TabbedPane.contentOpaque", false);
}
UIManager.put("swing.boldMetal", false);
UIManager.put("InternalFrame.useTaskBar", false);
UIManager.put("SplitPaneDivider.border",
BorderFactory.createEmptyBorder());
UIManager.put("Tree.scrollsOnExpand", true);
UIManager.put("Tree.scrollsHorizontallyAndVertically", true);
UIManager.put("SplitPane.border", BorderFactory.createEmptyBorder());
UIManager.put("SplitPane.dividerSize", (int) PlatformDefaults.
getPanelInsets(0).getValue());
UIManager.put("TreeUI", "javax.swing.plaf.metal.MetalTreeUI");
if ("com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(UIManager
.getLookAndFeel().getClass().getName())) {
UIManager.put("TitledBorder.titleColor", UIManager.getColor(
"Label.foreground"));
}
PlatformDefaults.setDefaultRowAlignmentBaseline(false);
}
|
diff --git a/src/joren/spawn/Spawn.java b/src/joren/spawn/Spawn.java
index 8dd6fc1..281339a 100644
--- a/src/joren/spawn/Spawn.java
+++ b/src/joren/spawn/Spawn.java
@@ -1,1490 +1,1490 @@
package joren.spawn;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
import org.bukkit.util.config.Configuration;
import org.bukkit.util.config.ConfigurationNode;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
/**
* Spawn
* @version 0.1
* @author jorencombs
*
* Originally intended to be a stripped-down version of the SpawnMob Bukkit plugin (most recently adapted
* by jordanneil23). However, it has been nuked and rewritten enough that there probably isn't much of
* the original code left. Also uses TargetBlock code from toi and Raphfrk
*/
public class Spawn extends JavaPlugin {
public static java.util.logging.Logger log = java.util.logging.Logger.getLogger("Minecraft");
/** Handle to access the Permissions plugin */
public static PermissionHandler Permissions;
/** Name of the plugin, used in output messages */
protected static String name = "Spawn";
/** Path where the plugin's saved information is located */
protected static String path = "plugins" + File.separator + name;
/** Location of the config YML file */
protected static String config = path + File.separator + name + ".yml";
/** Header used for console and player output messages */
protected static String header = "[" + name + "] ";
/** Represents the plugin's YML configuration */
protected static List<String> neverSpawn = new ArrayList<String>();
protected static List<String> neverKill = new ArrayList<String>();
protected static Configuration cfg;
/** True if this plugin is to be used with Permissions, false if not */
protected boolean permissions = false;
/** Limitations on how many entities can be spawned and what the maximum size of a spawned entity should be */
protected int spawnLimit, sizeLimit;
protected double hSpeedLimit;
/**
* Initializes plugin description variables (in case they are different from when written)
* and initiates a reload of the plugin
*/
public void onEnable()
{
PluginDescriptionFile pdfFile = this.getDescription();
name = pdfFile.getName();
header = "[" + name + "] ";
path = "plugins" + File.separator + name;
config = path + File.separator + name + ".yml";
reload();
info("Version " + pdfFile.getVersion() + " enabled.");
}
/**
* Saves plugin configuration to disk so that the plugin can be safely disabled.
*/
public void onDisable() {
save();
log.info("Disabled.");
}
/**
* Reloads the plugin by re-reading the configuration file and setting associated variables
*
* The configuration will be replaced with whatever information is in the file. Any variables that need to be read from the configuration will be initialized.
*
* @return boolean: True if reload was successful. Currently all reloads are considered successful
* since there are fallbacks for cases where the configuration isn't there.
*/
public boolean reload()
{
info("(re)loading...");
File file = new File(config);
cfg = new Configuration(file);
if(!file.exists())
{
warning("Could not find a configuration file, saving a new one...");
if (!saveDefault())
{
warning("Running on default values, but could not save a new configuration file.");
}
}
else
{
cfg.load();
sizeLimit = cfg.getInt("settings.size-limit", 100);
spawnLimit = cfg.getInt("settings.spawn-limit", 300);
hSpeedLimit = cfg.getDouble("settings.horizontal-speed-limit", 10);
permissions = cfg.getBoolean("settings.use-permissions", true);
neverSpawn = cfg.getStringList("never.spawn", neverSpawn);
neverKill = cfg.getStringList("never.kill", neverKill);
if (permissions)
setupPermissions();
}
info("done.");
return true;
}
/**
* Saves a new default configuration file, overwriting old configuration and file in the process
* Any existing configuration will be replaced with the default configuration and saved to disk. Any variables that need to be read from the configuration will be initialized
* @return boolean: True if successful, false otherwise
*/
public boolean saveDefault()
{
info("Resetting configuration file with default values...");
cfg = new Configuration(new File(config));
neverSpawn = Arrays.asList("Animals", "Creature", "Entity", "Explosive", "FallingSand", "Fish", "Flying", "HumanEntity", "LivingEntity", "Monster", "Painting", "Player", "Projectile", "Vehicle", "WaterMob");
neverKill = Arrays.asList("Animals", "Creature", "Entity", "Explosive", "FallingSand", "Fish", "Flying", "HumanEntity", "LivingEntity", "Monster", "Painting", "Player", "Projectile", "Vehicle", "WaterMob");
cfg.setProperty("alias.cavespider", Arrays.asList("CaveSpider"));
cfg.setProperty("alias.chicken", Arrays.asList("Chicken"));
cfg.setProperty("alias.cow", Arrays.asList("Cow"));
cfg.setProperty("alias.creeper", Arrays.asList("Creeper"));
cfg.setProperty("alias.supercreeper", Arrays.asList("Creeper"));
cfg.setProperty("alias.supercreeper-parameters", "/a");
cfg.setProperty("alias.enderman", Arrays.asList("Enderman"));
cfg.setProperty("alias.endermen", Arrays.asList("Enderman"));
cfg.setProperty("alias.ghast", Arrays.asList("Ghast"));
cfg.setProperty("alias.giant", Arrays.asList("Giant"));
cfg.setProperty("alias.pig", Arrays.asList("Pig"));
cfg.setProperty("alias.pigzombie", Arrays.asList("PigZombie"));
cfg.setProperty("alias.zombiepigman", Arrays.asList("PigZombie"));
cfg.setProperty("alias.pigman", Arrays.asList("PigZombie"));
cfg.setProperty("alias.sheep", Arrays.asList("Sheep"));
cfg.setProperty("alias.silverfish", Arrays.asList("Silverfish"));
cfg.setProperty("alias.skeleton", Arrays.asList("Skeleton"));
cfg.setProperty("alias.slime", Arrays.asList("Slime"));
cfg.setProperty("alias.spider", Arrays.asList("Spider"));
cfg.setProperty("alias.squid", Arrays.asList("Squid"));
cfg.setProperty("alias.wolf", Arrays.asList("Wolf"));
cfg.setProperty("alias.werewolf", Arrays.asList("Wolf"));
cfg.setProperty("alias.werewolf-parameters", "/a");
cfg.setProperty("alias.dog", Arrays.asList("Wolf"));
cfg.setProperty("alias.zombie", Arrays.asList("Zombie"));
cfg.setProperty("alias.friendly", Arrays.asList("Chicken", "Cow", "Pig", "Sheep", "Squid"));
cfg.setProperty("alias.hostile", Arrays.asList("CaveSpider", "Creeper", "Enderman", "Ghast", "Giant", "Silverfish", "Skeleton", "Slime", "Spider", "Zombie"));
cfg.setProperty("alias.provoke", Arrays.asList("Enderman", "PigZombie", "Wolf"));
cfg.setProperty("alias.provoke-parameters", "/a");
cfg.setProperty("alias.burnable", Arrays.asList("Enderman", "Skeleton", "Zombie"));
cfg.setProperty("alias.day", Arrays.asList("Chicken", "Cow", "Pig", "Sheep", "Squid"));
cfg.setProperty("alias.night", Arrays.asList("Creeper", "Enderman", "Skeleton", "Spider", "Zombie"));
cfg.setProperty("alias.cave", Arrays.asList("CaveSpider", "Creeper", "Enderman", "Silverfish", "Skeleton", "Slime", "Spider", "Zombie"));
cfg.setProperty("alias.boss", Arrays.asList("Ghast", "Giant"));
cfg.setProperty("alias.flying", Arrays.asList("Ghast"));
cfg.setProperty("alias.mob", Arrays.asList("CaveSpider", "Chicken", "Creeper", "Cow", "Enderman", "Pig", "PigZombie", "Sheep", "Silverfish", "Skeleton", "Slime", "Spider", "Squid", "Wolf", "Zombie"));
cfg.setProperty("alias.kill", Arrays.asList("CaveSpider", "Chicken", "Creeper", "Cow", "Enderman", "Ghast", "Giant", "Pig", "PigZombie", "Sheep", "Silverfish", "Skeleton", "Slime", "Spider", "Squid", "Wolf", "Zombie"));
cfg.setProperty("alias.meat", Arrays.asList("Pig", "Cow", "Chicken"));
cfg.setProperty("alias.meat-parameters", "/f:60");
//Transit
cfg.setProperty("alias.boat", Arrays.asList("Boat"));
cfg.setProperty("alias.cart", Arrays.asList("Minecart"));
cfg.setProperty("alias.minecart", Arrays.asList("Minecart"));
cfg.setProperty("alias.poweredminecart", Arrays.asList("PoweredMinecart"));
cfg.setProperty("alias.locomotive", Arrays.asList("PoweredMinecart"));
cfg.setProperty("alias.storageminecart", Arrays.asList("StorageMinecart"));
cfg.setProperty("alias.train", Arrays.asList("Minecart"));
cfg.setProperty("alias.transit", Arrays.asList("Boat", "Minecart", "PoweredMinecart", "StorageMinecart"));
//Projectiles
cfg.setProperty("alias.arrow", Arrays.asList("Arrow"));
cfg.setProperty("alias.egg", Arrays.asList("Egg"));
cfg.setProperty("alias.fireball", Arrays.asList("Fireball"));
cfg.setProperty("alias.snowball", Arrays.asList("Snowball"));
cfg.setProperty("alias.projectile", Arrays.asList("Arrow", "Egg", "Fireball", "Snowball"));
//Explosives
cfg.setProperty("alias.lightning", Arrays.asList("LightningStrike"));
cfg.setProperty("alias.lightningstrike", Arrays.asList("LightningStrike"));
cfg.setProperty("alias.strike", Arrays.asList("LightningStrike"));
cfg.setProperty("alias.primedtnt", Arrays.asList("PrimedTNT"));
cfg.setProperty("alias.tnt", Arrays.asList("TNTPrimed"));
cfg.setProperty("alias.weather", Arrays.asList("Weather"));
cfg.setProperty("alias.explosive", Arrays.asList("LightningStrike", "PrimedTNT", "Weather"));
//Drops
cfg.setProperty("alias.experience", Arrays.asList("ExperienceOrb"));
cfg.setProperty("alias.experienceorb", Arrays.asList("ExperienceOrb"));
cfg.setProperty("alias.orb", Arrays.asList("ExperienceOrb"));
cfg.setProperty("alias.xp", Arrays.asList("ExperienceOrb"));
cfg.setProperty("alias.xporb", Arrays.asList("ExperienceOrb"));
cfg.setProperty("alias.item", Arrays.asList("Item"));
cfg.setProperty("alias.mirage", Arrays.asList("Item"));
cfg.setProperty("alias.mirage-parameters", "/i:264,0");
cfg.setProperty("alias.fireworks", Arrays.asList("Item"));
cfg.setProperty("alias.fireworks-parameters", "/i:331,0/f:60/v:2");
//Example Player List
cfg.setProperty("player-alias.example", Arrays.asList("JohnDoe", "JohnDoesBrother"));
permissions = false;
spawnLimit = 100;
sizeLimit = 50;
hSpeedLimit = 10;
if (save())
{
reload();
return true;
}
else
return false;
}
/**
* Saves the configuration file, overwriting old file in the process
*
* @return boolean: True if successful, false otherwise.
*/
public boolean save()
{
info("Saving configuration file...");
File dir = new File(path);
cfg.setProperty("settings.use-permissions", permissions);
cfg.setProperty("settings.spawn-limit", spawnLimit);
cfg.setProperty("settings.size-limit", sizeLimit);
cfg.setProperty("settings.horizontal-speed-limit", hSpeedLimit);
cfg.setProperty("never.spawn", neverSpawn);
cfg.setProperty("never.kill", neverKill);
if(!dir.exists())
{
if (!dir.mkdir())
{
severe("Could not create directory " + path + "; if there is a file with this name, please rename it to something else. Please make sure the server has rights to make this directory.");
return false;
}
info("Created directory " + path + "; this is where your configuration file will be kept.");
}
cfg.save();
File file = new File(config);
if (!file.exists())
{
severe("Configuration could not be saved! Please make sure the server has rights to output to " + config);
return false;
}
info("Saved configuration file: " + config);
return true;
}
/**
* Sets a flag intended to prevent this entity from ever being spawned by this plugin
*
* This is intended for situations where the entity threw an exception indicating that the
* game really, really, really was not happy about being told to spawn that entity. Flagging
* this entity is supposed to stop any player (even the admin) from spawning this entity
* regardless of permissions, aliases, etc.
*
* @param ent - The entity class. No instance of this class will be spawned using this plugin
*/
public void flag(Class<Entity> ent)
{
if (neverSpawn.contains(ent.getSimpleName()))
return;
neverSpawn.add(ent.getSimpleName());
}
/**
* Utility function; returns a list of players associated with the supplied alias.
*
* This can be restricted by permissions in two ways: permission can be denied for a specific
* alias, or permission can be denied for spawning players in general. User should be aware that
* if permission is denied on alias Derp, but there is a player named DerpIsDerp, a list
* containing a single player named DerpIsDerp will be returned.
*
* @param alias: An alias/name associated with one or more players
* @param sender: The person who asked for the alias
* @param permsPrefix: The intended purpose of this list, used as a permissions prefix
* @return PlayerAlias: A list of players combined with parameters. If no players were found, returns a size 0 array (not null)
*/
protected PlayerAlias lookupPlayers(String alias, CommandSender sender, String permsPrefix)
{
List<Player> list = new ArrayList<Player>();
List<String> names = new ArrayList<String>();
String params = "";
Player[] derp = new Player[0];//Needed for workaround below
if (alias == null)
return new PlayerAlias(list.toArray(derp), params);
names = cfg.getStringList("player-alias." + alias.toLowerCase(), names);
params = cfg.getString("alias." + alias.toLowerCase() + "-parameters", params);
if ((names.size() > 0) && allowedTo(sender, permsPrefix + "." + alias))
{
for (Iterator<String> i = names.iterator(); i.hasNext();)
{
String name = i.next();
Player target = getServer().getPlayerExact(name);
if (target != null)
list.add(target);
}
}
else if (allowedTo(sender, permsPrefix + ".player"))
{
Player target = getServer().getPlayer(alias);
if (target == null)
target = getServer().getPlayerExact(alias);
if (target != null)
list.add(target);
}
return new PlayerAlias(list.toArray(derp), params); // what a ridiculous workaround
}
/**
* Utility function; returns a list of entity classes associated with the supplied alias.
*
* This can be restricted by permissions on each entity type (NOT by alias type). If player
* has permissions for only some of the entities indicated by an alias, a partial list will
* be returned.
*
* @param alias: An alias/name associated with one or more entity types
* @param sender: The person who asked for the alias
* @param permsPrefix: The intended purpose of this list, used as a permissions prefix
* @return Alias: A list of entities combined with parameters. If no entities were found, returns a size 0 array (not null)
*/
public Alias lookup(String alias, CommandSender sender, String permsPrefix)
{
List<Class<Entity>> list = new ArrayList<Class<Entity>>();
List<String> names = new ArrayList<String>();
String params = "";
Class<Entity>[] derp = new Class[0];//Needed for ridiculous workaround below
if (alias == null)
return new Alias(list.toArray(derp), params);
if (alias.toLowerCase().startsWith("org.bukkit.entity."))//allow user to specify formal name to avoid conflict (e.g. player named Zombie and not able to use lowercase because of lack of alias, which would be generated after using the formal name once)
{
if (alias.length() > 18)
alias = alias.substring(17);
else
return new Alias(list.toArray(derp), params);//an empty list since they didn't finish specifying the class
}
names = cfg.getStringList("alias." + alias.toLowerCase(), names);
params = cfg.getString("alias." + alias.toLowerCase() + "-parameters", params);
if (names.size() > 0)
for (Iterator<String> i = names.iterator(); i.hasNext();)
{
String entName = "org.bukkit.entity." + i.next();
try
{
Class<?> c = (Class<?>) Class.forName(entName);
if (Entity.class.isAssignableFrom(c))
{
if (allowedTo(sender, permsPrefix + "." + c.getSimpleName()) && !neverSpawn.contains(c.getSimpleName()))
{
list.add((Class<Entity>) c);
}
}
}
catch (ClassNotFoundException e)
{
warning("Config file says that " + alias + " is a " + entName + ", but could not find that class. Skipping...");
}
}
else
{
try
{
Class<?> c = (Class<?>) Class.forName("org.bukkit.entity." + alias);
if (Entity.class.isAssignableFrom(c))
{
if (allowedTo(sender, permsPrefix + "." + c.getSimpleName()) && !neverSpawn.contains(c.getSimpleName()))
{
list.add((Class<Entity>) c);
cfg.setProperty("alias." + alias.toLowerCase(), Arrays.asList(c.getSimpleName()));
info("Class " + c.getName() + " has not been invoked before; adding alias to configuration");
}
}
}
catch (ClassNotFoundException e)
{
;//om nom nom
}
}
return new Alias(list.toArray(derp), params); // what a ridiculous workaround to make it return an array
}
/**
* A ridiculously complicated function for handling player commands
* @param sender: The person sending the command
* @param command: The command being called
* @param commandLabel: Dunno what the difference is between this and command.getName()
* @param args: The list of arguments given for the command
*
* @return boolean: True if successful (also indicates player used syntax correctly), false otherwise
*/
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
int[] ignore = {8, 9};
if (command.getName().equalsIgnoreCase("ent"))
{
if (allowedTo(sender, "spawn"))
{
if ((args.length > 0)&&(args.length < 4))
{
if (args[0].equalsIgnoreCase("kill") || args[0].toLowerCase().startsWith("kill/"))
{
if (!allowedTo(sender, "spawn.kill"))
{
printHelp(sender);
return false;
}
String type=args[0]; // save parameters for later in case mob is not specified
int radius = 0;
if (args.length > 2) //Should be /sm kill <type> <radius>
{
type=args[1];
try
{
radius = Integer.parseInt(args[2]);
}
catch (NumberFormatException e)
{
printHelp(sender);
return false;
}
}
else if (args.length > 1) //Should be either /sm kill <type> or /sm kill <radius>
{
try
{
radius = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
type=args[1];
}
}
String name = type, params = "";
if (type.contains("/")) // if the user specified parameters, distinguish them from the name of the entity
{
name = type.substring(0, type.indexOf("/"));
params = type.substring(type.indexOf("/"));
}
Alias alias = lookup(name, sender, "spawn.kill-ent");
String mobParam[] = (name + alias.getParams() + params).split("/"); //user-specified params go last, so they can override alias-specified params
Class<Entity>[] targetEnts = alias.getTypes();
if (targetEnts.length == 0)
{
sender.sendMessage(ChatColor.RED + "Invalid mob type.");
return false;
}
int healthValue=100, sizeValue=1;
boolean angry = false, color = false, fire = false, health = false, mount = false, size = false, target = false, owned = false, naked = false;
PlayerAlias owner=new PlayerAlias(), targets=new PlayerAlias();
DyeColor colorCode=DyeColor.WHITE;
if (mobParam.length>1)
{
for (int j=1; j<mobParam.length; j++)
{
String paramName = mobParam[j].substring(0, 1);
String param = null;
if (mobParam[j].length() > 2)
param = mobParam[j].substring(2);
if (paramName.equalsIgnoreCase("a"))
{
if(allowedTo(sender, "spawn.kill.angry"))
{
angry=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("c"))
{
if(allowedTo(sender, "spawn.kill.color"))
{
color=true;
try
{
colorCode = DyeColor.getByData(Byte.parseByte(param));
}
catch (NumberFormatException e)
{
try
{
colorCode = DyeColor.valueOf(DyeColor.class, param.toUpperCase());
} catch (IllegalArgumentException f)
{
sender.sendMessage(ChatColor.RED + "Color parameter must be a valid color or a number from 0 to 15.");
return false;
}
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("f"))
{
if(allowedTo(sender, "spawn.kill.fire"))
fire=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("h"))
{
if (allowedTo(sender, "spawn.kill.health"))
{
try
{
if (param.endsWith("%"))
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer (Percentage not supported for kill)");
return false;
}
else
{
healthValue = Integer.parseInt(param);
health=true;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer (Percentage not supported for kill)");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("m"))
{
if(allowedTo(sender, "spawn.kill.mount"))
{
mount=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("n"))
{
if(allowedTo(sender, "spawn.kill.naked"))
naked=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("o"))
{
if(allowedTo(sender, "spawn.kill.owner"))
{
owned = true;
owner = lookupPlayers(param, sender, "kill.owner"); // No need to validate; null means that it will kill ALL owned wolves.\
if ((owner.getPeople().length == 0)&&(param != null)) // If user typed something, it means they wanted a specific player and would probably be unhappy with killing ALL owners.
sender.sendMessage(ChatColor.RED + "Could not locate player by that name.");
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("s"))
{
if(allowedTo(sender, "spawn.kill.size"))
{
try
{
size = true;
sizeValue = Integer.parseInt(param); //Size limit only for spawning, not killing.
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("t"))
{
try
{
if(allowedTo(sender, "spawn.kill.target"))
{
target=true;
targets = lookupPlayers(param, sender, "kill.target");
if ((targets.getPeople().length == 0) && (param != null)) // If user actually bothered to typed something, it means they were trying for a specific player and probably didn't intend for mobs with ANY targets.
{
sender.sendMessage(ChatColor.RED + "Could not find a target by that name");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
}
int bodyCount=0;
if ((radius != 0)&&(!(sender instanceof Player)))
{
sender.sendMessage(ChatColor.RED + "...and where did you think I'd measure that radius from, Mr Console?");
return false;
}
bodyCount=Kill(sender, targetEnts, radius, angry, color, colorCode, fire, health, healthValue, mount, naked, owned, owner.getPeople(), size, sizeValue, target, targets.getPeople());
sender.sendMessage(ChatColor.BLUE + "Killed " + bodyCount + " " + mobParam[0] + "s.");
return true;
}
// Done with /kill
else if (allowedTo(sender, "spawn.spawn"))
{
if (!(sender instanceof Player))
{
printHelp(sender);
return false;
}
Player player = (Player) sender;
Location loc=player.getLocation();
Block targetB = new TargetBlock(player, 300, 0.2, ignore).getTargetBlock();
if (targetB!=null)
{
loc.setX(targetB.getLocation().getX());
loc.setY(targetB.getLocation().getY() + 1);
loc.setZ(targetB.getLocation().getZ());
}
int count=1;
String[] passengerList = args[0].split(";"); //First, get the passenger list
Ent index = null, index2 = null;
for (int i=0; i<passengerList.length; i++)
{
if (index != null)
index.setPassenger(index2);
String name = passengerList[i], params = "";
if (passengerList[i].contains("/")) // if the user specified parameters, distinguish them from the name of the entity
{
name = passengerList[i].substring(0, passengerList[i].indexOf("/"));
params = passengerList[i].substring(passengerList[i].indexOf("/"));
}
PlayerAlias playerAlias = lookupPlayers(name, sender, "spawn.spawn-player");
Alias alias = lookup(name, sender, "spawn.spawn-ent");
if (playerAlias.getPeople().length > 0)
params = playerAlias.getParams() + params;
else
params = alias.getParams() + params;
String mobParam[] = (name + params).split("/"); //Check type for params
Player[] people = playerAlias.getPeople();
Class<Entity>[] results = alias.getTypes();
if (results.length == 0 && people.length == 0)
{
sender.sendMessage(ChatColor.RED + "Invalid mob type.");
return false;
}
int healthValue=100, itemType=17, itemAmount=1, size=1, fireTicks=-1;
short itemDamage=0;
Byte itemData=null;
double velRandom=0;
Vector velValue = new Vector(0,0,0);
boolean setSize = false, health = false, healthIsPercentage = true, angry = false, bounce = false, color = false, mount = false, target = false, tame = false, naked = false, velocity = false;
PlayerAlias targets=new PlayerAlias();
PlayerAlias owner=new PlayerAlias();
DyeColor colorCode=DyeColor.WHITE;
if (mobParam.length>1)
{
for (int j=1; j<mobParam.length; j++)
{
String paramName = mobParam[j].substring(0, 1);
String param = null;
if (mobParam[j].length() > 2)
param = mobParam[j].substring(2);
if (paramName.equalsIgnoreCase("a"))
{
if(allowedTo(sender, "spawn.angry"))
{
angry=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("b"))
{
if(allowedTo(sender, "spawn.bounce"))
{
bounce=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("c"))
{
if(allowedTo(sender, "spawn.color"))
{
color=true;
try
{
colorCode = DyeColor.getByData(Byte.parseByte(param));
}
catch (NumberFormatException e)
{
try
{
colorCode = DyeColor.valueOf(DyeColor.class, param.toUpperCase());
} catch (IllegalArgumentException f)
{
sender.sendMessage(ChatColor.RED + "Color parameter must be a valid color or a number from 0 to 15.");
return false;
}
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("f"))
{
if(allowedTo(sender, "spawn.fire"))
try
{
fireTicks = Integer.parseInt(param)*20;
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Fire parameter must be an integer.");
return false;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("h"))
{
if (allowedTo(sender, "spawn.health"))
{
try
{
if (param.endsWith("%"))
{
healthIsPercentage=true;
healthValue = Integer.parseInt(param.substring(0, param.indexOf("%")));
health=true;
}
else
{
healthIsPercentage=false;
healthValue = Integer.parseInt(param);
health=true;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer or a percentage");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("i"))
{
if(allowedTo(sender, "spawn.item"))
{
String specify[] = param.split(",");
if (specify.length>3)
itemData = Byte.parseByte(specify[3]);
if (specify.length>2)
itemDamage = Short.parseShort(specify[2]);
if (specify.length>1)
itemAmount = Integer.parseInt(specify[1]);
if (specify.length>0)
itemType = Integer.parseInt(specify[0]);
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("m"))
{
if(allowedTo(sender, "spawn.mount"))
{
mount=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("n"))
{
if(allowedTo(sender, "spawn.naked"))
naked=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("o"))
{
if(allowedTo(sender, "spawn.owner"))
{
tame=true;
owner = lookupPlayers(param, sender, "spawn.owner"); // No need to validate; null means that it will be tame but unownable. Could be fun.
if ((owner.getPeople().length == 0)&&(param != null)) // If user typed something, it means they wanted a specific player and would probably be unhappy with killing ALL owners.
sender.sendMessage(ChatColor.RED + "Could not locate player by that name.");
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("s"))
{
if(allowedTo(sender, "spawn.size"))
{
try
{
setSize = true;
size = Integer.parseInt(param);
if (size > sizeLimit)
size = sizeLimit;
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("t"))
{
try
{
if(allowedTo(sender, "spawn.target"))
{
target=true;
targets = lookupPlayers(param, sender, "spawn.target");
if (targets.getPeople().length == 0)
{
sender.sendMessage(ChatColor.RED + "Could not find a target by that name");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else if (paramName.equalsIgnoreCase("v"))
{
if(allowedTo(sender, "spawn.velocity"))
{
velocity = true;
String specify[] = param.split(",");
if (specify.length==3)
{
velValue.setX(Double.parseDouble(specify[0]));
velValue.setY(Double.parseDouble(specify[1]));
velValue.setZ(Double.parseDouble(specify[2]));
}
else
try
{
velRandom = Double.parseDouble(param);
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Velocity parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
}
index2=index;
if (people.length == 0)
index = new Ent(results, mobParam[0], angry, bounce, color, colorCode, fireTicks, health, healthIsPercentage, healthValue, itemType, itemAmount, itemDamage, itemData, mount, naked, tame, owner.getPeople(), index2, setSize, size, target, targets.getPeople(), velocity, velRandom, velValue);
else
index = new Person(people, mobParam[0], angry, bounce, color, colorCode, fireTicks, health, healthIsPercentage, healthValue, itemType, itemAmount, itemDamage, itemData, mount, naked, tame, owner.getPeople(), index2, setSize, size, target, targets.getPeople(), velocity, velRandom, velValue);
}
if (args.length > 1)
{
try
{
count=Integer.parseInt(args[1]);
if (count < 1)
{
sender.sendMessage(ChatColor.RED + "Invalid number - must be at least one.");
return false;
}
}
catch (Exception e)
{
return false;
}
}
if (count > (spawnLimit/passengerList.length))
{
info("Player " + sender.getName() + " tried to spawn more than " + spawnLimit + " entities.");
count = spawnLimit/passengerList.length;
}
if (index.spawn(player, this, loc, count))
sender.sendMessage(ChatColor.BLUE + "Spawned " + count + " " + index.description());
else
sender.sendMessage(ChatColor.RED + "Some things just weren't meant to be spawned. Check server log.");
return true;
}
}
else
{
printHelp(sender);
return false;
}
}
}
else if (command.getName().equalsIgnoreCase("ent-admin"))
{
- if (allowedTo(sender, "spawn-admin"))
+ if (allowedTo(sender, "spawn.admin"))
{
if ((args.length > 0))
{
if (args[0].equalsIgnoreCase("save"))
{
sender.sendMessage(ChatColor.GREEN + "Saving configuration file...");
if (save())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "Could not save configuration file - please see server log.");
return true;
}
else if (args[0].equalsIgnoreCase("reset"))
{
sender.sendMessage(ChatColor.GREEN + "Resetting configuration file...");
if (saveDefault())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "Could not save configuration file - please see server log.");
return true;
}
else if (args[0].equalsIgnoreCase("reload"))
{
sender.sendMessage(ChatColor.GREEN + "Reloading Spawn...");
if (reload())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "An error occurred while reloading - please see server log.");
return true;
}
}
}
}
else
sender.sendMessage("Unknown console command. Type \"help\" for help"); // No reason to tell them what they CAN'T do, right?
return false;
}
/**
* Prints help in accordance with the player's permissions
*
* @param sender: The person being "helped"
*/
public void printHelp(CommandSender sender)
{
if (allowedTo(sender, "spawn.admin"))
{
sender.sendMessage(ChatColor.GREEN + "/spawn-admin reload");
sender.sendMessage(ChatColor.YELLOW + "Reloads Spawn plugin");
sender.sendMessage(ChatColor.GREEN + "/spawn-admin save");
sender.sendMessage(ChatColor.YELLOW + "Saves Spawn's configuration file");
sender.sendMessage(ChatColor.GREEN + "/spawn-admin reset");
sender.sendMessage(ChatColor.RED + "Overwrites Spawn's configuration file with default settings");
sender.sendMessage(ChatColor.YELLOW + "Alternative commands: " + ChatColor.WHITE + "/ent-admin, /spawn-entity-admin, /sp-admin, /se-admin, /s-admin");
}
if (allowedTo(sender, "spawn.spawn") && sender instanceof Player)
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/<paramname>:<param>/<paramname>:<param>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with parameters");
if (allowedTo(sender, "spawn.angry"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/a:");
sender.sendMessage(ChatColor.YELLOW + "Spawns an angry/powered version of <entity>");
}
if (allowedTo(sender, "spawn.bounce"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/b:");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> projectile that bounces on impact");
}
if (allowedTo(sender, "spawn.color"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/c:<color code 0-15>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> that has the specified color");
}
if (allowedTo(sender, "spawn.fire"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/f:<number of seconds>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> that burns for specified number of (unlagged) seconds");
sender.sendMessage(ChatColor.YELLOW + "Entities that specify a fuse also use this value");
}
if (allowedTo(sender, "spawn.health"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/h:<health>" + ChatColor.YELLOW + " OR " + ChatColor.BLUE + "/spawn <mob>/h:<health%>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with specified health (usually only works for 1-10, can also use percentage)");
}
if (allowedTo(sender, "spawn.item"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn Item/i:<type>,<amount/stack>,<damage>,<data>");
sender.sendMessage(ChatColor.YELLOW + "Spawns an item stack of specified type number, amount per stack, damage value, and data value.");
}
if (allowedTo(sender, "spawn.mount"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/m:");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with a mount (saddle)");
}
if (allowedTo(sender, "spawn.naked"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/n:");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with clothing irretrievably destroyed");
}
if (allowedTo(sender, "spawn.owner"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/o:<player name>");
sender.sendMessage(ChatColor.YELLOW + "Spawns tame <entity> with specified player as owner; if unspecified, will be unownable");
}
if (allowedTo(sender, "spawn.passenger"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entparams>;<entparams2>" + ChatColor.AQUA + "[;<entparams3>...] <number>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with parameters riding <ent2>" + ChatColor.DARK_AQUA + " riding <ent3>...");
}
if (allowedTo(sender, "spawn.size"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/s:<size>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with specified size (usually only works for slimes)");
}
if (allowedTo(sender, "spawn.target"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/t:<player name>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with specified player as target");
}
if (allowedTo(sender, "spawn.velocity"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/v:<velocity>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with specified velocity (random direction)");
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/v:<x>,<y>,<z>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with specified velocity and direction");
sender.sendMessage(ChatColor.BLUE + "/spawn <entity>/v:<x>,<y>,<z>/v:<offsetvelocity>");
sender.sendMessage(ChatColor.YELLOW + "Spawns <entity> with specified direction plus an offset in a random direction");
}
sender.sendMessage(ChatColor.YELLOW + "Alternative commands: " + ChatColor.WHITE + "/ent, /spawn-entity, /sp, /se, /s");
}
if (allowedTo(sender, "spawn.kill"))
{
sender.sendMessage(ChatColor.BLUE + "/spawn kill");
sender.sendMessage(ChatColor.YELLOW + "Kills all entities and gives a body count");
sender.sendMessage(ChatColor.BLUE + "/spawn kill<params>");
sender.sendMessage(ChatColor.YELLOW + "Kills all entities with <optional parameters> and gives a body count");
if (sender instanceof Player)
{
sender.sendMessage(ChatColor.BLUE + "/spawn kill <enttype><params> <radius>");
sender.sendMessage(ChatColor.YELLOW + "Kills all entities of <type> with <optional parameters> within <optional radius> of you and gives a body count");
}
else
{
sender.sendMessage(ChatColor.BLUE + "/spawn kill <enttype><params>");
sender.sendMessage(ChatColor.YELLOW + "Kills all entities of <type> with <optional parameters> and gives a body count");
}
}
}
/**
* Probably the only leftover from SpawnMob. Should replace with a PluginListener...
*
* Tests to see if permissions is working; if so, sets our Permissions handle so we can access it.
* Otherwise, sets permissions to false.
*/
private void setupPermissions()
{
Plugin test = this.getServer().getPluginManager().getPlugin("Permissions");
if (Spawn.Permissions == null) {
if (test != null) {
Spawn.Permissions = ((Permissions)test).getHandler();
info("Permission system found, plugin enabled");
} else {
info("Permission system not detected! Please go into the SpawnMob.properties and set use-permissions to false.");
info("Please go into the SpawnMob.properties and set use-permissions to false.");
permissions = false;
}
}
}
/**
* Checks to see if sender has permission OR is an op. If not using permissions, only op is tested.
* @param sender: The person whose permission is being checked
* @param permission The permission being checked (e.g. "exampleplugin.examplepermnode")
* @returns boolean: True if player has the permission node OR if player is an op
*/
boolean allowedTo(CommandSender sender, String permission)
{
if (sender.isOp())
return true;
else if (permissions && sender instanceof Player)
return Permissions.has((Player)sender, permission);
return false;
}
/**
* Test to see whether type (usually a CraftBukkit Entity of some kind) uses any of the (Bukkit)
* interfaces in types. (e.g. CraftCow implements Cow). Useful for determining if an entity
* is in our list of creature types we want to work on.
*
* @param types: A list of types that is being used to filter Entities
* @param type: The type being filtered
* @return boolean: True if type uses any of the types as an Interface
*/
private boolean hasClass(Class<Entity>[] types, Class<? extends Entity> type)
{
for (int i=0; i<types.length; i++)
for (int j=0; j<type.getInterfaces().length; j++)
if (type.getInterfaces()[j]==types[i])
return true;
return false;
}
/**
* Tests to see whether subject exists as a member of array.
* @param subject: An object being filtered
* @param array: A list of objects being used as a filter
* @return boolean: True if array has subject in it
*/
private boolean existsIn(Object subject, Object[] array)
{
for (int i=0; i<array.length; i++)
if (array[i]==subject)
return true;
return false;
}
/**
* Determines if an entity meets the criteria for slaughter. If so, removes it.
* @param types: The types of entity referred to by the alias
* @param angry: If true, only kills angry entities
* @param color: If true, only kills entities of a specific colorCode
* @param colorCode: Used to decide what color of entity to kill (e.g. only kill blue sheep).
* @param fire: If true, only kills burning entities
* @param health: If true, only kills entities of a specific health value
* @param healthValue: Used to decide exactly how healthy an entity needs to be to die
* @param mount: If true, will only kill mounted entities (e.g. saddled pigs)
* @param owned: If true, will only kill owned entities (e.g. owned wolves) (default is to IGNORE owned entities, use carefully!)
* @param owner: If set and owned is true, only kills entities owned by that player. If set to null and owned is true, kills ALL owned entities
* @param naked: If true, only kills naked entities (e.g. sheared sheep)
* @param size: If true, only kills entities of a specific size
* @param sizeValue: Used to decide exactly how big an entity needs to be to die
* @param target: If true, only kills entities that currently have a target
* @param targets: If set and target is true, only killed entities with these targets. If null and target is true, kills entities with ANY target
*
* @return boolean: true is ent was killed, false if it lived
*/
private boolean KillSingle(Entity ent, Class<Entity>[] types, boolean angry, boolean color, DyeColor colorCode, boolean fire, boolean health, int healthValue, boolean mount, boolean naked, boolean owned, AnimalTamer[] owner, boolean size, int sizeValue, boolean target, Player[] targets)
{
Class<? extends Entity> type = ent.getClass();
try
{
if (hasClass(types, type))
{
for (int i=0; i<type.getInterfaces().length; i++)
if (neverKill.contains(type.getInterfaces()[i].getSimpleName()))
return false; // Never, ever, kill somethingn on this list
Method ownerMethod;
//CULLING STAGE - each test returns false if it fails to meet it.
//ANGRY (default is to kill either way)
if (angry)
{
Method angryMethod = null;
try
{
angryMethod = type.getMethod("isAngry");
if (!(Boolean)angryMethod.invoke(ent))
return false;
} catch (NoSuchMethodException e)
{
try
{
angryMethod = type.getMethod("isPowered");
if (!(Boolean)angryMethod.invoke(ent))
return false;
} catch (NoSuchMethodException f){return false;};//yeah, we have to rely on Exceptions to find out if it has a method or not, how sad is that?
}
}
//COLOR (default is to kill either way)
if (color)
{
Method colorMethod;
try
{
colorMethod = type.getMethod("getColor");
if (colorCode!=colorMethod.invoke(ent))
return false;
} catch (NoSuchMethodException e){return false;}
}
//FIRE (default is to kill either way)
if (fire)
if (ent.getFireTicks() < 1)
return false;
//HEALTH (default is to kill either way)
if (health)
{
try
{
Method healthMethod = type.getMethod("getHealth");
if ((Integer)healthMethod.invoke(ent)!=healthValue)
return false;
if (ent instanceof ExperienceOrb)
if (((ExperienceOrb)ent).getExperience()!=healthValue)
return false;
} catch (NoSuchMethodException e){return false;}
}
//MOUNT (default is to leave mounted ents alone)
Method mountMethod;
try
{
mountMethod = type.getMethod("hasSaddle");
if (mount != (Boolean)mountMethod.invoke(ent))
return false;
} catch (NoSuchMethodException e){if (mount) return false;}
//NAKED (default is to leave naked ents alone)
Method shearMethod;
try
{
shearMethod = type.getMethod("isSheared");
if (naked != (Boolean)shearMethod.invoke(ent))
return false;
} catch (NoSuchMethodException e){if (naked) return false;}
//OWNER (default is to leave owned ents alone)
try
{
ownerMethod = type.getMethod("getOwner");
AnimalTamer entOwner = (AnimalTamer) ownerMethod.invoke(ent); // If Bukkit ever adds a getOwner that does not return this, it will break.
if (owned)
{
if (entOwner == null) //Cull all the unowned ents
return false;
if (owner.length > 0) //If owner is unspecified, then don't cull ANY owned ents
if (!existsIn(entOwner, owner)) // Otherwise, cull wolves owned by someone not in the list
return false;
}
else // Default is to NOT kill owned ents. (Tamed ents with null owner will still be killed)
if (entOwner != null)
return false;
} catch(NoSuchMethodException e){if (owned) return false;}
//SIZE (default is to kill either way)
if (size)
{
Method sizeMethod = null;
try
{
sizeMethod = type.getMethod("getSize");
if (sizeValue != (Integer)sizeMethod.invoke(ent, sizeValue))
return false;
} catch (NoSuchMethodException e){return false;};
}
//TARGET (default is to kill either way)
Method targetMethod;
try
{
if (target)
{
targetMethod = type.getMethod("getTarget");
LivingEntity targetLiving = (LivingEntity)targetMethod.invoke(ent);
if (targetLiving == null) // Cull all living ents without a target
return false;
if (targets.length > 0) // If target is unspecified, don't cull ANY mobs with targets
if (!existsIn(targetLiving, targets))
return false;
}
} catch (NoSuchMethodException e){if (target) return false;}
ent.remove();
return true;
}
} catch(InvocationTargetException e)
{
warning("Target " + type.getSimpleName() + " has a method for doing something, but threw an exception when it was invoked:");
e.printStackTrace();
} catch(IllegalAccessException e)
{
warning("Target " + type.getSimpleName() + " has a method for doing something, but threw an exception when it was invoked:");
e.printStackTrace();
}
return false;
}
/**
* Searches for and kills all entities that meet the specified criteria and returns a body count
*
* @param sender: The person who sent out the hit. Used for radius parameter.
* @param types: The types of entity referred to by the alias
* @param radius: If positive, only kills entities within radius of sender. Will throw casting exception if positive and sender is the console.
* @param angry: If true, only kills angry entities
* @param color: If true, only kills entities of a specific colorCode
* @param colorCode: Used to decide what color of entity to kill (e.g. only kill blue sheep).
* @param fire: If true, only kills burning entities
* @param health: If true, only kills entities of a specific health value
* @param healthValue: Used to decide exactly how healthy an entity needs to be to die
* @param mount: If true, will only kill mounted entities (e.g. saddled pigs)
* @param owned: If true, will only kill owned entities (e.g. owned wolves) (default is to IGNORE owned entities, use carefully!)
* @param owner: If set and owned is true, only kills entities owned by that player. If set to null and owned is true, kills ALL owned entities
* @param naked: If true, only kills naked entities (e.g. sheared sheep)
* @param size: If true, only kills entities of a specific size
* @param sizeValue: Used to decide exactly how big an entity needs to be to die
* @param target: If true, only kills entities that currently have a target
* @param targets: If set and target is true, only killed entities with these targets. If null and target is true, kills entities with ANY target
*
* @return int: how many entities were slain
*/
public int Kill(CommandSender sender, Class<Entity>[] types, int radius, boolean angry, boolean color, DyeColor colorCode, boolean fire, boolean health, int healthValue, boolean mount, boolean naked, boolean owned, Player[] owner, boolean size, int sizeValue, boolean target, Player[] targets)
{
int bodycount=0;
List<Entity> ents;
if (radius > 0)
{
ents = ((Player)sender).getNearbyEntities(radius, radius, radius);
for(Iterator<Entity> iterator = ents.iterator(); iterator.hasNext();)
{
Entity ent = iterator.next();
if (ent.getLocation().distance(((Player)sender).getLocation()) <= radius)
if (KillSingle(ent, types, angry, color, colorCode, fire, health, healthValue, mount, naked, owned, owner, size, sizeValue, target, targets))
bodycount++;
}
}
else
{
for (Iterator<World> worlditerator = getServer().getWorlds().iterator(); worlditerator.hasNext();)
{
ents = worlditerator.next().getEntities();
for(Iterator<Entity> iterator = ents.iterator(); iterator.hasNext();)
{
Entity ent = iterator.next();
if (KillSingle(ent, types, angry, color, colorCode, fire, health, healthValue, mount, naked, owned, owner, size, sizeValue, target, targets))
bodycount++;
}
}
}
return bodycount;
}
/**
* Logs an informative message to the console, prefaced with this plugin's header
* @param message: String
*/
protected static void info(String message)
{
log.info(header + message);
}
/**
* Logs a severe error message to the console, prefaced with this plugin's header
* Used to log severe problems that have prevented normal execution of the plugin
* @param message: String
*/
protected static void severe(String message)
{
log.severe(header + message);
}
/**
* Logs a warning message to the console, prefaced with this plugin's header
* Used to log problems that could interfere with the plugin's ability to meet admin expectations
* @param message: String
*/
protected static void warning(String message)
{
log.warning(message);
}
/**
* Logs a message to the console, prefaced with this plugin's header
* @param level: Logging level under which to send the message
* @param message: String
*/
protected static void log(java.util.logging.Level level, String message)
{
log.log(level, header + message);
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
int[] ignore = {8, 9};
if (command.getName().equalsIgnoreCase("ent"))
{
if (allowedTo(sender, "spawn"))
{
if ((args.length > 0)&&(args.length < 4))
{
if (args[0].equalsIgnoreCase("kill") || args[0].toLowerCase().startsWith("kill/"))
{
if (!allowedTo(sender, "spawn.kill"))
{
printHelp(sender);
return false;
}
String type=args[0]; // save parameters for later in case mob is not specified
int radius = 0;
if (args.length > 2) //Should be /sm kill <type> <radius>
{
type=args[1];
try
{
radius = Integer.parseInt(args[2]);
}
catch (NumberFormatException e)
{
printHelp(sender);
return false;
}
}
else if (args.length > 1) //Should be either /sm kill <type> or /sm kill <radius>
{
try
{
radius = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
type=args[1];
}
}
String name = type, params = "";
if (type.contains("/")) // if the user specified parameters, distinguish them from the name of the entity
{
name = type.substring(0, type.indexOf("/"));
params = type.substring(type.indexOf("/"));
}
Alias alias = lookup(name, sender, "spawn.kill-ent");
String mobParam[] = (name + alias.getParams() + params).split("/"); //user-specified params go last, so they can override alias-specified params
Class<Entity>[] targetEnts = alias.getTypes();
if (targetEnts.length == 0)
{
sender.sendMessage(ChatColor.RED + "Invalid mob type.");
return false;
}
int healthValue=100, sizeValue=1;
boolean angry = false, color = false, fire = false, health = false, mount = false, size = false, target = false, owned = false, naked = false;
PlayerAlias owner=new PlayerAlias(), targets=new PlayerAlias();
DyeColor colorCode=DyeColor.WHITE;
if (mobParam.length>1)
{
for (int j=1; j<mobParam.length; j++)
{
String paramName = mobParam[j].substring(0, 1);
String param = null;
if (mobParam[j].length() > 2)
param = mobParam[j].substring(2);
if (paramName.equalsIgnoreCase("a"))
{
if(allowedTo(sender, "spawn.kill.angry"))
{
angry=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("c"))
{
if(allowedTo(sender, "spawn.kill.color"))
{
color=true;
try
{
colorCode = DyeColor.getByData(Byte.parseByte(param));
}
catch (NumberFormatException e)
{
try
{
colorCode = DyeColor.valueOf(DyeColor.class, param.toUpperCase());
} catch (IllegalArgumentException f)
{
sender.sendMessage(ChatColor.RED + "Color parameter must be a valid color or a number from 0 to 15.");
return false;
}
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("f"))
{
if(allowedTo(sender, "spawn.kill.fire"))
fire=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("h"))
{
if (allowedTo(sender, "spawn.kill.health"))
{
try
{
if (param.endsWith("%"))
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer (Percentage not supported for kill)");
return false;
}
else
{
healthValue = Integer.parseInt(param);
health=true;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer (Percentage not supported for kill)");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("m"))
{
if(allowedTo(sender, "spawn.kill.mount"))
{
mount=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("n"))
{
if(allowedTo(sender, "spawn.kill.naked"))
naked=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("o"))
{
if(allowedTo(sender, "spawn.kill.owner"))
{
owned = true;
owner = lookupPlayers(param, sender, "kill.owner"); // No need to validate; null means that it will kill ALL owned wolves.\
if ((owner.getPeople().length == 0)&&(param != null)) // If user typed something, it means they wanted a specific player and would probably be unhappy with killing ALL owners.
sender.sendMessage(ChatColor.RED + "Could not locate player by that name.");
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("s"))
{
if(allowedTo(sender, "spawn.kill.size"))
{
try
{
size = true;
sizeValue = Integer.parseInt(param); //Size limit only for spawning, not killing.
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("t"))
{
try
{
if(allowedTo(sender, "spawn.kill.target"))
{
target=true;
targets = lookupPlayers(param, sender, "kill.target");
if ((targets.getPeople().length == 0) && (param != null)) // If user actually bothered to typed something, it means they were trying for a specific player and probably didn't intend for mobs with ANY targets.
{
sender.sendMessage(ChatColor.RED + "Could not find a target by that name");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
}
int bodyCount=0;
if ((radius != 0)&&(!(sender instanceof Player)))
{
sender.sendMessage(ChatColor.RED + "...and where did you think I'd measure that radius from, Mr Console?");
return false;
}
bodyCount=Kill(sender, targetEnts, radius, angry, color, colorCode, fire, health, healthValue, mount, naked, owned, owner.getPeople(), size, sizeValue, target, targets.getPeople());
sender.sendMessage(ChatColor.BLUE + "Killed " + bodyCount + " " + mobParam[0] + "s.");
return true;
}
// Done with /kill
else if (allowedTo(sender, "spawn.spawn"))
{
if (!(sender instanceof Player))
{
printHelp(sender);
return false;
}
Player player = (Player) sender;
Location loc=player.getLocation();
Block targetB = new TargetBlock(player, 300, 0.2, ignore).getTargetBlock();
if (targetB!=null)
{
loc.setX(targetB.getLocation().getX());
loc.setY(targetB.getLocation().getY() + 1);
loc.setZ(targetB.getLocation().getZ());
}
int count=1;
String[] passengerList = args[0].split(";"); //First, get the passenger list
Ent index = null, index2 = null;
for (int i=0; i<passengerList.length; i++)
{
if (index != null)
index.setPassenger(index2);
String name = passengerList[i], params = "";
if (passengerList[i].contains("/")) // if the user specified parameters, distinguish them from the name of the entity
{
name = passengerList[i].substring(0, passengerList[i].indexOf("/"));
params = passengerList[i].substring(passengerList[i].indexOf("/"));
}
PlayerAlias playerAlias = lookupPlayers(name, sender, "spawn.spawn-player");
Alias alias = lookup(name, sender, "spawn.spawn-ent");
if (playerAlias.getPeople().length > 0)
params = playerAlias.getParams() + params;
else
params = alias.getParams() + params;
String mobParam[] = (name + params).split("/"); //Check type for params
Player[] people = playerAlias.getPeople();
Class<Entity>[] results = alias.getTypes();
if (results.length == 0 && people.length == 0)
{
sender.sendMessage(ChatColor.RED + "Invalid mob type.");
return false;
}
int healthValue=100, itemType=17, itemAmount=1, size=1, fireTicks=-1;
short itemDamage=0;
Byte itemData=null;
double velRandom=0;
Vector velValue = new Vector(0,0,0);
boolean setSize = false, health = false, healthIsPercentage = true, angry = false, bounce = false, color = false, mount = false, target = false, tame = false, naked = false, velocity = false;
PlayerAlias targets=new PlayerAlias();
PlayerAlias owner=new PlayerAlias();
DyeColor colorCode=DyeColor.WHITE;
if (mobParam.length>1)
{
for (int j=1; j<mobParam.length; j++)
{
String paramName = mobParam[j].substring(0, 1);
String param = null;
if (mobParam[j].length() > 2)
param = mobParam[j].substring(2);
if (paramName.equalsIgnoreCase("a"))
{
if(allowedTo(sender, "spawn.angry"))
{
angry=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("b"))
{
if(allowedTo(sender, "spawn.bounce"))
{
bounce=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("c"))
{
if(allowedTo(sender, "spawn.color"))
{
color=true;
try
{
colorCode = DyeColor.getByData(Byte.parseByte(param));
}
catch (NumberFormatException e)
{
try
{
colorCode = DyeColor.valueOf(DyeColor.class, param.toUpperCase());
} catch (IllegalArgumentException f)
{
sender.sendMessage(ChatColor.RED + "Color parameter must be a valid color or a number from 0 to 15.");
return false;
}
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("f"))
{
if(allowedTo(sender, "spawn.fire"))
try
{
fireTicks = Integer.parseInt(param)*20;
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Fire parameter must be an integer.");
return false;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("h"))
{
if (allowedTo(sender, "spawn.health"))
{
try
{
if (param.endsWith("%"))
{
healthIsPercentage=true;
healthValue = Integer.parseInt(param.substring(0, param.indexOf("%")));
health=true;
}
else
{
healthIsPercentage=false;
healthValue = Integer.parseInt(param);
health=true;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer or a percentage");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("i"))
{
if(allowedTo(sender, "spawn.item"))
{
String specify[] = param.split(",");
if (specify.length>3)
itemData = Byte.parseByte(specify[3]);
if (specify.length>2)
itemDamage = Short.parseShort(specify[2]);
if (specify.length>1)
itemAmount = Integer.parseInt(specify[1]);
if (specify.length>0)
itemType = Integer.parseInt(specify[0]);
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("m"))
{
if(allowedTo(sender, "spawn.mount"))
{
mount=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("n"))
{
if(allowedTo(sender, "spawn.naked"))
naked=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("o"))
{
if(allowedTo(sender, "spawn.owner"))
{
tame=true;
owner = lookupPlayers(param, sender, "spawn.owner"); // No need to validate; null means that it will be tame but unownable. Could be fun.
if ((owner.getPeople().length == 0)&&(param != null)) // If user typed something, it means they wanted a specific player and would probably be unhappy with killing ALL owners.
sender.sendMessage(ChatColor.RED + "Could not locate player by that name.");
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("s"))
{
if(allowedTo(sender, "spawn.size"))
{
try
{
setSize = true;
size = Integer.parseInt(param);
if (size > sizeLimit)
size = sizeLimit;
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("t"))
{
try
{
if(allowedTo(sender, "spawn.target"))
{
target=true;
targets = lookupPlayers(param, sender, "spawn.target");
if (targets.getPeople().length == 0)
{
sender.sendMessage(ChatColor.RED + "Could not find a target by that name");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else if (paramName.equalsIgnoreCase("v"))
{
if(allowedTo(sender, "spawn.velocity"))
{
velocity = true;
String specify[] = param.split(",");
if (specify.length==3)
{
velValue.setX(Double.parseDouble(specify[0]));
velValue.setY(Double.parseDouble(specify[1]));
velValue.setZ(Double.parseDouble(specify[2]));
}
else
try
{
velRandom = Double.parseDouble(param);
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Velocity parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
}
index2=index;
if (people.length == 0)
index = new Ent(results, mobParam[0], angry, bounce, color, colorCode, fireTicks, health, healthIsPercentage, healthValue, itemType, itemAmount, itemDamage, itemData, mount, naked, tame, owner.getPeople(), index2, setSize, size, target, targets.getPeople(), velocity, velRandom, velValue);
else
index = new Person(people, mobParam[0], angry, bounce, color, colorCode, fireTicks, health, healthIsPercentage, healthValue, itemType, itemAmount, itemDamage, itemData, mount, naked, tame, owner.getPeople(), index2, setSize, size, target, targets.getPeople(), velocity, velRandom, velValue);
}
if (args.length > 1)
{
try
{
count=Integer.parseInt(args[1]);
if (count < 1)
{
sender.sendMessage(ChatColor.RED + "Invalid number - must be at least one.");
return false;
}
}
catch (Exception e)
{
return false;
}
}
if (count > (spawnLimit/passengerList.length))
{
info("Player " + sender.getName() + " tried to spawn more than " + spawnLimit + " entities.");
count = spawnLimit/passengerList.length;
}
if (index.spawn(player, this, loc, count))
sender.sendMessage(ChatColor.BLUE + "Spawned " + count + " " + index.description());
else
sender.sendMessage(ChatColor.RED + "Some things just weren't meant to be spawned. Check server log.");
return true;
}
}
else
{
printHelp(sender);
return false;
}
}
}
else if (command.getName().equalsIgnoreCase("ent-admin"))
{
if (allowedTo(sender, "spawn-admin"))
{
if ((args.length > 0))
{
if (args[0].equalsIgnoreCase("save"))
{
sender.sendMessage(ChatColor.GREEN + "Saving configuration file...");
if (save())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "Could not save configuration file - please see server log.");
return true;
}
else if (args[0].equalsIgnoreCase("reset"))
{
sender.sendMessage(ChatColor.GREEN + "Resetting configuration file...");
if (saveDefault())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "Could not save configuration file - please see server log.");
return true;
}
else if (args[0].equalsIgnoreCase("reload"))
{
sender.sendMessage(ChatColor.GREEN + "Reloading Spawn...");
if (reload())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "An error occurred while reloading - please see server log.");
return true;
}
}
}
}
else
sender.sendMessage("Unknown console command. Type \"help\" for help"); // No reason to tell them what they CAN'T do, right?
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
int[] ignore = {8, 9};
if (command.getName().equalsIgnoreCase("ent"))
{
if (allowedTo(sender, "spawn"))
{
if ((args.length > 0)&&(args.length < 4))
{
if (args[0].equalsIgnoreCase("kill") || args[0].toLowerCase().startsWith("kill/"))
{
if (!allowedTo(sender, "spawn.kill"))
{
printHelp(sender);
return false;
}
String type=args[0]; // save parameters for later in case mob is not specified
int radius = 0;
if (args.length > 2) //Should be /sm kill <type> <radius>
{
type=args[1];
try
{
radius = Integer.parseInt(args[2]);
}
catch (NumberFormatException e)
{
printHelp(sender);
return false;
}
}
else if (args.length > 1) //Should be either /sm kill <type> or /sm kill <radius>
{
try
{
radius = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
type=args[1];
}
}
String name = type, params = "";
if (type.contains("/")) // if the user specified parameters, distinguish them from the name of the entity
{
name = type.substring(0, type.indexOf("/"));
params = type.substring(type.indexOf("/"));
}
Alias alias = lookup(name, sender, "spawn.kill-ent");
String mobParam[] = (name + alias.getParams() + params).split("/"); //user-specified params go last, so they can override alias-specified params
Class<Entity>[] targetEnts = alias.getTypes();
if (targetEnts.length == 0)
{
sender.sendMessage(ChatColor.RED + "Invalid mob type.");
return false;
}
int healthValue=100, sizeValue=1;
boolean angry = false, color = false, fire = false, health = false, mount = false, size = false, target = false, owned = false, naked = false;
PlayerAlias owner=new PlayerAlias(), targets=new PlayerAlias();
DyeColor colorCode=DyeColor.WHITE;
if (mobParam.length>1)
{
for (int j=1; j<mobParam.length; j++)
{
String paramName = mobParam[j].substring(0, 1);
String param = null;
if (mobParam[j].length() > 2)
param = mobParam[j].substring(2);
if (paramName.equalsIgnoreCase("a"))
{
if(allowedTo(sender, "spawn.kill.angry"))
{
angry=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("c"))
{
if(allowedTo(sender, "spawn.kill.color"))
{
color=true;
try
{
colorCode = DyeColor.getByData(Byte.parseByte(param));
}
catch (NumberFormatException e)
{
try
{
colorCode = DyeColor.valueOf(DyeColor.class, param.toUpperCase());
} catch (IllegalArgumentException f)
{
sender.sendMessage(ChatColor.RED + "Color parameter must be a valid color or a number from 0 to 15.");
return false;
}
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("f"))
{
if(allowedTo(sender, "spawn.kill.fire"))
fire=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("h"))
{
if (allowedTo(sender, "spawn.kill.health"))
{
try
{
if (param.endsWith("%"))
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer (Percentage not supported for kill)");
return false;
}
else
{
healthValue = Integer.parseInt(param);
health=true;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer (Percentage not supported for kill)");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("m"))
{
if(allowedTo(sender, "spawn.kill.mount"))
{
mount=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("n"))
{
if(allowedTo(sender, "spawn.kill.naked"))
naked=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("o"))
{
if(allowedTo(sender, "spawn.kill.owner"))
{
owned = true;
owner = lookupPlayers(param, sender, "kill.owner"); // No need to validate; null means that it will kill ALL owned wolves.\
if ((owner.getPeople().length == 0)&&(param != null)) // If user typed something, it means they wanted a specific player and would probably be unhappy with killing ALL owners.
sender.sendMessage(ChatColor.RED + "Could not locate player by that name.");
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("s"))
{
if(allowedTo(sender, "spawn.kill.size"))
{
try
{
size = true;
sizeValue = Integer.parseInt(param); //Size limit only for spawning, not killing.
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("t"))
{
try
{
if(allowedTo(sender, "spawn.kill.target"))
{
target=true;
targets = lookupPlayers(param, sender, "kill.target");
if ((targets.getPeople().length == 0) && (param != null)) // If user actually bothered to typed something, it means they were trying for a specific player and probably didn't intend for mobs with ANY targets.
{
sender.sendMessage(ChatColor.RED + "Could not find a target by that name");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
}
int bodyCount=0;
if ((radius != 0)&&(!(sender instanceof Player)))
{
sender.sendMessage(ChatColor.RED + "...and where did you think I'd measure that radius from, Mr Console?");
return false;
}
bodyCount=Kill(sender, targetEnts, radius, angry, color, colorCode, fire, health, healthValue, mount, naked, owned, owner.getPeople(), size, sizeValue, target, targets.getPeople());
sender.sendMessage(ChatColor.BLUE + "Killed " + bodyCount + " " + mobParam[0] + "s.");
return true;
}
// Done with /kill
else if (allowedTo(sender, "spawn.spawn"))
{
if (!(sender instanceof Player))
{
printHelp(sender);
return false;
}
Player player = (Player) sender;
Location loc=player.getLocation();
Block targetB = new TargetBlock(player, 300, 0.2, ignore).getTargetBlock();
if (targetB!=null)
{
loc.setX(targetB.getLocation().getX());
loc.setY(targetB.getLocation().getY() + 1);
loc.setZ(targetB.getLocation().getZ());
}
int count=1;
String[] passengerList = args[0].split(";"); //First, get the passenger list
Ent index = null, index2 = null;
for (int i=0; i<passengerList.length; i++)
{
if (index != null)
index.setPassenger(index2);
String name = passengerList[i], params = "";
if (passengerList[i].contains("/")) // if the user specified parameters, distinguish them from the name of the entity
{
name = passengerList[i].substring(0, passengerList[i].indexOf("/"));
params = passengerList[i].substring(passengerList[i].indexOf("/"));
}
PlayerAlias playerAlias = lookupPlayers(name, sender, "spawn.spawn-player");
Alias alias = lookup(name, sender, "spawn.spawn-ent");
if (playerAlias.getPeople().length > 0)
params = playerAlias.getParams() + params;
else
params = alias.getParams() + params;
String mobParam[] = (name + params).split("/"); //Check type for params
Player[] people = playerAlias.getPeople();
Class<Entity>[] results = alias.getTypes();
if (results.length == 0 && people.length == 0)
{
sender.sendMessage(ChatColor.RED + "Invalid mob type.");
return false;
}
int healthValue=100, itemType=17, itemAmount=1, size=1, fireTicks=-1;
short itemDamage=0;
Byte itemData=null;
double velRandom=0;
Vector velValue = new Vector(0,0,0);
boolean setSize = false, health = false, healthIsPercentage = true, angry = false, bounce = false, color = false, mount = false, target = false, tame = false, naked = false, velocity = false;
PlayerAlias targets=new PlayerAlias();
PlayerAlias owner=new PlayerAlias();
DyeColor colorCode=DyeColor.WHITE;
if (mobParam.length>1)
{
for (int j=1; j<mobParam.length; j++)
{
String paramName = mobParam[j].substring(0, 1);
String param = null;
if (mobParam[j].length() > 2)
param = mobParam[j].substring(2);
if (paramName.equalsIgnoreCase("a"))
{
if(allowedTo(sender, "spawn.angry"))
{
angry=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("b"))
{
if(allowedTo(sender, "spawn.bounce"))
{
bounce=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("c"))
{
if(allowedTo(sender, "spawn.color"))
{
color=true;
try
{
colorCode = DyeColor.getByData(Byte.parseByte(param));
}
catch (NumberFormatException e)
{
try
{
colorCode = DyeColor.valueOf(DyeColor.class, param.toUpperCase());
} catch (IllegalArgumentException f)
{
sender.sendMessage(ChatColor.RED + "Color parameter must be a valid color or a number from 0 to 15.");
return false;
}
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("f"))
{
if(allowedTo(sender, "spawn.fire"))
try
{
fireTicks = Integer.parseInt(param)*20;
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Fire parameter must be an integer.");
return false;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("h"))
{
if (allowedTo(sender, "spawn.health"))
{
try
{
if (param.endsWith("%"))
{
healthIsPercentage=true;
healthValue = Integer.parseInt(param.substring(0, param.indexOf("%")));
health=true;
}
else
{
healthIsPercentage=false;
healthValue = Integer.parseInt(param);
health=true;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Health parameter must be an integer or a percentage");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("i"))
{
if(allowedTo(sender, "spawn.item"))
{
String specify[] = param.split(",");
if (specify.length>3)
itemData = Byte.parseByte(specify[3]);
if (specify.length>2)
itemDamage = Short.parseShort(specify[2]);
if (specify.length>1)
itemAmount = Integer.parseInt(specify[1]);
if (specify.length>0)
itemType = Integer.parseInt(specify[0]);
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("m"))
{
if(allowedTo(sender, "spawn.mount"))
{
mount=true;
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("n"))
{
if(allowedTo(sender, "spawn.naked"))
naked=true;
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("o"))
{
if(allowedTo(sender, "spawn.owner"))
{
tame=true;
owner = lookupPlayers(param, sender, "spawn.owner"); // No need to validate; null means that it will be tame but unownable. Could be fun.
if ((owner.getPeople().length == 0)&&(param != null)) // If user typed something, it means they wanted a specific player and would probably be unhappy with killing ALL owners.
sender.sendMessage(ChatColor.RED + "Could not locate player by that name.");
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("s"))
{
if(allowedTo(sender, "spawn.size"))
{
try
{
setSize = true;
size = Integer.parseInt(param);
if (size > sizeLimit)
size = sizeLimit;
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else if (paramName.equalsIgnoreCase("t"))
{
try
{
if(allowedTo(sender, "spawn.target"))
{
target=true;
targets = lookupPlayers(param, sender, "spawn.target");
if (targets.getPeople().length == 0)
{
sender.sendMessage(ChatColor.RED + "Could not find a target by that name");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Size parameter must be an integer.");
return false;
}
}
else if (paramName.equalsIgnoreCase("v"))
{
if(allowedTo(sender, "spawn.velocity"))
{
velocity = true;
String specify[] = param.split(",");
if (specify.length==3)
{
velValue.setX(Double.parseDouble(specify[0]));
velValue.setY(Double.parseDouble(specify[1]));
velValue.setZ(Double.parseDouble(specify[2]));
}
else
try
{
velRandom = Double.parseDouble(param);
} catch (NumberFormatException e)
{
sender.sendMessage(ChatColor.RED + "Velocity parameter must be an integer.");
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
else
{
sender.sendMessage(ChatColor.RED + "Invalid parameter " + paramName);
return false;
}
}
}
index2=index;
if (people.length == 0)
index = new Ent(results, mobParam[0], angry, bounce, color, colorCode, fireTicks, health, healthIsPercentage, healthValue, itemType, itemAmount, itemDamage, itemData, mount, naked, tame, owner.getPeople(), index2, setSize, size, target, targets.getPeople(), velocity, velRandom, velValue);
else
index = new Person(people, mobParam[0], angry, bounce, color, colorCode, fireTicks, health, healthIsPercentage, healthValue, itemType, itemAmount, itemDamage, itemData, mount, naked, tame, owner.getPeople(), index2, setSize, size, target, targets.getPeople(), velocity, velRandom, velValue);
}
if (args.length > 1)
{
try
{
count=Integer.parseInt(args[1]);
if (count < 1)
{
sender.sendMessage(ChatColor.RED + "Invalid number - must be at least one.");
return false;
}
}
catch (Exception e)
{
return false;
}
}
if (count > (spawnLimit/passengerList.length))
{
info("Player " + sender.getName() + " tried to spawn more than " + spawnLimit + " entities.");
count = spawnLimit/passengerList.length;
}
if (index.spawn(player, this, loc, count))
sender.sendMessage(ChatColor.BLUE + "Spawned " + count + " " + index.description());
else
sender.sendMessage(ChatColor.RED + "Some things just weren't meant to be spawned. Check server log.");
return true;
}
}
else
{
printHelp(sender);
return false;
}
}
}
else if (command.getName().equalsIgnoreCase("ent-admin"))
{
if (allowedTo(sender, "spawn.admin"))
{
if ((args.length > 0))
{
if (args[0].equalsIgnoreCase("save"))
{
sender.sendMessage(ChatColor.GREEN + "Saving configuration file...");
if (save())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "Could not save configuration file - please see server log.");
return true;
}
else if (args[0].equalsIgnoreCase("reset"))
{
sender.sendMessage(ChatColor.GREEN + "Resetting configuration file...");
if (saveDefault())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "Could not save configuration file - please see server log.");
return true;
}
else if (args[0].equalsIgnoreCase("reload"))
{
sender.sendMessage(ChatColor.GREEN + "Reloading Spawn...");
if (reload())
sender.sendMessage(ChatColor.GREEN + "Done.");
else
sender.sendMessage(ChatColor.RED + "An error occurred while reloading - please see server log.");
return true;
}
}
}
}
else
sender.sendMessage("Unknown console command. Type \"help\" for help"); // No reason to tell them what they CAN'T do, right?
return false;
}
|
diff --git a/HTML/server/WebsocketServer/src/org/java_websocket/ServerManager.java b/HTML/server/WebsocketServer/src/org/java_websocket/ServerManager.java
index 78717e4..fe04802 100644
--- a/HTML/server/WebsocketServer/src/org/java_websocket/ServerManager.java
+++ b/HTML/server/WebsocketServer/src/org/java_websocket/ServerManager.java
@@ -1,92 +1,92 @@
package org.java_websocket;
/**
*
* @author Matteo Ciman
*
* @version 1.0
*/
import java.net.UnknownHostException;
import java.util.Date;
import org.json.simple.JSONObject;
public class ServerManager {
private EyeTrackerManager clientEyeTracker = null;
private IPADClientManager clientIpad = null;
private DoctorClientManager clientDoctor = null;
private boolean eyeTrackerReady = false;
private boolean gameReady = false;
private boolean doctorClientReady = false;
protected void timeToStart() {
long minimumIncrement = 10000;
long timeToStart = new Date().getTime() + minimumIncrement;
clientEyeTracker.comunicateStartTime(timeToStart);
clientIpad.comunicateStartTime(timeToStart);
}
public void startManagers() {
clientEyeTracker.start();
clientIpad.start();
clientDoctor.start();
}
public void stopGame(JSONObject packet) {
clientEyeTracker.sendPacket(packet);
clientIpad.sendPacket(packet);
clientDoctor.sendPacket(packet);
WebSocketWithOffsetCalc.messageManager.gameIsEnded();
}
public void messageFromDoctorToClient(JSONObject packet) {
clientIpad.sendPacket(packet);
}
public ServerManager() throws UnknownHostException{
int eyeTrackerPort = 8000;
int ipadPort = 8001;
int doctorPort = 8002;
clientDoctor = new DoctorClientManager(doctorPort);
clientEyeTracker = new EyeTrackerManager(eyeTrackerPort);
clientIpad = new IPADClientManager(ipadPort);
WebSocketWithOffsetCalc.setDoctorClientManager(clientDoctor);
}
/* Definire un metodo che permetta di chiudere applicazione
* che deve però essere invocato da un utente esterno
*/
public static void main(String args[]) {
WebSocket.DEBUG = false;
String host = "localhost";
if (args.length != 0) {
host = args[0];
}
System.out.println(host);
try {
ServerManager manager = new ServerManager();
BaseManager.setServerManager(manager);
manager.startManagers();
System.out.println("Server Started");
Thread.sleep(3000);
- //EyeTrackerSimulator simulator = new EyeTrackerSimulator(host, 8000);
- //simulator.connect();
+ EyeTrackerSimulator simulator = new EyeTrackerSimulator(host, 8000);
+ simulator.connect();
}
catch (Exception exc) {
exc.printStackTrace();
}
}
}
| true | true | public static void main(String args[]) {
WebSocket.DEBUG = false;
String host = "localhost";
if (args.length != 0) {
host = args[0];
}
System.out.println(host);
try {
ServerManager manager = new ServerManager();
BaseManager.setServerManager(manager);
manager.startManagers();
System.out.println("Server Started");
Thread.sleep(3000);
//EyeTrackerSimulator simulator = new EyeTrackerSimulator(host, 8000);
//simulator.connect();
}
catch (Exception exc) {
exc.printStackTrace();
}
}
| public static void main(String args[]) {
WebSocket.DEBUG = false;
String host = "localhost";
if (args.length != 0) {
host = args[0];
}
System.out.println(host);
try {
ServerManager manager = new ServerManager();
BaseManager.setServerManager(manager);
manager.startManagers();
System.out.println("Server Started");
Thread.sleep(3000);
EyeTrackerSimulator simulator = new EyeTrackerSimulator(host, 8000);
simulator.connect();
}
catch (Exception exc) {
exc.printStackTrace();
}
}
|
diff --git a/src/main/java/hudson/plugins/accurev/AccurevSCM.java b/src/main/java/hudson/plugins/accurev/AccurevSCM.java
index 2c47e7c..e4d0831 100644
--- a/src/main/java/hudson/plugins/accurev/AccurevSCM.java
+++ b/src/main/java/hudson/plugins/accurev/AccurevSCM.java
@@ -1,1232 +1,1233 @@
package hudson.plugins.accurev;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.ModelObject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.jetty.security.Password;
import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogParser;
import hudson.scm.ChangeLogSet;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.ArgumentListBuilder;
import hudson.util.IOException2;
import org.codehaus.plexus.util.StringOutputStream;
import org.kohsuke.stapler.StaplerRequest;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;
/**
* Created by IntelliJ IDEA.
*
* @author connollys
* @since 09-Oct-2007 16:17:34
*/
public class AccurevSCM extends SCM {
private static final Logger logger = Logger.getLogger(AccurevSCM.class.getName());
public static final SimpleDateFormat ACCUREV_DATETIME_FORMATTER = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static final long MILLIS_PER_SECOND = 1000L;
private final String serverName;
private final String depot;
private final String stream;
private final boolean useWorkspace;
private final boolean useUpdate;
private final boolean synctime;
private final String workspace;
private final String workspaceSubPath;
/**
* @stapler-constructor
*/
public AccurevSCM(String serverName,
String depot,
String stream,
boolean useWorkspace,
String workspace,
String workspaceSubPath,
boolean synctime,
boolean useUpdate) {
super();
this.serverName = serverName;
this.depot = depot;
this.stream = stream;
this.useWorkspace = useWorkspace;
this.workspace = workspace;
this.workspaceSubPath = workspaceSubPath;
this.synctime = synctime;
this.useUpdate = useUpdate;
}
/**
* {@inheritDoc}
*/
public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
final String accurevPath = workspace.act(new FindAccurevHome());
AccurevServer server = DESCRIPTOR.getServer(serverName);
Map<String, String> accurevEnv = new HashMap<String, String>();
if (!accurevLogin(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
if (synctime) {
listener.getLogger().println("Synchronizing clock with the server...");
if (!synctime(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
}
final Run lastBuild = project.getLastBuild();
if (lastBuild == null) {
listener.getLogger().println("Project has never been built");
return true;
}
final Date buildDate = lastBuild.getTimestamp().getTime();
listener.getLogger().println("Last build on " + buildDate);
Map<String, AccurevStream> streams = getStreams(server, accurevEnv, workspace, listener, accurevPath, launcher);
AccurevStream stream = streams.get(this.stream);
if (stream == null) {
// if there was a problem, fall back to simple stream check
return checkStreamForChanges(server, accurevEnv, workspace, listener, accurevPath, launcher, this.stream, buildDate);
}
// There may be changes in a parent stream that we need to factor in.
do {
if (checkStreamForChanges(server, accurevEnv, workspace, listener, accurevPath, launcher, stream.getName(), buildDate)) {
return true;
}
stream = stream.getParent();
} while (stream != null && stream.isReceivingChangesFromParent());
return false;
}
private boolean checkStreamForChanges(AccurevServer server,
Map<String, String> accurevEnv,
FilePath workspace,
TaskListener listener,
String accurevPath,
Launcher launcher,
String stream,
Date buildDate)
throws IOException, InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("hist");
addServer(cmd, server);
cmd.add("-fx");
cmd.add("-p");
cmd.add(depot);
cmd.add("-s");
cmd.add(stream);
cmd.add("-t");
cmd.add("now.1");
StringOutputStream sos = new StringOutputStream();
int rv;
if (0 != (rv = launchAccurev(launcher, cmd, accurevEnv, null, sos, workspace))) {
listener.fatalError("History command failed with exit code " + rv);
return false;
}
try {
XmlPullParser parser = newPullParser();
parser.setInput(new StringReader(sos.toString()));
while (true) {
if (parser.next() != XmlPullParser.START_TAG) {
continue;
}
if (!parser.getName().equalsIgnoreCase("transaction")) {
continue;
}
break;
}
String transactionId = parser.getAttributeValue("", "id");
String transactionType = parser.getAttributeValue("", "type");
String transactionTime = parser.getAttributeValue("", "time");
String transactionUser = parser.getAttributeValue("", "user");
Date transactionDate = convertAccurevTimestamp(transactionTime);
listener.getLogger().println("Last change on " + transactionDate);
listener.getLogger().println("#" + transactionId + " " + transactionUser + " " + transactionType);
String transactionComment = null;
boolean inComment = false;
while (transactionComment == null) {
switch (parser.next()) {
case XmlPullParser.START_TAG:
inComment = parser.getName().equalsIgnoreCase("comment");
break;
case XmlPullParser.END_TAG:
inComment = false;
break;
case XmlPullParser.TEXT:
if (inComment) {
transactionComment = parser.getText();
}
break;
case XmlPullParser.END_DOCUMENT:
transactionComment = "";
default:
continue;
}
}
if (transactionComment != null) {
listener.getLogger().println(transactionComment);
}
return buildDate == null || buildDate.compareTo(transactionDate) < 0;
} catch (XmlPullParserException e) {
e.printStackTrace(listener.getLogger());
logger.warning(e.getMessage());
return false;
}
}
private boolean synctime(AccurevServer server,
Map<String, String> accurevEnv,
FilePath workspace,
TaskListener listener,
String accurevPath,
Launcher launcher)
throws IOException, InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("synctime");
addServer(cmd, server);
StringOutputStream sos = new StringOutputStream();
int rv;
if (0 != (rv = launchAccurev(launcher, cmd, accurevEnv, null, sos, workspace))) {
listener.fatalError("Synctime command failed with exit code " + rv);
return false;
}
return true;
}
private Map<String, AccurevStream> getStreams(AccurevServer server,
Map<String, String> accurevEnv,
FilePath workspace,
TaskListener listener,
String accurevPath,
Launcher launcher)
throws IOException, InterruptedException {
Map<String, AccurevStream> streams = new HashMap<String, AccurevStream>();
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("show");
addServer(cmd, server);
cmd.add("-fx");
cmd.add("-p");
cmd.add(depot);
cmd.add("streams");
StringOutputStream sos = new StringOutputStream();
int rv;
if (0 != (rv = launchAccurev(launcher, cmd, accurevEnv, null, sos, workspace))) {
listener.fatalError("Show streams command failed with exit code " + rv);
return null;
}
try {
XmlPullParser parser = newPullParser();
parser.setInput(new StringReader(sos.toString()));
while (true) {
switch (parser.next()) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.END_DOCUMENT:
// build the tree
for (AccurevStream stream : streams.values()) {
if (stream.getBasisName() != null) {
stream.setParent(streams.get(stream.getBasisName()));
}
}
return streams;
case XmlPullParser.START_TAG:
final String tagName = parser.getName();
if ("stream".equalsIgnoreCase(tagName)) {
String streamName = parser.getAttributeValue("", "name");
String streamNumber = parser.getAttributeValue("", "streamNumber");
String basisStreamName = parser.getAttributeValue("", "basis");
String basisStreamNumber = parser.getAttributeValue("", "basisStreamNumber");
String streamType = parser.getAttributeValue("", "type");
String streamIsDynamic = parser.getAttributeValue("", "isDynamic");
String streamTimeString = parser.getAttributeValue("", "time");
Date streamTime = streamTimeString == null ? null : convertAccurevTimestamp(streamTimeString);
String streamStartTimeString = parser.getAttributeValue("", "startTime");
Date streamStartTime = streamTimeString == null ? null : convertAccurevTimestamp(streamTimeString);
try {
AccurevStream stream = new AccurevStream(streamName,
streamNumber == null ? null : Long.valueOf(streamNumber),
depot,
basisStreamName,
basisStreamNumber == null ? null : Long.valueOf(basisStreamNumber),
streamIsDynamic == null ? false : Boolean.parseBoolean(streamIsDynamic),
AccurevStream.StreamType.parseStreamType(streamType),
streamTime,
streamStartTime);
streams.put(streamName, stream);
} catch (NumberFormatException e) {
e.printStackTrace(listener.getLogger());
}
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.TEXT:
break;
}
}
} catch (XmlPullParserException e) {
e.printStackTrace(listener.getLogger());
logger.warning(e.getMessage());
return null;
}
}
private Map<String, AccurevWorkspace> getWorkspaces(AccurevServer server,
Map<String, String> accurevEnv,
FilePath workspace,
TaskListener listener,
String accurevPath,
Launcher launcher)
throws IOException, InterruptedException {
Map<String, AccurevWorkspace> workspaces = new HashMap<String, AccurevWorkspace>();
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("show");
addServer(cmd, server);
cmd.add("-fx");
cmd.add("-p");
cmd.add(depot);
cmd.add("wspaces");
StringOutputStream sos = new StringOutputStream();
int rv;
if (0 != (rv = launchAccurev(launcher, cmd, accurevEnv, null, sos, workspace))) {
listener.fatalError("Show workspaces command failed with exit code " + rv);
return null;
}
try {
XmlPullParser parser = newPullParser();
parser.setInput(new StringReader(sos.toString()));
while (true) {
switch (parser.next()) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.END_DOCUMENT:
return workspaces;
case XmlPullParser.START_TAG:
final String tagName = parser.getName();
if ("Element".equalsIgnoreCase(tagName)) {
String name = parser.getAttributeValue("", "Name");
String storage = parser.getAttributeValue("", "Storage");
String host = parser.getAttributeValue("", "Host");
String streamNumber = parser.getAttributeValue("", "Stream");
String depot = parser.getAttributeValue("", "depot");
try {
workspaces.put(name, new AccurevWorkspace(
depot,
streamNumber == null ? null : Long.valueOf(streamNumber),
name,
host,
storage));
} catch (NumberFormatException e) {
e.printStackTrace(listener.getLogger());
}
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.TEXT:
break;
}
}
} catch (XmlPullParserException e) {
e.printStackTrace(listener.getLogger());
logger.warning(e.getMessage());
return null;
}
}
/**
* {@inheritDoc}
*/
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
final String accurevPath = workspace.act(new FindAccurevHome());
if (!useWorkspace
|| !useUpdate
|| (build.getPreviousBuild() != null && build.getPreviousBuild().getResult().isWorseThan(Result.UNSTABLE))) {
workspace.act(new PurgeWorkspaceContents(listener));
}
AccurevServer server = DESCRIPTOR.getServer(serverName);
Map<String, String> accurevEnv = new HashMap<String, String>();
if (!accurevLogin(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
if (synctime) {
listener.getLogger().println("Synchronizing clock with the server...");
if (!synctime(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
}
listener.getLogger().println("Getting a list of streams...");
final Map<String, AccurevStream> streams = getStreams(server, accurevEnv, workspace, listener, accurevPath,
launcher);
if (depot == null || "".equals(depot)) {
listener.fatalError("Must specify a depot");
return false;
}
if (stream == null || "".equals(stream)) {
listener.fatalError("Must specify a stream");
return false;
}
if (streams != null && !streams.containsKey(stream)) {
listener.fatalError("The specified stream does not appear to exist!");
return false;
}
if (useWorkspace && (this.workspace == null || "".equals(this.workspace))) {
listener.fatalError("Must specify a workspace");
return false;
}
if (useWorkspace) {
listener.getLogger().println("Getting a list of workspaces...");
Map<String, AccurevWorkspace> workspaces = getWorkspaces(server, accurevEnv, workspace, listener,
accurevPath, launcher);
if (workspaces == null) {
listener.fatalError("Cannot determine workspace configuration information");
return false;
}
if (!workspaces.containsKey(this.workspace)) {
listener.fatalError("The specified workspace does not appear to exist!");
return false;
}
AccurevWorkspace accurevWorkspace = workspaces.get(this.workspace);
if (!depot.equals(accurevWorkspace.getDepot())) {
listener.fatalError("The specified workspace, " + this.workspace + ", is based in the depot " +
accurevWorkspace.getDepot() + " not " + depot);
return false;
}
for (AccurevStream accurevStream : streams.values()) {
if (accurevWorkspace.getStreamNumber().equals(accurevStream.getNumber())) {
accurevWorkspace.setStream(accurevStream);
break;
}
}
RemoteWorkspaceDetails remoteDetails;
try {
remoteDetails = workspace.act(new DetermineRemoteHostname(workspace.getRemote()));
} catch (IOException e) {
listener.fatalError("Unable to validate workspace host.");
e.printStackTrace(listener.getLogger());
return false;
}
boolean needsRelocation = false;
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("chws");
addServer(cmd, server);
cmd.add("-w");
cmd.add(this.workspace);
if (!stream.equals(accurevWorkspace.getStream().getParent().getName())) {
listener.getLogger().println("Parent stream needs to be updated.");
needsRelocation = true;
cmd.add("-b");
cmd.add(this.stream);
}
if (!accurevWorkspace.getHost().equals(remoteDetails.getHostName())) {
listener.getLogger().println("Host needs to be updated.");
needsRelocation = true;
cmd.add("-m");
cmd.add(remoteDetails.getHostName());
}
final String oldStorage = accurevWorkspace.getStorage()
.replace("/", remoteDetails.getFileSeparator())
.replace("\\", remoteDetails.getFileSeparator());
if (!oldStorage.equals(remoteDetails.getPath())) {
listener.getLogger().println("Storage needs to be updated.");
needsRelocation = true;
cmd.add("-l");
cmd.add(workspace.getRemote());
}
if (needsRelocation) {
listener.getLogger().println("Relocating workspace...");
listener.getLogger().println(" Old host: " + accurevWorkspace.getHost());
listener.getLogger().println(" New host: " + remoteDetails.getHostName());
listener.getLogger().println(" Old storage: " + oldStorage);
listener.getLogger().println(" New storage: " + remoteDetails.getPath());
listener.getLogger().println(" Old parent stream: " + accurevWorkspace.getStream().getParent()
.getName());
listener.getLogger().println(" New parent stream: " + stream);
listener.getLogger().println(cmd.toStringWithQuote());
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Relocation failed with exit code " + rv);
return false;
}
listener.getLogger().println("Relocation successfully.");
}
listener.getLogger().println("Updating workspace...");
cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("update");
addServer(cmd, server);
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Update failed with exit code " + rv);
return false;
}
listener.getLogger().println("Update completed successfully.");
listener.getLogger().println("Populating workspace...");
cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("pop");
addServer(cmd, server);
cmd.add("-R");
if ((workspaceSubPath == null) || (workspaceSubPath.trim().length() == 0)) {
cmd.add(".");
} else {
cmd.add(workspaceSubPath);
}
+ rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Populate failed with exit code " + rv);
return false;
}
listener.getLogger().println("Populate completed successfully.");
} else {
listener.getLogger().println("Populating workspace...");
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("pop");
addServer(cmd, server);
cmd.add("-v");
cmd.add(stream);
cmd.add("-L");
cmd.add(workspace.getRemote());
cmd.add("-R");
if ((workspaceSubPath == null) || (workspaceSubPath.trim().length() == 0)) {
cmd.add(".");
} else {
cmd.add(workspaceSubPath);
}
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Populate failed with exit code " + rv);
return false;
}
listener.getLogger().println("Populate completed successfully.");
}
listener.getLogger().println("Calculating changelog...");
Calendar startTime = null;
if (null == build.getPreviousBuild()) {
listener.getLogger().println("Cannot find a previous build to compare against. Computing all changes.");
} else {
startTime = build.getPreviousBuild().getTimestamp();
}
{
AccurevStream stream = streams.get(this.stream);
if (stream == null) {
// if there was a problem, fall back to simple stream check
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime.getTime(),
this.stream, changelogFile);
}
// There may be changes in a parent stream that we need to factor in.
// TODO produce a consolidated list of changes from the parent streams
do {
// This is a best effort to get as close to the changes as possible
if (checkStreamForChanges(server, accurevEnv, workspace, listener, accurevPath, launcher,
stream.getName(), startTime == null ? null : startTime.getTime())) {
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime
.getTime(), stream.getName(), changelogFile);
}
stream = stream.getParent();
} while (stream != null && stream.isReceivingChangesFromParent());
}
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime.getTime(), this.stream,
changelogFile);
}
private boolean captureChangelog(AccurevServer server,
Map<String, String> accurevEnv,
FilePath workspace,
BuildListener listener,
String accurevPath,
Launcher launcher,
Date buildDate,
Date startDate,
String stream,
File changelogFile) throws IOException, InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("hist");
addServer(cmd, server);
cmd.add("-fx");
cmd.add("-a");
cmd.add("-s");
cmd.add(stream);
cmd.add("-t");
String dateRange = ACCUREV_DATETIME_FORMATTER.format(buildDate);
if (startDate != null) {
dateRange += "-" + ACCUREV_DATETIME_FORMATTER.format(startDate);
} else {
dateRange += ".100";
}
cmd.add(dateRange); // if this breaks windows there's going to be fun
FileOutputStream os = new FileOutputStream(changelogFile);
try {
BufferedOutputStream bos = new BufferedOutputStream(os);
try {
int rv = launchAccurev(launcher, cmd, accurevEnv, null, bos, workspace);
if (rv != 0) {
listener.fatalError("Changelog failed with exit code " + rv);
return false;
}
} finally {
bos.close();
}
} finally {
os.close();
}
listener.getLogger().println("Changelog calculated successfully.");
return true;
}
private boolean accurevLogin(AccurevServer server, Map<String, String> accurevEnv, FilePath workspace, TaskListener listener, String accurevPath, Launcher launcher) throws IOException, InterruptedException {
ArgumentListBuilder cmd;
if (server != null) {
accurevEnv.put("ACCUREV_HOME", workspace.getParent().getRemote());
listener.getLogger().println("Authenticating with Accurev server...");
boolean[] masks;
cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("login");
addServer(cmd, server);
cmd.add(server.getUsername());
if (server.getPassword() == null || "".equals(server.getPassword())) {
cmd.addQuoted("");
masks = new boolean[cmd.toCommandArray().length];
} else {
cmd.add(server.getPassword());
masks = new boolean[cmd.toCommandArray().length];
masks[masks.length - 1] = true;
}
String resp = null;
DESCRIPTOR.ACCUREV_LOCK.lock();
try {
StringOutputStream sos = new StringOutputStream();
int rv = launcher.launch(cmd.toCommandArray(), masks, Util.mapToEnv(accurevEnv), null, sos, workspace)
.join();
if (rv == 0) {
resp = null;
} else {
resp = sos.toString();
}
} finally {
DESCRIPTOR.ACCUREV_LOCK.unlock();
}
if (null == resp || "".equals(resp)) {
listener.getLogger().println("Authentication completed successfully.");
return true;
} else {
listener.fatalError("Authentication failed: " + resp);
return false;
}
}
return true;
}
private int launchAccurev(Launcher launcher,
ArgumentListBuilder cmd,
Map<String, String> env,
InputStream in,
OutputStream os,
FilePath workspace) throws IOException, InterruptedException {
int rv;
DESCRIPTOR.ACCUREV_LOCK.lock();
try {
rv = launcher.launch(cmd.toCommandArray(), Util.mapToEnv(env), in, os, workspace).join();
} finally {
DESCRIPTOR.ACCUREV_LOCK.unlock();
}
return rv;
}
private void addServer(ArgumentListBuilder cmd, AccurevServer server) {
if (null != server && null != server.getHost() && !"".equals(server.getHost())) {
cmd.add("-H");
if (server.getPort() != 0) {
cmd.add(server.getHost() + ":" + server.getPort());
} else {
cmd.add(server.getHost());
}
}
}
/**
* {@inheritDoc}
*/
public ChangeLogParser createChangeLogParser() {
return new AccurevChangeLogParser();
}
/**
* Getter for property 'useWorkspace'.
*
* @return Value for property 'useWorkspace'.
*/
public boolean isUseWorkspace() {
return useWorkspace;
}
/**
* Getter for property 'useUpdate'.
*
* @return Value for property 'useUpdate'.
*/
public boolean isUseUpdate() {
return useUpdate;
}
/**
* Getter for property 'workspace'.
*
* @return Value for property 'workspace'.
*/
public String getWorkspace() {
return workspace;
}
/**
* Getter for property 'serverName'.
*
* @return Value for property 'serverName'.
*/
public String getServerName() {
return serverName;
}
/**
* Getter for property 'depot'.
*
* @return Value for property 'depot'.
*/
public String getDepot() {
return depot;
}
/**
* Getter for property 'stream'.
*
* @return Value for property 'stream'.
*/
public String getStream() {
return stream;
}
/**
* Getter for property 'workspaceSubPath'.
*
* @return Value for property 'workspaceSubPath'.
*/
public String getWorkspaceSubPath() {
return workspaceSubPath;
}
/**
* Getter for property 'synctime'.
*
* @return Value for property 'synctime'.
*/
public boolean isSynctime() {
return synctime;
}
private static Date convertAccurevTimestamp(String transactionTime) {
if (transactionTime == null) {
return null;
}
try {
final long time = Long.parseLong(transactionTime);
final long date = time * MILLIS_PER_SECOND;
return new Date(date);
} catch (NumberFormatException e) {
return null;
}
}
private static XmlPullParser newPullParser() throws XmlPullParserException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
XmlPullParser parser = factory.newPullParser();
return parser;
}
/**
* {@inheritDoc}
*/
public SCMDescriptor<?> getDescriptor() {
return DESCRIPTOR;
}
public static final AccurevSCMDescriptor DESCRIPTOR = new AccurevSCMDescriptor();
public static final class AccurevSCMDescriptor extends SCMDescriptor<AccurevSCM> implements ModelObject {
/**
* The accurev server has been known to crash if more than one copy of the accurev has been run concurrently
* on the local machine.
*/
transient static final Lock ACCUREV_LOCK = new ReentrantLock();
private List<AccurevServer> servers;
/**
* Constructs a new AccurevSCMDescriptor.
*/
protected AccurevSCMDescriptor() {
super(AccurevSCM.class, null);
load();
}
/**
* {@inheritDoc}
*/
@Override
public String getDisplayName() {
return "Accurev";
}
/**
* {@inheritDoc}
*/
@Override
public boolean configure(StaplerRequest req) throws FormException {
req.bindParameters(this, "accurev.");
servers = req.bindParametersToList(AccurevServer.class, "accurev.server.");
save();
return true;
}
/**
* {@inheritDoc}
*/
@Override
public SCM newInstance(StaplerRequest req) throws FormException {
return req.bindParameters(AccurevSCM.class, "accurev.");
}
/**
* Getter for property 'servers'.
*
* @return Value for property 'servers'.
*/
public List<AccurevServer> getServers() {
if (servers == null) {
servers = new ArrayList<AccurevServer>();
}
return servers;
}
/**
* Setter for property 'servers'.
*
* @param servers Value to set for property 'servers'.
*/
public void setServers(List<AccurevServer> servers) {
this.servers = servers;
}
public AccurevServer getServer(String name) {
if (name == null) {
return null;
}
for (AccurevServer server : servers) {
if (name.equals(server.getName())) {
return server;
}
}
return null;
}
/**
* Getter for property 'serverNames'.
*
* @return Value for property 'serverNames'.
*/
public String[] getServerNames() {
String[] result = new String[servers.size()];
for (int i = 0; i < result.length; i++) {
result[i] = servers.get(i).getName();
}
return result;
}
}
public static final class AccurevServer {
private String name;
private String host;
private int port;
private String username;
private String password;
/**
* Constructs a new AccurevServer.
*/
public AccurevServer() {
}
public AccurevServer(String name, String host, int port, String username, String password) {
this.name = name;
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}
/**
* Getter for property 'name'.
*
* @return Value for property 'name'.
*/
public String getName() {
return name;
}
/**
* Setter for property 'name'.
*
* @param name Value to set for property 'name'.
*/
public void setName(String name) {
this.name = name;
}
/**
* Getter for property 'host'.
*
* @return Value for property 'host'.
*/
public String getHost() {
return host;
}
/**
* Setter for property 'host'.
*
* @param host Value to set for property 'host'.
*/
public void setHost(String host) {
this.host = host;
}
/**
* Getter for property 'port'.
*
* @return Value for property 'port'.
*/
public int getPort() {
return port;
}
/**
* Setter for property 'port'.
*
* @param port Value to set for property 'port'.
*/
public void setPort(int port) {
this.port = port;
}
/**
* Getter for property 'username'.
*
* @return Value for property 'username'.
*/
public String getUsername() {
return username;
}
/**
* Setter for property 'username'.
*
* @param username Value to set for property 'username'.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Getter for property 'password'.
*
* @return Value for property 'password'.
*/
public String getPassword() {
return Password.deobfuscate(password);
}
/**
* Setter for property 'password'.
*
* @param password Value to set for property 'password'.
*/
public void setPassword(String password) {
this.password = Password.obfuscate(password);
}
}
private static final class PurgeWorkspaceContents implements FilePath.FileCallable<Boolean> {
private final TaskListener listener;
public PurgeWorkspaceContents(TaskListener listener) {
this.listener = listener;
}
/**
* {@inheritDoc}
*/
public Boolean invoke(File ws, VirtualChannel channel) throws IOException {
listener.getLogger().println("Purging workspace...");
Util.deleteContentsRecursive(ws);
listener.getLogger().println("Workspace purged.");
return Boolean.TRUE;
}
}
private static final class FindAccurevHome implements FilePath.FileCallable<String> {
private String[] nonWindowsPaths = {
"/usr/local/bin/accurev",
"/usr/bin/accurev",
"/bin/accurev",
"/local/bin/accurev",
};
private String[] windowsPaths = {
"C:\\Program Files\\AccuRev\\bin\\accurev.exe",
"C:\\Program Files (x86)\\AccuRev\\bin\\accurev.exe"
};
private static String getExistingPath(String[] paths) {
for (int i = 0; i < paths.length; i++) {
if (new File(paths[i]).exists()) {
return paths[i];
}
}
return paths[0];
}
/**
* {@inheritDoc}
*/
public String invoke(File f, VirtualChannel channel) throws IOException {
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
// we are running on windows
return getExistingPath(windowsPaths);
} else {
// we are running on *nix
return getExistingPath(nonWindowsPaths);
}
}
}
private static final class AccurevChangeLogParser extends ChangeLogParser {
/**
* {@inheritDoc}
*/
public ChangeLogSet<AccurevTransaction> parse(AbstractBuild build, File changelogFile) throws IOException, SAXException {
List<AccurevTransaction> transactions = null;
try {
XmlPullParser parser = newPullParser();
FileReader fis = null;
BufferedReader bis = null;
try {
fis = new FileReader(changelogFile);
bis = new BufferedReader(fis);
parser.setInput(bis);
transactions = parseTransactions(parser);
} finally {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
}
} catch (XmlPullParserException e) {
throw new IOException2(e);
}
logger.info("transations size = " + transactions.size());
return new AccurevChangeLogSet(build, transactions);
}
private List<AccurevTransaction> parseTransactions(XmlPullParser parser) throws IOException, XmlPullParserException {
List<AccurevTransaction> transactions = new ArrayList<AccurevTransaction>();
AccurevTransaction currentTransaction = null;
boolean inComment = false;
while (true) {
switch (parser.next()) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.END_DOCUMENT:
return transactions;
case XmlPullParser.START_TAG:
final String tagName = parser.getName();
inComment = "comment".equalsIgnoreCase(tagName);
if ("transaction".equalsIgnoreCase(tagName)) {
currentTransaction = new AccurevTransaction();
transactions.add(currentTransaction);
currentTransaction.setRevision(parser.getAttributeValue("", "id"));
currentTransaction.setUser(parser.getAttributeValue("", "user"));
currentTransaction.setDate(convertAccurevTimestamp(parser.getAttributeValue("", "time")));
currentTransaction.setAction(parser.getAttributeValue("", "type"));
} else if ("version".equalsIgnoreCase(tagName) && currentTransaction != null) {
String path = parser.getAttributeValue("", "path");
if (path != null) {
path = path.replace("\\", "/");
if (path.startsWith("/./")) {
path = path.substring(3);
}
}
currentTransaction.addAffectedPath(path);
}
break;
case XmlPullParser.END_TAG:
inComment = false;
break;
case XmlPullParser.TEXT:
if (inComment && currentTransaction != null) {
currentTransaction.setMsg(parser.getText());
}
break;
}
}
}
}
private static class RemoteWorkspaceDetails implements Serializable {
private final String hostName;
private final String path;
private final String fileSeparator;
public RemoteWorkspaceDetails(String hostName, String path, String fileSeparator) {
this.hostName = hostName;
this.path = path;
this.fileSeparator = fileSeparator;
}
/**
* Getter for property 'hostName'.
*
* @return Value for property 'hostName'.
*/
public String getHostName() {
return hostName;
}
/**
* Getter for property 'path'.
*
* @return Value for property 'path'.
*/
public String getPath() {
return path;
}
/**
* Getter for property 'fileSeparator'.
*
* @return Value for property 'fileSeparator'.
*/
public String getFileSeparator() {
return fileSeparator;
}
}
private static class DetermineRemoteHostname implements Callable<RemoteWorkspaceDetails, UnknownHostException> {
private final String path;
public DetermineRemoteHostname(String path) {
this.path = path;
}
/**
* {@inheritDoc}
*/
public RemoteWorkspaceDetails call() throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
File f = new File(path);
String path;
try {
path = f.getCanonicalPath();
} catch (IOException e) {
path = f.getAbsolutePath();
}
return new RemoteWorkspaceDetails(addr.getCanonicalHostName(), path, File.separator);
}
}
}
| true | true | public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
final String accurevPath = workspace.act(new FindAccurevHome());
if (!useWorkspace
|| !useUpdate
|| (build.getPreviousBuild() != null && build.getPreviousBuild().getResult().isWorseThan(Result.UNSTABLE))) {
workspace.act(new PurgeWorkspaceContents(listener));
}
AccurevServer server = DESCRIPTOR.getServer(serverName);
Map<String, String> accurevEnv = new HashMap<String, String>();
if (!accurevLogin(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
if (synctime) {
listener.getLogger().println("Synchronizing clock with the server...");
if (!synctime(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
}
listener.getLogger().println("Getting a list of streams...");
final Map<String, AccurevStream> streams = getStreams(server, accurevEnv, workspace, listener, accurevPath,
launcher);
if (depot == null || "".equals(depot)) {
listener.fatalError("Must specify a depot");
return false;
}
if (stream == null || "".equals(stream)) {
listener.fatalError("Must specify a stream");
return false;
}
if (streams != null && !streams.containsKey(stream)) {
listener.fatalError("The specified stream does not appear to exist!");
return false;
}
if (useWorkspace && (this.workspace == null || "".equals(this.workspace))) {
listener.fatalError("Must specify a workspace");
return false;
}
if (useWorkspace) {
listener.getLogger().println("Getting a list of workspaces...");
Map<String, AccurevWorkspace> workspaces = getWorkspaces(server, accurevEnv, workspace, listener,
accurevPath, launcher);
if (workspaces == null) {
listener.fatalError("Cannot determine workspace configuration information");
return false;
}
if (!workspaces.containsKey(this.workspace)) {
listener.fatalError("The specified workspace does not appear to exist!");
return false;
}
AccurevWorkspace accurevWorkspace = workspaces.get(this.workspace);
if (!depot.equals(accurevWorkspace.getDepot())) {
listener.fatalError("The specified workspace, " + this.workspace + ", is based in the depot " +
accurevWorkspace.getDepot() + " not " + depot);
return false;
}
for (AccurevStream accurevStream : streams.values()) {
if (accurevWorkspace.getStreamNumber().equals(accurevStream.getNumber())) {
accurevWorkspace.setStream(accurevStream);
break;
}
}
RemoteWorkspaceDetails remoteDetails;
try {
remoteDetails = workspace.act(new DetermineRemoteHostname(workspace.getRemote()));
} catch (IOException e) {
listener.fatalError("Unable to validate workspace host.");
e.printStackTrace(listener.getLogger());
return false;
}
boolean needsRelocation = false;
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("chws");
addServer(cmd, server);
cmd.add("-w");
cmd.add(this.workspace);
if (!stream.equals(accurevWorkspace.getStream().getParent().getName())) {
listener.getLogger().println("Parent stream needs to be updated.");
needsRelocation = true;
cmd.add("-b");
cmd.add(this.stream);
}
if (!accurevWorkspace.getHost().equals(remoteDetails.getHostName())) {
listener.getLogger().println("Host needs to be updated.");
needsRelocation = true;
cmd.add("-m");
cmd.add(remoteDetails.getHostName());
}
final String oldStorage = accurevWorkspace.getStorage()
.replace("/", remoteDetails.getFileSeparator())
.replace("\\", remoteDetails.getFileSeparator());
if (!oldStorage.equals(remoteDetails.getPath())) {
listener.getLogger().println("Storage needs to be updated.");
needsRelocation = true;
cmd.add("-l");
cmd.add(workspace.getRemote());
}
if (needsRelocation) {
listener.getLogger().println("Relocating workspace...");
listener.getLogger().println(" Old host: " + accurevWorkspace.getHost());
listener.getLogger().println(" New host: " + remoteDetails.getHostName());
listener.getLogger().println(" Old storage: " + oldStorage);
listener.getLogger().println(" New storage: " + remoteDetails.getPath());
listener.getLogger().println(" Old parent stream: " + accurevWorkspace.getStream().getParent()
.getName());
listener.getLogger().println(" New parent stream: " + stream);
listener.getLogger().println(cmd.toStringWithQuote());
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Relocation failed with exit code " + rv);
return false;
}
listener.getLogger().println("Relocation successfully.");
}
listener.getLogger().println("Updating workspace...");
cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("update");
addServer(cmd, server);
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Update failed with exit code " + rv);
return false;
}
listener.getLogger().println("Update completed successfully.");
listener.getLogger().println("Populating workspace...");
cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("pop");
addServer(cmd, server);
cmd.add("-R");
if ((workspaceSubPath == null) || (workspaceSubPath.trim().length() == 0)) {
cmd.add(".");
} else {
cmd.add(workspaceSubPath);
}
if (rv != 0) {
listener.fatalError("Populate failed with exit code " + rv);
return false;
}
listener.getLogger().println("Populate completed successfully.");
} else {
listener.getLogger().println("Populating workspace...");
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("pop");
addServer(cmd, server);
cmd.add("-v");
cmd.add(stream);
cmd.add("-L");
cmd.add(workspace.getRemote());
cmd.add("-R");
if ((workspaceSubPath == null) || (workspaceSubPath.trim().length() == 0)) {
cmd.add(".");
} else {
cmd.add(workspaceSubPath);
}
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Populate failed with exit code " + rv);
return false;
}
listener.getLogger().println("Populate completed successfully.");
}
listener.getLogger().println("Calculating changelog...");
Calendar startTime = null;
if (null == build.getPreviousBuild()) {
listener.getLogger().println("Cannot find a previous build to compare against. Computing all changes.");
} else {
startTime = build.getPreviousBuild().getTimestamp();
}
{
AccurevStream stream = streams.get(this.stream);
if (stream == null) {
// if there was a problem, fall back to simple stream check
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime.getTime(),
this.stream, changelogFile);
}
// There may be changes in a parent stream that we need to factor in.
// TODO produce a consolidated list of changes from the parent streams
do {
// This is a best effort to get as close to the changes as possible
if (checkStreamForChanges(server, accurevEnv, workspace, listener, accurevPath, launcher,
stream.getName(), startTime == null ? null : startTime.getTime())) {
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime
.getTime(), stream.getName(), changelogFile);
}
stream = stream.getParent();
} while (stream != null && stream.isReceivingChangesFromParent());
}
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime.getTime(), this.stream,
changelogFile);
}
| public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
final String accurevPath = workspace.act(new FindAccurevHome());
if (!useWorkspace
|| !useUpdate
|| (build.getPreviousBuild() != null && build.getPreviousBuild().getResult().isWorseThan(Result.UNSTABLE))) {
workspace.act(new PurgeWorkspaceContents(listener));
}
AccurevServer server = DESCRIPTOR.getServer(serverName);
Map<String, String> accurevEnv = new HashMap<String, String>();
if (!accurevLogin(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
if (synctime) {
listener.getLogger().println("Synchronizing clock with the server...");
if (!synctime(server, accurevEnv, workspace, listener, accurevPath, launcher)) {
return false;
}
}
listener.getLogger().println("Getting a list of streams...");
final Map<String, AccurevStream> streams = getStreams(server, accurevEnv, workspace, listener, accurevPath,
launcher);
if (depot == null || "".equals(depot)) {
listener.fatalError("Must specify a depot");
return false;
}
if (stream == null || "".equals(stream)) {
listener.fatalError("Must specify a stream");
return false;
}
if (streams != null && !streams.containsKey(stream)) {
listener.fatalError("The specified stream does not appear to exist!");
return false;
}
if (useWorkspace && (this.workspace == null || "".equals(this.workspace))) {
listener.fatalError("Must specify a workspace");
return false;
}
if (useWorkspace) {
listener.getLogger().println("Getting a list of workspaces...");
Map<String, AccurevWorkspace> workspaces = getWorkspaces(server, accurevEnv, workspace, listener,
accurevPath, launcher);
if (workspaces == null) {
listener.fatalError("Cannot determine workspace configuration information");
return false;
}
if (!workspaces.containsKey(this.workspace)) {
listener.fatalError("The specified workspace does not appear to exist!");
return false;
}
AccurevWorkspace accurevWorkspace = workspaces.get(this.workspace);
if (!depot.equals(accurevWorkspace.getDepot())) {
listener.fatalError("The specified workspace, " + this.workspace + ", is based in the depot " +
accurevWorkspace.getDepot() + " not " + depot);
return false;
}
for (AccurevStream accurevStream : streams.values()) {
if (accurevWorkspace.getStreamNumber().equals(accurevStream.getNumber())) {
accurevWorkspace.setStream(accurevStream);
break;
}
}
RemoteWorkspaceDetails remoteDetails;
try {
remoteDetails = workspace.act(new DetermineRemoteHostname(workspace.getRemote()));
} catch (IOException e) {
listener.fatalError("Unable to validate workspace host.");
e.printStackTrace(listener.getLogger());
return false;
}
boolean needsRelocation = false;
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("chws");
addServer(cmd, server);
cmd.add("-w");
cmd.add(this.workspace);
if (!stream.equals(accurevWorkspace.getStream().getParent().getName())) {
listener.getLogger().println("Parent stream needs to be updated.");
needsRelocation = true;
cmd.add("-b");
cmd.add(this.stream);
}
if (!accurevWorkspace.getHost().equals(remoteDetails.getHostName())) {
listener.getLogger().println("Host needs to be updated.");
needsRelocation = true;
cmd.add("-m");
cmd.add(remoteDetails.getHostName());
}
final String oldStorage = accurevWorkspace.getStorage()
.replace("/", remoteDetails.getFileSeparator())
.replace("\\", remoteDetails.getFileSeparator());
if (!oldStorage.equals(remoteDetails.getPath())) {
listener.getLogger().println("Storage needs to be updated.");
needsRelocation = true;
cmd.add("-l");
cmd.add(workspace.getRemote());
}
if (needsRelocation) {
listener.getLogger().println("Relocating workspace...");
listener.getLogger().println(" Old host: " + accurevWorkspace.getHost());
listener.getLogger().println(" New host: " + remoteDetails.getHostName());
listener.getLogger().println(" Old storage: " + oldStorage);
listener.getLogger().println(" New storage: " + remoteDetails.getPath());
listener.getLogger().println(" Old parent stream: " + accurevWorkspace.getStream().getParent()
.getName());
listener.getLogger().println(" New parent stream: " + stream);
listener.getLogger().println(cmd.toStringWithQuote());
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Relocation failed with exit code " + rv);
return false;
}
listener.getLogger().println("Relocation successfully.");
}
listener.getLogger().println("Updating workspace...");
cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("update");
addServer(cmd, server);
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Update failed with exit code " + rv);
return false;
}
listener.getLogger().println("Update completed successfully.");
listener.getLogger().println("Populating workspace...");
cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("pop");
addServer(cmd, server);
cmd.add("-R");
if ((workspaceSubPath == null) || (workspaceSubPath.trim().length() == 0)) {
cmd.add(".");
} else {
cmd.add(workspaceSubPath);
}
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Populate failed with exit code " + rv);
return false;
}
listener.getLogger().println("Populate completed successfully.");
} else {
listener.getLogger().println("Populating workspace...");
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(accurevPath);
cmd.add("pop");
addServer(cmd, server);
cmd.add("-v");
cmd.add(stream);
cmd.add("-L");
cmd.add(workspace.getRemote());
cmd.add("-R");
if ((workspaceSubPath == null) || (workspaceSubPath.trim().length() == 0)) {
cmd.add(".");
} else {
cmd.add(workspaceSubPath);
}
int rv;
rv = launchAccurev(launcher, cmd, accurevEnv, null, listener.getLogger(), workspace);
if (rv != 0) {
listener.fatalError("Populate failed with exit code " + rv);
return false;
}
listener.getLogger().println("Populate completed successfully.");
}
listener.getLogger().println("Calculating changelog...");
Calendar startTime = null;
if (null == build.getPreviousBuild()) {
listener.getLogger().println("Cannot find a previous build to compare against. Computing all changes.");
} else {
startTime = build.getPreviousBuild().getTimestamp();
}
{
AccurevStream stream = streams.get(this.stream);
if (stream == null) {
// if there was a problem, fall back to simple stream check
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime.getTime(),
this.stream, changelogFile);
}
// There may be changes in a parent stream that we need to factor in.
// TODO produce a consolidated list of changes from the parent streams
do {
// This is a best effort to get as close to the changes as possible
if (checkStreamForChanges(server, accurevEnv, workspace, listener, accurevPath, launcher,
stream.getName(), startTime == null ? null : startTime.getTime())) {
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime
.getTime(), stream.getName(), changelogFile);
}
stream = stream.getParent();
} while (stream != null && stream.isReceivingChangesFromParent());
}
return captureChangelog(server, accurevEnv, workspace, listener, accurevPath, launcher,
build.getTimestamp().getTime(), startTime == null ? null : startTime.getTime(), this.stream,
changelogFile);
}
|
diff --git a/src/common/wustendorf/CommandWustendorf.java b/src/common/wustendorf/CommandWustendorf.java
index 7ac30ae..079b114 100644
--- a/src/common/wustendorf/CommandWustendorf.java
+++ b/src/common/wustendorf/CommandWustendorf.java
@@ -1,181 +1,181 @@
package wustendorf;
import net.minecraft.src.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class CommandWustendorf extends CommandBase {
public String getCommandName()
{
return "w";
}
/**
* Return the required permission level for this command.
*/
public int getRequiredPermissionLevel()
{
return 2;
}
public String getCommandUsage(ICommandSender sender)
{
return "/w help";
}
public void processCommand(ICommandSender sender, String[] params)
{
if (!(sender instanceof EntityPlayer)) {
sender.sendChatToPlayer("Not available from console.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
if (!(player.worldObj instanceof WorldServer)) {
// WTF? This is a server command!
sender.sendChatToPlayer("World not sane.");
return;
}
WorldServer world = (WorldServer) player.worldObj;
if (params.length < 1 || params[0].equals("help")) {
if (params.length < 2) {
sender.sendChatToPlayer("Available subcommands:");
sender.sendChatToPlayer("tag, range");
} else if (params[1].equals("tag")) {
sender.sendChatToPlayer("Usage:");
sender.sendChatToPlayer("/w tag {|list} - List tags on target flag.");
sender.sendChatToPlayer("/w tag set <tag> <level> - Set tag on target flag.");
sender.sendChatToPlayer("/w tag clear <tag> - Remove tag from target flag.");
} else if (params[1].equals("range")) {
sender.sendChatToPlayer("Usage:");
sender.sendChatToPlayer("/w range - Show range of target flag.");
sender.sendChatToPlayer("/w range <blocks> - Set range of target flag.");
} else {
sender.sendChatToPlayer("Unknown subcommand.");
}
return;
}
// Flag-bound commands.
- Vec3 position = player.getPosition(0F);
+ Vec3 position = world.getWorldVec3Pool().getVecFromPool(player.posX, player.posY, player.posZ);
position.yCoord += 1.6;
Vec3 look = player.getLook(0F);
Vec3 lookLimit = position.addVector(look.xCoord * 10, look.yCoord * 10, look.zCoord * 10);
MovingObjectPosition hit = world.rayTraceBlocks(position, lookLimit);
boolean good = false;
int x=0, y=0, z=0;
if (hit != null && hit.typeOfHit == EnumMovingObjectType.TILE) {
x = hit.blockX;
y = hit.blockY;
z = hit.blockZ;
int id = world.getBlockId(x, y, z);
Block block = Block.blocksList[id];
if (block instanceof WustendorfMarker) {
good = true;
}
}
if (!good) {
sender.sendChatToPlayer("That's not a house flag.");
return;
}
WustendorfDB worldDB = Wustendorf.getWorldDB(world);
if (params[0].equals("tag")) {
if (params.length < 2 || params[1].equals("list")) {
Map<String, Integer> tags = worldDB.getAllTags(x, y, z);
ArrayList<String> keys = new ArrayList(tags.keySet());
Collections.sort(keys);
String output = "";
for (String key : keys) {
if (output.length() > 0) {
output += ", ";
}
output += key + ":" + tags.get(key);
}
sender.sendChatToPlayer("Current tags:");
sender.sendChatToPlayer(output);
} else if (params[1].equals("clear")) {
if (params.length == 3) {
String tag = params[2];
worldDB.clearTag(tag, x, y, z);
sender.sendChatToPlayer("Removed tag " + tag + ".");
return;
}
sender.sendChatToPlayer("Usage: /w tag clear <tag>");
} else {
boolean okay = false;
int value = -1;
String tag = null;
if (params.length == 3) {
tag = params[1];
try {
value = Integer.parseInt(params[2]);
okay = true;
} catch (NumberFormatException e) { }
}
if (!okay) {
sender.sendChatToPlayer("Usage: /w tag <tag> <level>");
return;
}
worldDB.setTag(value, tag, x, y, z);
sender.sendChatToPlayer("Set tag " + tag + " to " + value + ".");
}
} else if (params[0].equals("range")) {
if (params.length < 2) {
int range = worldDB.getRange(x, y, z);
sender.sendChatToPlayer("This house flag has range " + range + ".");
} else {
boolean okay = false;
int new_range = -1;
if (params.length == 2) {
try {
new_range = Integer.parseInt(params[1]);
okay = true;
} catch (NumberFormatException e) { }
}
if (!okay) {
sender.sendChatToPlayer("Usage: /w range [value]");
return;
}
worldDB.setRange(new_range, x, y, z);
sender.sendChatToPlayer("Range set to " + new_range + ".");
}
} else {
sender.sendChatToPlayer("Unknown subcommand.");
}
}
/**
* Adds the strings available in this command to the given list of tab completion options.
*/
public List addTabCompletionOptions(ICommandSender sender, String[] params)
{
return Collections.EMPTY_LIST;
//return params.length == 1 ? getListOfStringsMatchingLastWord(params, new String[] {"set", "add"}): (params.length == 2 && params[0].equals("set") ? getListOfStringsMatchingLastWord(params, new String[] {"day", "night"}): null);
}
}
| true | true | public void processCommand(ICommandSender sender, String[] params)
{
if (!(sender instanceof EntityPlayer)) {
sender.sendChatToPlayer("Not available from console.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
if (!(player.worldObj instanceof WorldServer)) {
// WTF? This is a server command!
sender.sendChatToPlayer("World not sane.");
return;
}
WorldServer world = (WorldServer) player.worldObj;
if (params.length < 1 || params[0].equals("help")) {
if (params.length < 2) {
sender.sendChatToPlayer("Available subcommands:");
sender.sendChatToPlayer("tag, range");
} else if (params[1].equals("tag")) {
sender.sendChatToPlayer("Usage:");
sender.sendChatToPlayer("/w tag {|list} - List tags on target flag.");
sender.sendChatToPlayer("/w tag set <tag> <level> - Set tag on target flag.");
sender.sendChatToPlayer("/w tag clear <tag> - Remove tag from target flag.");
} else if (params[1].equals("range")) {
sender.sendChatToPlayer("Usage:");
sender.sendChatToPlayer("/w range - Show range of target flag.");
sender.sendChatToPlayer("/w range <blocks> - Set range of target flag.");
} else {
sender.sendChatToPlayer("Unknown subcommand.");
}
return;
}
// Flag-bound commands.
Vec3 position = player.getPosition(0F);
position.yCoord += 1.6;
Vec3 look = player.getLook(0F);
Vec3 lookLimit = position.addVector(look.xCoord * 10, look.yCoord * 10, look.zCoord * 10);
MovingObjectPosition hit = world.rayTraceBlocks(position, lookLimit);
boolean good = false;
int x=0, y=0, z=0;
if (hit != null && hit.typeOfHit == EnumMovingObjectType.TILE) {
x = hit.blockX;
y = hit.blockY;
z = hit.blockZ;
int id = world.getBlockId(x, y, z);
Block block = Block.blocksList[id];
if (block instanceof WustendorfMarker) {
good = true;
}
}
if (!good) {
sender.sendChatToPlayer("That's not a house flag.");
return;
}
WustendorfDB worldDB = Wustendorf.getWorldDB(world);
if (params[0].equals("tag")) {
if (params.length < 2 || params[1].equals("list")) {
Map<String, Integer> tags = worldDB.getAllTags(x, y, z);
ArrayList<String> keys = new ArrayList(tags.keySet());
Collections.sort(keys);
String output = "";
for (String key : keys) {
if (output.length() > 0) {
output += ", ";
}
output += key + ":" + tags.get(key);
}
sender.sendChatToPlayer("Current tags:");
sender.sendChatToPlayer(output);
} else if (params[1].equals("clear")) {
if (params.length == 3) {
String tag = params[2];
worldDB.clearTag(tag, x, y, z);
sender.sendChatToPlayer("Removed tag " + tag + ".");
return;
}
sender.sendChatToPlayer("Usage: /w tag clear <tag>");
} else {
boolean okay = false;
int value = -1;
String tag = null;
if (params.length == 3) {
tag = params[1];
try {
value = Integer.parseInt(params[2]);
okay = true;
} catch (NumberFormatException e) { }
}
if (!okay) {
sender.sendChatToPlayer("Usage: /w tag <tag> <level>");
return;
}
worldDB.setTag(value, tag, x, y, z);
sender.sendChatToPlayer("Set tag " + tag + " to " + value + ".");
}
} else if (params[0].equals("range")) {
if (params.length < 2) {
int range = worldDB.getRange(x, y, z);
sender.sendChatToPlayer("This house flag has range " + range + ".");
} else {
boolean okay = false;
int new_range = -1;
if (params.length == 2) {
try {
new_range = Integer.parseInt(params[1]);
okay = true;
} catch (NumberFormatException e) { }
}
if (!okay) {
sender.sendChatToPlayer("Usage: /w range [value]");
return;
}
worldDB.setRange(new_range, x, y, z);
sender.sendChatToPlayer("Range set to " + new_range + ".");
}
} else {
sender.sendChatToPlayer("Unknown subcommand.");
}
}
| public void processCommand(ICommandSender sender, String[] params)
{
if (!(sender instanceof EntityPlayer)) {
sender.sendChatToPlayer("Not available from console.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
if (!(player.worldObj instanceof WorldServer)) {
// WTF? This is a server command!
sender.sendChatToPlayer("World not sane.");
return;
}
WorldServer world = (WorldServer) player.worldObj;
if (params.length < 1 || params[0].equals("help")) {
if (params.length < 2) {
sender.sendChatToPlayer("Available subcommands:");
sender.sendChatToPlayer("tag, range");
} else if (params[1].equals("tag")) {
sender.sendChatToPlayer("Usage:");
sender.sendChatToPlayer("/w tag {|list} - List tags on target flag.");
sender.sendChatToPlayer("/w tag set <tag> <level> - Set tag on target flag.");
sender.sendChatToPlayer("/w tag clear <tag> - Remove tag from target flag.");
} else if (params[1].equals("range")) {
sender.sendChatToPlayer("Usage:");
sender.sendChatToPlayer("/w range - Show range of target flag.");
sender.sendChatToPlayer("/w range <blocks> - Set range of target flag.");
} else {
sender.sendChatToPlayer("Unknown subcommand.");
}
return;
}
// Flag-bound commands.
Vec3 position = world.getWorldVec3Pool().getVecFromPool(player.posX, player.posY, player.posZ);
position.yCoord += 1.6;
Vec3 look = player.getLook(0F);
Vec3 lookLimit = position.addVector(look.xCoord * 10, look.yCoord * 10, look.zCoord * 10);
MovingObjectPosition hit = world.rayTraceBlocks(position, lookLimit);
boolean good = false;
int x=0, y=0, z=0;
if (hit != null && hit.typeOfHit == EnumMovingObjectType.TILE) {
x = hit.blockX;
y = hit.blockY;
z = hit.blockZ;
int id = world.getBlockId(x, y, z);
Block block = Block.blocksList[id];
if (block instanceof WustendorfMarker) {
good = true;
}
}
if (!good) {
sender.sendChatToPlayer("That's not a house flag.");
return;
}
WustendorfDB worldDB = Wustendorf.getWorldDB(world);
if (params[0].equals("tag")) {
if (params.length < 2 || params[1].equals("list")) {
Map<String, Integer> tags = worldDB.getAllTags(x, y, z);
ArrayList<String> keys = new ArrayList(tags.keySet());
Collections.sort(keys);
String output = "";
for (String key : keys) {
if (output.length() > 0) {
output += ", ";
}
output += key + ":" + tags.get(key);
}
sender.sendChatToPlayer("Current tags:");
sender.sendChatToPlayer(output);
} else if (params[1].equals("clear")) {
if (params.length == 3) {
String tag = params[2];
worldDB.clearTag(tag, x, y, z);
sender.sendChatToPlayer("Removed tag " + tag + ".");
return;
}
sender.sendChatToPlayer("Usage: /w tag clear <tag>");
} else {
boolean okay = false;
int value = -1;
String tag = null;
if (params.length == 3) {
tag = params[1];
try {
value = Integer.parseInt(params[2]);
okay = true;
} catch (NumberFormatException e) { }
}
if (!okay) {
sender.sendChatToPlayer("Usage: /w tag <tag> <level>");
return;
}
worldDB.setTag(value, tag, x, y, z);
sender.sendChatToPlayer("Set tag " + tag + " to " + value + ".");
}
} else if (params[0].equals("range")) {
if (params.length < 2) {
int range = worldDB.getRange(x, y, z);
sender.sendChatToPlayer("This house flag has range " + range + ".");
} else {
boolean okay = false;
int new_range = -1;
if (params.length == 2) {
try {
new_range = Integer.parseInt(params[1]);
okay = true;
} catch (NumberFormatException e) { }
}
if (!okay) {
sender.sendChatToPlayer("Usage: /w range [value]");
return;
}
worldDB.setRange(new_range, x, y, z);
sender.sendChatToPlayer("Range set to " + new_range + ".");
}
} else {
sender.sendChatToPlayer("Unknown subcommand.");
}
}
|
diff --git a/uMappin/src/mdiss/umappin/fragments/PictureFragment.java b/uMappin/src/mdiss/umappin/fragments/PictureFragment.java
index 617803e..9106f59 100644
--- a/uMappin/src/mdiss/umappin/fragments/PictureFragment.java
+++ b/uMappin/src/mdiss/umappin/fragments/PictureFragment.java
@@ -1,166 +1,165 @@
package mdiss.umappin.fragments;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import org.mapsforge.android.maps.MapView;
import org.mapsforge.android.maps.mapgenerator.tiledownloader.MapnikTileDownloader;
import org.mapsforge.android.maps.overlay.ArrayItemizedOverlay;
import org.mapsforge.android.maps.overlay.OverlayItem;
import org.mapsforge.core.GeoPoint;
import mdiss.umappin.R;
import mdiss.umappin.asynctasks.UploadImageAsyncTask;
import mdiss.umappin.ui.MainActivity;
import mdiss.umappin.utils.Constants;
import mdiss.umappin.utils.GeoMethods;
import mdiss.umappin.utils.ImageUtils;
import android.app.Dialog;
import android.app.Fragment;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class PictureFragment extends Fragment {
private MapView mapView;
private ImageView mImageView;
private FrameLayout mFrameLayout;
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;
private GeoPoint picturePoint;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
getActivity().setTitle("Pictures");
View view = inflater.inflate(R.layout.locate_picture, container, false);
mFrameLayout = (FrameLayout) view.findViewById(R.id.map_container);
mapView = new MapView(getActivity(), new MapnikTileDownloader());
mapView.getController().setZoom(16);
mapView.setBuiltInZoomControls(true);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
picturePoint = GeoMethods.getCurrentLocation(getActivity());
mapView.setCenter(picturePoint);
gestureDetector = new GestureDetector(getActivity(), new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
mapView.setOnTouchListener(gestureListener);
mFrameLayout.addView(mapView);
return view;
}
/**
* Using global variable picturePoint, draws a OverlayItem in map in that
* location
*/
private void putMarkerInMap() {
mapView.getOverlays().clear();
Drawable defaultMarker = getResources().getDrawable(R.drawable.marker);
ArrayItemizedOverlay itemizedOverlay = new ArrayItemizedOverlay(defaultMarker);
OverlayItem item = new OverlayItem(picturePoint, Constants.picturePointName, Constants.picturePointDesc);
itemizedOverlay.addItem(item);
mapView.getOverlays().add(itemizedOverlay);
mapView.setCenter(picturePoint);
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.i(Constants.logMap, "On single tap");
picturePoint = mapView.getProjection().fromPixels((int) e.getX(), (int) e.getY());
putMarkerInMap();
return super.onSingleTapConfirmed(e);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.picture, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MainActivity main = (MainActivity) getActivity();
switch (item.getItemId()) {
case R.id.action_new_photo:
main.cleanBackStack();
main.dispatchTakePictureIntent(MainActivity.ACTION_TAKE_PHOTO_B);
return true;
case R.id.action_upload_photo:
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_photo_upload);
dialog.setTitle(getString(R.string.photo_upload));
Button upload = (Button) dialog.findViewById(R.id.upload);
upload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
- GeoPoint currentPoint = GeoMethods.getCurrentLocation(getActivity());
mImageView = (ImageView) getActivity().findViewById(R.id.current_picture);
String imageBase64 = ImageUtils.getBase64(mImageView);
EditText et = (EditText) dialog.findViewById(R.id.title);
String title = et.getText().toString();
et = (EditText) dialog.findViewById(R.id.description);
String description = et.getText().toString();
Date date = new Date();
JSONObject json = new JSONObject();
try {
json.put("content", "data:image/jpeg;base64;" + imageBase64);
json.put("title",title);
json.put("description",description);
- json.put("latitude",currentPoint.getLatitude());
- json.put("longitude",currentPoint.getLongitude());
+ json.put("latitude",picturePoint.getLatitude());
+ json.put("longitude",picturePoint.getLongitude());
json.put("is_searchable",true);
json.put("date_created",date.getTime());
new UploadImageAsyncTask(getActivity()).execute(json);
} catch (JSONException e) {
e.printStackTrace();
} finally {
dialog.dismiss();
}
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onStop() {
super.onStop();
mapView.getOverlays().clear();
}
@Override
public void onResume() {
super.onResume();
putMarkerInMap();
}
}
| false | true | public boolean onOptionsItemSelected(MenuItem item) {
MainActivity main = (MainActivity) getActivity();
switch (item.getItemId()) {
case R.id.action_new_photo:
main.cleanBackStack();
main.dispatchTakePictureIntent(MainActivity.ACTION_TAKE_PHOTO_B);
return true;
case R.id.action_upload_photo:
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_photo_upload);
dialog.setTitle(getString(R.string.photo_upload));
Button upload = (Button) dialog.findViewById(R.id.upload);
upload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
GeoPoint currentPoint = GeoMethods.getCurrentLocation(getActivity());
mImageView = (ImageView) getActivity().findViewById(R.id.current_picture);
String imageBase64 = ImageUtils.getBase64(mImageView);
EditText et = (EditText) dialog.findViewById(R.id.title);
String title = et.getText().toString();
et = (EditText) dialog.findViewById(R.id.description);
String description = et.getText().toString();
Date date = new Date();
JSONObject json = new JSONObject();
try {
json.put("content", "data:image/jpeg;base64;" + imageBase64);
json.put("title",title);
json.put("description",description);
json.put("latitude",currentPoint.getLatitude());
json.put("longitude",currentPoint.getLongitude());
json.put("is_searchable",true);
json.put("date_created",date.getTime());
new UploadImageAsyncTask(getActivity()).execute(json);
} catch (JSONException e) {
e.printStackTrace();
} finally {
dialog.dismiss();
}
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
| public boolean onOptionsItemSelected(MenuItem item) {
MainActivity main = (MainActivity) getActivity();
switch (item.getItemId()) {
case R.id.action_new_photo:
main.cleanBackStack();
main.dispatchTakePictureIntent(MainActivity.ACTION_TAKE_PHOTO_B);
return true;
case R.id.action_upload_photo:
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_photo_upload);
dialog.setTitle(getString(R.string.photo_upload));
Button upload = (Button) dialog.findViewById(R.id.upload);
upload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mImageView = (ImageView) getActivity().findViewById(R.id.current_picture);
String imageBase64 = ImageUtils.getBase64(mImageView);
EditText et = (EditText) dialog.findViewById(R.id.title);
String title = et.getText().toString();
et = (EditText) dialog.findViewById(R.id.description);
String description = et.getText().toString();
Date date = new Date();
JSONObject json = new JSONObject();
try {
json.put("content", "data:image/jpeg;base64;" + imageBase64);
json.put("title",title);
json.put("description",description);
json.put("latitude",picturePoint.getLatitude());
json.put("longitude",picturePoint.getLongitude());
json.put("is_searchable",true);
json.put("date_created",date.getTime());
new UploadImageAsyncTask(getActivity()).execute(json);
} catch (JSONException e) {
e.printStackTrace();
} finally {
dialog.dismiss();
}
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
|
diff --git a/src/de/bezier/math/combinatorics/CombinationSet.java b/src/de/bezier/math/combinatorics/CombinationSet.java
index 4fb9f10..c7db561 100644
--- a/src/de/bezier/math/combinatorics/CombinationSet.java
+++ b/src/de/bezier/math/combinatorics/CombinationSet.java
@@ -1,71 +1,70 @@
package de.bezier.math.combinatorics;
import java.math.BigInteger;
/**
* A range of Combinations
*
* <p>A CombinationSet represents a range of Combinations, for example:</p>
* <pre>
* CombinationSet cset = new CombinationSet( 3 );
* </pre>
* <p>would represent (and loop thru the results of) these single Combinations:</p>
* <pre>
* {
* new Combination( 3, 0 ), // [], empty
* new Combination( 3, 1 ), // [0], [1], [2]
* new Combination( 3, 2 ), // [0,1], [0,2], [1,2]
* new Combination( 3, 3 ) // [0,1,2]
* }
* </pre>
* <p>If you were just interessted in results of lengths 1 and 2 you could:</p>
* <pre>
* CombinationSet cset = new CombinationSet( 3, 1, 2 ); // 3 elements, starting at lenghts 1, ends at length 2
* </pre>
* <p>which then would only represent these Combinations:</p>
* <pre>
* {
* new Combination( 3, 1 ), // [0], [1], [2]
* new Combination( 3, 2 ), // [0,1], [0,2], [1,2]
* }
* </pre>
*
* @see de.bezier.math.combinatorics.Combination
*/
public class CombinationSet
extends CombinatoricsBaseSet
{
// TODO: implement groups, say CombinationSet( 3, [1,3,5,6] )
// maybe even CombinationSet( 3, CombinationSet.ODD )
public CombinationSet ( int elements ) { super(elements); }
public CombinationSet ( int elements, int from, int to ) { super(elements, from, to); }
public void rewind ()
{
current = BigInteger.ZERO;
totalResults = BigInteger.ZERO;
// calc total results
- Combination c[] = new Combination[to-from+1];
for ( int i = from; i <= to; i++ )
{
- c[i] = new Combination(elements, i);
+ Combination c = new Combination(elements, i);
totalResults =
- totalResults.add( c[i].total() );
+ totalResults.add( c.total() );
}
// first generator
generator = new Combination(elements, from);
current = BigInteger.ZERO;
currentSet = from;
}
// this will jump to / create the next generator (CombinatoricsBase) represented in this group
CombinatoricsBase nextGenerator ()
{
generator = new Combination(elements, currentSet);
return generator;
}
}
| false | true | public void rewind ()
{
current = BigInteger.ZERO;
totalResults = BigInteger.ZERO;
// calc total results
Combination c[] = new Combination[to-from+1];
for ( int i = from; i <= to; i++ )
{
c[i] = new Combination(elements, i);
totalResults =
totalResults.add( c[i].total() );
}
// first generator
generator = new Combination(elements, from);
current = BigInteger.ZERO;
currentSet = from;
}
| public void rewind ()
{
current = BigInteger.ZERO;
totalResults = BigInteger.ZERO;
// calc total results
for ( int i = from; i <= to; i++ )
{
Combination c = new Combination(elements, i);
totalResults =
totalResults.add( c.total() );
}
// first generator
generator = new Combination(elements, from);
current = BigInteger.ZERO;
currentSet = from;
}
|
diff --git a/infra/test/edu/illinois/gitsvn/infra/RepositoryCrawlerTest.java b/infra/test/edu/illinois/gitsvn/infra/RepositoryCrawlerTest.java
index 94fd7d7..33c07e5 100644
--- a/infra/test/edu/illinois/gitsvn/infra/RepositoryCrawlerTest.java
+++ b/infra/test/edu/illinois/gitsvn/infra/RepositoryCrawlerTest.java
@@ -1,32 +1,32 @@
package edu.illinois.gitsvn.infra;
import java.io.File;
import org.eclipse.jgit.api.Git;
import org.gitective.tests.GitTestCase;
import org.junit.Before;
import org.junit.Test;
public class RepositoryCrawlerTest extends GitTestCase{
private RepositoryCrawler crawler;
@Before
public void setUp() throws Exception {
super.setUp();
crawler = new RepositoryCrawler();
}
@Test
public void testProducesCorrectOutput() throws Exception {
add("test.java", "Some java program", "first");
add("test2.java", "Some other java program", "second");
mv("test.java", "test_rename.java");
add("readme","A non-java file", "forth");
crawler.crawlRepo(Git.open(testRepo));
- File file = new File("mumu.txt");
+ File file = new File("mumu.csv");
assertTrue(file.exists());
}
}
| true | true | public void testProducesCorrectOutput() throws Exception {
add("test.java", "Some java program", "first");
add("test2.java", "Some other java program", "second");
mv("test.java", "test_rename.java");
add("readme","A non-java file", "forth");
crawler.crawlRepo(Git.open(testRepo));
File file = new File("mumu.txt");
assertTrue(file.exists());
}
| public void testProducesCorrectOutput() throws Exception {
add("test.java", "Some java program", "first");
add("test2.java", "Some other java program", "second");
mv("test.java", "test_rename.java");
add("readme","A non-java file", "forth");
crawler.crawlRepo(Git.open(testRepo));
File file = new File("mumu.csv");
assertTrue(file.exists());
}
|
diff --git a/src/java/main/org/jaxen/function/xslt/DocumentFunction.java b/src/java/main/org/jaxen/function/xslt/DocumentFunction.java
index f81b517..69b6055 100644
--- a/src/java/main/org/jaxen/function/xslt/DocumentFunction.java
+++ b/src/java/main/org/jaxen/function/xslt/DocumentFunction.java
@@ -1,103 +1,103 @@
/*
* $Header$
* $Revision$
* $Date$
*
* ====================================================================
*
* Copyright (C) 2000-2002 bob mcwhirter & James Strachan.
* 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 disclaimer that follows
* these conditions in the documentation and/or other materials
* provided with the distribution.
*
* 3. The name "Jaxen" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 4. Products derived from this software may not be called "Jaxen", nor
* may "Jaxen" appear in their name, without prior written permission
* from the Jaxen Project Management ([email protected]).
*
* In addition, we request (but do not require) that you include in the
* end-user documentation provided with the redistribution and/or in the
* software itself an acknowledgement equivalent to the following:
* "This product includes software developed by the
* Jaxen Project (http://www.jaxen.org/)."
* Alternatively, the acknowledgment may be graphical using the logos
* available at http://www.jaxen.org/
*
* 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 Jaxen AUTHORS OR THE PROJECT
* 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 Jaxen Project and was originally
* created by bob mcwhirter <[email protected]> and
* James Strachan <[email protected]>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id$
*/
package org.jaxen.function.xslt;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.Navigator;
import org.jaxen.FunctionCallException;
import org.jaxen.function.StringFunction;
import java.util.List;
/**
* Implements the XSLT document() function
*
* @author <a href="mailto:[email protected]">James Strachan</a>
*/
public class DocumentFunction implements Function
{
public Object call(Context context,
List args) throws FunctionCallException
{
if (args.size() == 1)
{
Navigator nav = context.getNavigator();
String url = StringFunction.evaluate( args.get( 0 ),
nav );
return evaluate( url,
nav );
}
- throw new FunctionCallException( "false() requires no arguments." );
+ throw new FunctionCallException( "document() requires one argument." );
}
public static Object evaluate(String url,
Navigator nav) throws FunctionCallException
{
return nav.getDocument( url );
}
}
| true | true | public Object call(Context context,
List args) throws FunctionCallException
{
if (args.size() == 1)
{
Navigator nav = context.getNavigator();
String url = StringFunction.evaluate( args.get( 0 ),
nav );
return evaluate( url,
nav );
}
throw new FunctionCallException( "false() requires no arguments." );
}
| public Object call(Context context,
List args) throws FunctionCallException
{
if (args.size() == 1)
{
Navigator nav = context.getNavigator();
String url = StringFunction.evaluate( args.get( 0 ),
nav );
return evaluate( url,
nav );
}
throw new FunctionCallException( "document() requires one argument." );
}
|
diff --git a/src/org/biojava/bio/seq/db/TabIndexStore.java b/src/org/biojava/bio/seq/db/TabIndexStore.java
index 933c91246..acbe6c26e 100644
--- a/src/org/biojava/bio/seq/db/TabIndexStore.java
+++ b/src/org/biojava/bio/seq/db/TabIndexStore.java
@@ -1,248 +1,248 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq.db;
import java.io.*;
import java.util.*;
import org.biojava.utils.*;
import org.biojava.bio.*;
import org.biojava.bio.seq.*;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.symbol.*;
/**
* Implements IndexStore as a serialized file for the java data and a
* tab-delimited file of offets.
* <P>
* The tab-delimited file looks like:
* <pre>
* fileNumber \t offset \t id \n
* </pre>
*/
public class TabIndexStore implements IndexStore, Serializable {
public static TabIndexStore open(File storeFile)
throws IOException {
try {
FileInputStream fis = new FileInputStream(storeFile);
ObjectInputStream p = new ObjectInputStream(fis);
TabIndexStore indxStore = (TabIndexStore) p.readObject();
fis.close();
return indxStore;
} catch (ClassNotFoundException cnfe) {
throw new NestedError(cnfe, "Assertion Failure: How did we get here?");
}
}
// internal book-keeping for indices
private transient Map idToIndex;
private transient Map commited;
private transient Map uncommited;
// the two files for storing the store info and the actual table of indices
private final File storeFile;
private final File indexFile;
private final String name;
private final Set files;
private File[] seqFileIndex;
private final SequenceFormat format;
private final SequenceBuilderFactory sbFactory;
private final SymbolTokenization symbolParser;
public TabIndexStore(
File storeFile,
File indexFile,
String name,
SequenceFormat format,
SequenceBuilderFactory sbFactory,
SymbolTokenization symbolParser
) throws IOException, BioException {
if(storeFile.exists() || indexFile.exists()) {
throw new BioException("Files already exist");
}
- this.storeFile = storeFile;
- this.indexFile = indexFile;
+ this.storeFile = storeFile.getAbsoluteFile();
+ this.indexFile = indexFile.getAbsoluteFile();
this.name = name;
this.format = format;
this.sbFactory = sbFactory;
this.symbolParser = symbolParser;
this.files = new HashSet();
this.seqFileIndex = new File[0];
this.commited = new HashMap();
this.uncommited = new HashMap();
this.idToIndex = new OverlayMap(commited, uncommited);
commit();
}
public void store(Index indx) throws IllegalIDException, BioException {
if(idToIndex.containsKey(indx.getID())) {
throw new IllegalIDException("ID already in use: '" + indx.getID() + "'");
}
addFile(indx.getFile());
uncommited.put(indx.getID(), indx);
}
public Index fetch(String id) throws IllegalIDException, BioException {
Index indx = (Index) idToIndex.get(id);
if(indx == null) {
throw new IllegalIDException("No Index known for id '" + id + "'");
}
return indx;
}
public void commit() throws BioException {
try {
PrintWriter out = new PrintWriter(
new FileWriter(
indexFile.toString(), true
)
);
for(Iterator i = uncommited.values().iterator(); i.hasNext(); ) {
Index indx = (Index) i.next();
out.println(
getFileIndex(indx.getFile()) + "\t" +
indx.getStart() + "\t" +
indx.getID()
);
}
commitStore();
out.close();
commited.putAll(uncommited);
uncommited.clear();
} catch (IOException ioe) {
throw new BioException(ioe, "Failed to commit");
}
}
public void rollback() {
uncommited.clear();
}
public String getName() {
return name;
}
public Set getIDs() {
return Collections.unmodifiableSet(idToIndex.keySet());
}
public Set getFiles() {
return Collections.unmodifiableSet(files);
}
public SequenceFormat getFormat() {
return format;
}
public SequenceBuilderFactory getSBFactory() {
return sbFactory;
}
public SymbolTokenization getSymbolParser() {
return symbolParser;
}
protected void commitStore() throws IOException {
FileOutputStream fos = new FileOutputStream(storeFile);
ObjectOutputStream p = new ObjectOutputStream(fos);
p.writeObject(this);
p.flush();
fos.close();
}
protected void addFile(File f) {
if(!files.contains(f)) {
int len = seqFileIndex.length;
files.add(f);
File[] sfi = new File[len + 1];
System.arraycopy(this.seqFileIndex, 0, sfi, 0, len);
sfi[len] = f;
this.seqFileIndex = sfi;
}
}
protected int getFileIndex(File file) {
for(int pos = seqFileIndex.length-1; pos >= 0; pos--) {
File f = seqFileIndex[pos];
// don't know if this construct is faster than a plain equals()
if(f == file || file.equals(f)) {
return pos;
}
}
throw new IndexOutOfBoundsException("Index not found for File '" + file + "'");
}
protected void initialize() throws IOException {
if(indexFile.exists()) {
// load in stuff from the files
BufferedReader reader = new BufferedReader(
new FileReader(indexFile )
);
for(
String line = reader.readLine();
line != null;
line = reader.readLine()
) {
StringTokenizer stok = new StringTokenizer(line);
int fileNum = Integer.parseInt(stok.nextToken());
long start = Long.parseLong(stok.nextToken());
String id = stok.nextToken();
SimpleIndex index = new SimpleIndex(
seqFileIndex[fileNum],
start,
id
);
commited.put(id, index);
}
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.commited = new HashMap();
this.uncommited = new HashMap();
this.idToIndex = new OverlayMap(commited, uncommited);
this.initialize();
}
}
| true | true | public TabIndexStore(
File storeFile,
File indexFile,
String name,
SequenceFormat format,
SequenceBuilderFactory sbFactory,
SymbolTokenization symbolParser
) throws IOException, BioException {
if(storeFile.exists() || indexFile.exists()) {
throw new BioException("Files already exist");
}
this.storeFile = storeFile;
this.indexFile = indexFile;
this.name = name;
this.format = format;
this.sbFactory = sbFactory;
this.symbolParser = symbolParser;
this.files = new HashSet();
this.seqFileIndex = new File[0];
this.commited = new HashMap();
this.uncommited = new HashMap();
this.idToIndex = new OverlayMap(commited, uncommited);
commit();
}
| public TabIndexStore(
File storeFile,
File indexFile,
String name,
SequenceFormat format,
SequenceBuilderFactory sbFactory,
SymbolTokenization symbolParser
) throws IOException, BioException {
if(storeFile.exists() || indexFile.exists()) {
throw new BioException("Files already exist");
}
this.storeFile = storeFile.getAbsoluteFile();
this.indexFile = indexFile.getAbsoluteFile();
this.name = name;
this.format = format;
this.sbFactory = sbFactory;
this.symbolParser = symbolParser;
this.files = new HashSet();
this.seqFileIndex = new File[0];
this.commited = new HashMap();
this.uncommited = new HashMap();
this.idToIndex = new OverlayMap(commited, uncommited);
commit();
}
|
diff --git a/src/java/com/eviware/soapui/security/scan/MalformedXmlSecurityScan.java b/src/java/com/eviware/soapui/security/scan/MalformedXmlSecurityScan.java
index 3a9221b76..a7a8dd898 100644
--- a/src/java/com/eviware/soapui/security/scan/MalformedXmlSecurityScan.java
+++ b/src/java/com/eviware/soapui/security/scan/MalformedXmlSecurityScan.java
@@ -1,561 +1,564 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.security.scan;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JComponent;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.config.MalformedXmlAttributeConfig;
import com.eviware.soapui.config.MalformedXmlConfig;
import com.eviware.soapui.config.SecurityScanConfig;
import com.eviware.soapui.config.StrategyTypeConfig;
import com.eviware.soapui.model.ModelItem;
import com.eviware.soapui.model.iface.MessageExchange;
import com.eviware.soapui.model.security.SecurityCheckedParameter;
import com.eviware.soapui.model.testsuite.TestCaseRunner;
import com.eviware.soapui.model.testsuite.TestProperty;
import com.eviware.soapui.model.testsuite.TestStep;
import com.eviware.soapui.security.SecurityTestRunContext;
import com.eviware.soapui.security.SecurityTestRunner;
import com.eviware.soapui.security.ui.MalformedXmlAdvancedSettingsPanel;
import com.eviware.soapui.support.types.StringToStringMap;
import com.eviware.soapui.support.xml.XmlObjectTreeModel;
import com.eviware.soapui.support.xml.XmlObjectTreeModel.AttributeXmlTreeNode;
import com.eviware.soapui.support.xml.XmlObjectTreeModel.XmlTreeNode;
import com.eviware.soapui.support.xml.XmlUtils;
public class MalformedXmlSecurityScan extends AbstractSecurityScanWithProperties
{
public static final String TYPE = "MalformedXmlSecurityScan";
public static final String NAME = "Malformed XML";
private Map<SecurityCheckedParameter, ArrayList<String>> parameterMutations = new HashMap<SecurityCheckedParameter, ArrayList<String>>();
private boolean mutation;
private MalformedXmlConfig malformedXmlConfig;
private MalformedXmlAttributeConfig malformedAttributeConfig;
private MalformedXmlAdvancedSettingsPanel advancedSettingsPanel;
public MalformedXmlSecurityScan( TestStep testStep, SecurityScanConfig config, ModelItem parent, String icon )
{
super( testStep, config, parent, icon );
if( config.getConfig() == null || !( config.getConfig() instanceof MalformedXmlConfig ) )
initMalformedXmlConfig();
else
{
malformedXmlConfig = ( ( MalformedXmlConfig )config.getConfig() );
malformedAttributeConfig = malformedXmlConfig.getAttributeMutation();
}
}
/**
* Default malformed xml configuration
*/
protected void initMalformedXmlConfig()
{
getConfig().setConfig( MalformedXmlConfig.Factory.newInstance() );
malformedXmlConfig = ( MalformedXmlConfig )getConfig().getConfig();
malformedXmlConfig.addNewAttributeMutation();
// init default configuration
malformedXmlConfig.setInsertNewElement( true );
malformedXmlConfig.setNewElementValue( "<xml>xml <joke> </xml> </joke>" );
malformedXmlConfig.setChangeTagName( true );
malformedXmlConfig.setLeaveTagOpen( true );
malformedXmlConfig.setInsertInvalidCharacter( true );
malformedAttributeConfig = malformedXmlConfig.getAttributeMutation();
malformedAttributeConfig.setMutateAttributes( true );
malformedAttributeConfig.setInsertInvalidChars( true );
malformedAttributeConfig.setLeaveAttributeOpen( true );
malformedAttributeConfig.setAddNewAttribute( true );
malformedAttributeConfig.setNewAttributeName( "newAttribute" );
malformedAttributeConfig.setNewAttributeValue( "XXX" );
}
@Override
protected void execute( SecurityTestRunner runner, TestStep testStep, SecurityTestRunContext context )
{
try
{
StringToStringMap paramsUpdated = update( testStep, context );
MessageExchange message = ( MessageExchange )testStep.run( ( TestCaseRunner )runner, context );
createMessageExchange( paramsUpdated, message, context );
}
catch( XmlException e )
{
SoapUI.logError( e, "[MalformedXmlSecurityScan]XPath seems to be invalid!" );
reportSecurityScanException( "Property value is not XML or XPath is wrong!" );
}
catch( Exception e )
{
SoapUI.logError( e, "[MalformedXmlSecurityScan]Property value is not valid xml!" );
reportSecurityScanException( "Property value is not XML or XPath is wrong!" );
}
}
protected StringToStringMap update( TestStep testStep, SecurityTestRunContext context ) throws XmlException,
Exception
{
StringToStringMap params = new StringToStringMap();
if( parameterMutations.size() == 0 )
mutateParameters( testStep, context );
if( getExecutionStrategy().getStrategy() == StrategyTypeConfig.ONE_BY_ONE )
{
/*
* Idea is to drain for each parameter mutations.
*/
for( SecurityCheckedParameter param : getParameterHolder().getParameterList() )
{
if( parameterMutations.containsKey( param ) )
if( parameterMutations.get( param ).size() > 0 )
{
TestProperty property = testStep.getProperties().get( param.getName() );
String value = context.expand( property.getValue() );
if( param.getXpath() == null || param.getXpath().trim().length() == 0 )
{
// no xpath ignore
}
else
{
// no value, do nothing.
if( value == null || value.trim().equals( "" ) )
continue;
// XmlObjectTreeModel model = new XmlObjectTreeModel(
// property.getSchemaType().getTypeSystem(),
// XmlObject.Factory.parse( value ) );
XmlObjectTreeModel model = new XmlObjectTreeModel( property.getSchemaType().getTypeSystem(),
XmlUtils.createXmlObject( value ) );
XmlTreeNode[] nodes = model.selectTreeNodes( context.expand( param.getXpath() ) );
StringBuffer buffer = new StringBuffer( value );
for( int cnt = 0; cnt < nodes.length; cnt++ )
{
// find right node
// this finds where node that needs updateing begins
int start = value.indexOf( "<" + nodes[cnt].getNodeName() ); // keeps
// node
// start
int cnt2 = 0;
// if have more than one node that matches xpath, find
// next one.
while( cnt2 < cnt )
{
start = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
cnt2++ ;
}
// get node xml
String nodeXml = getXmlForNode( nodes[cnt] );
// find end of target xml node
int end = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
if( end <= 0 )
{
if( nodeXml.endsWith( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ) )
{
end = value.indexOf( "</" + nodes[cnt].getDomNode().getNodeName() + ">" )
+ ( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ).length();
}
else
{
end = value.indexOf( ">", value.indexOf( "/", start ) );
}
}
if( end <= 0 || end <= start )
break;
// replace node with right value
buffer.replace( start, end + 1, parameterMutations.get( param ).get( 0 ) );
}
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
testStep.getProperties().get( param.getName() ).setValue( buffer.toString() );
}
break;
}
}
}
else
{
for( TestProperty property : testStep.getPropertyList() )
{
String value = context.expand( property.getValue() );
if( XmlUtils.seemsToBeXml( value ) )
{
StringBuffer buffer = new StringBuffer( value );
XmlObjectTreeModel model = null;
// model = new XmlObjectTreeModel(
// property.getSchemaType().getTypeSystem(),
// XmlObject.Factory.parse( value ) );
model = new XmlObjectTreeModel( property.getSchemaType().getTypeSystem(),
XmlUtils.createXmlObject( value ) );
for( SecurityCheckedParameter param : getParameterHolder().getParameterList() )
{
if( param.getXpath() == null || param.getXpath().trim().length() == 0 )
{
- testStep.getProperties().get( param.getName() )
- .setValue( parameterMutations.get( param ).get( 0 ) );
- params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
- parameterMutations.get( param ).remove( 0 );
+ if( parameterMutations.containsKey( param ) )
+ {
+ testStep.getProperties().get( param.getName() )
+ .setValue( parameterMutations.get( param ).get( 0 ) );
+ params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
+ parameterMutations.get( param ).remove( 0 );
+ }
}
else
{
// no value, do nothing.
if( value == null || value.trim().equals( "" ) )
continue;
if( param.getName().equals( property.getName() ) )
{
XmlTreeNode[] nodes = model.selectTreeNodes( context.expand( param.getXpath() ) );
if( parameterMutations.containsKey( param ) )
if( parameterMutations.get( param ).size() > 0 )
{
for( int cnt = 0; cnt < nodes.length; cnt++ )
{
// find right node
// keeps node start
int start = value.indexOf( "<" + nodes[cnt].getNodeName() );
int cnt2 = 0;
while( cnt2 < cnt )
{
start = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
cnt2++ ;
}
String nodeXml = getXmlForNode( nodes[cnt] );
int end = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
if( end <= 0 )
{
if( nodeXml.endsWith( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ) )
{
end = value.indexOf( "</" + nodes[cnt].getDomNode().getNodeName() + ">" );
}
else
{
end = value.indexOf( ">", value.indexOf( "/", start ) );
}
}
if( end <= 0 || end <= start )
break;
buffer.replace( start, end + 1, parameterMutations.get( param ).get( 0 ) );
}
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
}
}
}
}
if( model != null )
property.setValue( buffer.toString() );
}
}
}
return params;
}
protected void mutateParameters( TestStep testStep, SecurityTestRunContext context ) throws XmlException,
IOException
{
mutation = true;
// for each parameter
for( SecurityCheckedParameter parameter : getParameterHolder().getParameterList() )
{
if( parameter.isChecked() )
{
TestProperty property = getTestStep().getProperties().get( parameter.getName() );
// check parameter does not have any xpath
if( parameter.getXpath() == null || parameter.getXpath().trim().length() == 0 )
{
/*
* parameter xpath is not set ignore than ignore this parameter
*/
}
else
{
// we have xpath but do we have xml which need to mutate
// ignore if there is no value, since than we'll get exception
if( !( property.getValue() == null && property.getDefaultValue() == null ) )
{
// get value of that property
String value = context.expand( property.getValue() );
// we have something that looks like xpath, or hope so.
// XmlObjectTreeModel model = new XmlObjectTreeModel(
// property.getSchemaType().getTypeSystem(),
// XmlObject.Factory.parse( value ) );
XmlObjectTreeModel model = new XmlObjectTreeModel( property.getSchemaType().getTypeSystem(),
XmlUtils.createXmlObject( value ) );
XmlTreeNode[] nodes = model.selectTreeNodes( context.expand( parameter.getXpath() ) );
if( nodes.length > 0 && !( nodes[0] instanceof AttributeXmlTreeNode ) )
{
if( !parameterMutations.containsKey( parameter ) )
parameterMutations.put( parameter, new ArrayList<String>() );
parameterMutations.get( parameter ).addAll( mutateNode( nodes[0], value ) );
}
}
}
}
}
}
protected Collection<? extends String> mutateNode( XmlTreeNode node, String xml ) throws IOException
{
ArrayList<String> result = new ArrayList<String>();
String nodeXml = getXmlForNode( node );
// insert new element
if( malformedXmlConfig.getInsertNewElement() )
{
StringBuffer buffer = new StringBuffer( nodeXml );
if( nodeXml.endsWith( "</" + node.getDomNode().getNodeName() + ">" ) )
{
buffer.insert( nodeXml.indexOf( ">" ) + 1, malformedXmlConfig.getNewElementValue() );
}
else
{
buffer.delete( nodeXml.lastIndexOf( "/" ), nodeXml.length() );
buffer.append( ">" + malformedXmlConfig.getNewElementValue() + "</" + node.getDomNode().getNodeName() + ">" );
}
result.add( buffer.toString() );
}
// change name
if( malformedXmlConfig.getChangeTagName() )
{
String original = node.getNodeName();
if( original.toUpperCase().equals( original ) )
{
result.add( nodeXml.replaceAll( original, original.toLowerCase() ) );
}
else if( original.toLowerCase().equals( original ) )
{
result.add( nodeXml.replaceAll( original, original.toUpperCase() ) );
}
else
{
StringBuffer buffer = new StringBuffer();
// kewl
for( char ch : original.toCharArray() )
{
if( Character.isUpperCase( ch ) )
buffer.append( Character.toLowerCase( ch ) );
else
buffer.append( Character.toUpperCase( ch ) );
}
result.add( nodeXml.replaceAll( original, buffer.toString() ) );
// add '_' before upper case and make uppercase lowercase
// just start tag change
buffer = new StringBuffer();
for( char ch : original.toCharArray() )
{
if( Character.isUpperCase( ch ) )
buffer.append( "_" ).append( Character.toLowerCase( ch ) );
else
buffer.append( ch );
}
result.add( nodeXml.replaceAll( original, buffer.toString() ) );
}
}
// leave tag open
if( malformedXmlConfig.getLeaveTagOpen() )
{
if( nodeXml.endsWith( "</" + node.getDomNode().getNodeName() + ">" ) )
{
// cut end tag
StringBuffer buffer = new StringBuffer( nodeXml );
buffer.delete( buffer.indexOf( "</" + node.getDomNode().getNodeName() + ">" ), buffer.length() );
result.add( buffer.toString() );
// cut start tag
buffer = new StringBuffer( nodeXml );
buffer.delete( 0, buffer.indexOf( ">" ) + 1 );
result.add( buffer.toString() );
// cut start tag and remove '/' from end tag
buffer = new StringBuffer( nodeXml );
buffer.delete( 0, buffer.indexOf( ">" ) + 1 );
buffer.delete( buffer.indexOf( "</" + node.getDomNode().getNodeName() + ">" ) + 1,
buffer.indexOf( "</" + node.getDomNode().getNodeName() + ">" ) + 2 );
result.add( buffer.toString() );
}
else
{
// remove '/>' from end of tag
StringBuffer buffer = new StringBuffer( nodeXml );
buffer.delete( nodeXml.lastIndexOf( "/" ), nodeXml.length() );
result.add( buffer.toString() );
}
}
if( malformedXmlConfig.getInsertInvalidCharacter() )
{
for( char ch : new char[] { '<', '>', '&' } )
{
StringBuffer buffer = new StringBuffer( nodeXml );
if( nodeXml.endsWith( "</" + node.getDomNode().getNodeName() + ">" ) )
{
buffer.insert( buffer.indexOf( "</" + node.getDomNode().getNodeName() + ">" ), ch );
}
else
{
buffer.delete( nodeXml.lastIndexOf( "/" ), nodeXml.length() );
buffer.append( '>' ).append( ch ).append( "</" ).append( node.getDomNode().getNodeName() ).append( ">" );
}
result.add( buffer.toString() );
}
}
// mutate attributes
if( malformedAttributeConfig.getMutateAttributes() )
{
if( malformedAttributeConfig.getAddNewAttribute() )
{
if( malformedAttributeConfig.getNewAttributeName().trim().length() > 0 )
{
// insert new attribute just after node tag
StringBuffer buffer = new StringBuffer( nodeXml );
buffer.insert( node.getNodeName().length() + 1, " " + malformedAttributeConfig.getNewAttributeName()
+ "=" + "\"" + malformedAttributeConfig.getNewAttributeValue() + "\" " );
result.add( buffer.toString() );
}
}
if( malformedAttributeConfig.getInsertInvalidChars() )
{
if( node.getDomNode().hasAttributes() )
{
for( char ch : new char[] { '"', '\'', '<', '>', '&' } )
{
// add it at beggining of attribute value
StringBuffer buffer = new StringBuffer( nodeXml );
buffer.insert( buffer.indexOf( "=" ) + 3, ch );
result.add( buffer.toString() );
}
}
}
if( malformedAttributeConfig.getLeaveAttributeOpen() )
{
if( node.getDomNode().hasAttributes() )
{
StringBuffer buffer = new StringBuffer( nodeXml );
buffer.delete( buffer.indexOf( "=" ) + 1, buffer.indexOf( "=" ) + 2 );
result.add( buffer.toString() );
}
}
}
return result;
}
private String getXmlForNode( XmlTreeNode nodes )
{
XmlOptions options = new XmlOptions();
options.setSaveOuter();
options.setSavePrettyPrint();
String xml = nodes.getXmlObject().xmlText( options );
return XmlUtils.removeUnneccessaryNamespaces( xml );
}
@Override
public String getConfigDescription()
{
return "Configures Malformed XML Security Scan";
}
@Override
public String getConfigName()
{
return "Malformed XML Security Scan";
}
@Override
public String getHelpURL()
{
return "http://soapui.org/Security/malformed-xml.html";
}
@Override
public String getType()
{
return TYPE;
}
@Override
protected boolean hasNext( TestStep testStep, SecurityTestRunContext context )
{
boolean hasNext = false;
if( ( parameterMutations == null || parameterMutations.size() == 0 ) && !mutation )
{
if( getParameterHolder().getParameterList().size() > 0 )
hasNext = true;
else
hasNext = false;
}
else
{
for( SecurityCheckedParameter param : parameterMutations.keySet() )
{
if( parameterMutations.get( param ).size() > 0 )
{
hasNext = true;
break;
}
}
}
if( !hasNext )
{
parameterMutations.clear();
mutation = false;
}
return hasNext;
}
@Override
protected void clear()
{
parameterMutations.clear();
mutation = false;
}
@Override
public JComponent getAdvancedSettingsPanel()
{
if( advancedSettingsPanel == null )
advancedSettingsPanel = new MalformedXmlAdvancedSettingsPanel( malformedXmlConfig );
return advancedSettingsPanel.getPanel();
}
@Override
public void release()
{
if( advancedSettingsPanel != null )
advancedSettingsPanel.release();
super.release();
}
}
| true | true | protected StringToStringMap update( TestStep testStep, SecurityTestRunContext context ) throws XmlException,
Exception
{
StringToStringMap params = new StringToStringMap();
if( parameterMutations.size() == 0 )
mutateParameters( testStep, context );
if( getExecutionStrategy().getStrategy() == StrategyTypeConfig.ONE_BY_ONE )
{
/*
* Idea is to drain for each parameter mutations.
*/
for( SecurityCheckedParameter param : getParameterHolder().getParameterList() )
{
if( parameterMutations.containsKey( param ) )
if( parameterMutations.get( param ).size() > 0 )
{
TestProperty property = testStep.getProperties().get( param.getName() );
String value = context.expand( property.getValue() );
if( param.getXpath() == null || param.getXpath().trim().length() == 0 )
{
// no xpath ignore
}
else
{
// no value, do nothing.
if( value == null || value.trim().equals( "" ) )
continue;
// XmlObjectTreeModel model = new XmlObjectTreeModel(
// property.getSchemaType().getTypeSystem(),
// XmlObject.Factory.parse( value ) );
XmlObjectTreeModel model = new XmlObjectTreeModel( property.getSchemaType().getTypeSystem(),
XmlUtils.createXmlObject( value ) );
XmlTreeNode[] nodes = model.selectTreeNodes( context.expand( param.getXpath() ) );
StringBuffer buffer = new StringBuffer( value );
for( int cnt = 0; cnt < nodes.length; cnt++ )
{
// find right node
// this finds where node that needs updateing begins
int start = value.indexOf( "<" + nodes[cnt].getNodeName() ); // keeps
// node
// start
int cnt2 = 0;
// if have more than one node that matches xpath, find
// next one.
while( cnt2 < cnt )
{
start = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
cnt2++ ;
}
// get node xml
String nodeXml = getXmlForNode( nodes[cnt] );
// find end of target xml node
int end = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
if( end <= 0 )
{
if( nodeXml.endsWith( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ) )
{
end = value.indexOf( "</" + nodes[cnt].getDomNode().getNodeName() + ">" )
+ ( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ).length();
}
else
{
end = value.indexOf( ">", value.indexOf( "/", start ) );
}
}
if( end <= 0 || end <= start )
break;
// replace node with right value
buffer.replace( start, end + 1, parameterMutations.get( param ).get( 0 ) );
}
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
testStep.getProperties().get( param.getName() ).setValue( buffer.toString() );
}
break;
}
}
}
else
{
for( TestProperty property : testStep.getPropertyList() )
{
String value = context.expand( property.getValue() );
if( XmlUtils.seemsToBeXml( value ) )
{
StringBuffer buffer = new StringBuffer( value );
XmlObjectTreeModel model = null;
// model = new XmlObjectTreeModel(
// property.getSchemaType().getTypeSystem(),
// XmlObject.Factory.parse( value ) );
model = new XmlObjectTreeModel( property.getSchemaType().getTypeSystem(),
XmlUtils.createXmlObject( value ) );
for( SecurityCheckedParameter param : getParameterHolder().getParameterList() )
{
if( param.getXpath() == null || param.getXpath().trim().length() == 0 )
{
testStep.getProperties().get( param.getName() )
.setValue( parameterMutations.get( param ).get( 0 ) );
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
}
else
{
// no value, do nothing.
if( value == null || value.trim().equals( "" ) )
continue;
if( param.getName().equals( property.getName() ) )
{
XmlTreeNode[] nodes = model.selectTreeNodes( context.expand( param.getXpath() ) );
if( parameterMutations.containsKey( param ) )
if( parameterMutations.get( param ).size() > 0 )
{
for( int cnt = 0; cnt < nodes.length; cnt++ )
{
// find right node
// keeps node start
int start = value.indexOf( "<" + nodes[cnt].getNodeName() );
int cnt2 = 0;
while( cnt2 < cnt )
{
start = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
cnt2++ ;
}
String nodeXml = getXmlForNode( nodes[cnt] );
int end = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
if( end <= 0 )
{
if( nodeXml.endsWith( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ) )
{
end = value.indexOf( "</" + nodes[cnt].getDomNode().getNodeName() + ">" );
}
else
{
end = value.indexOf( ">", value.indexOf( "/", start ) );
}
}
if( end <= 0 || end <= start )
break;
buffer.replace( start, end + 1, parameterMutations.get( param ).get( 0 ) );
}
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
}
}
}
}
if( model != null )
property.setValue( buffer.toString() );
}
}
}
return params;
}
| protected StringToStringMap update( TestStep testStep, SecurityTestRunContext context ) throws XmlException,
Exception
{
StringToStringMap params = new StringToStringMap();
if( parameterMutations.size() == 0 )
mutateParameters( testStep, context );
if( getExecutionStrategy().getStrategy() == StrategyTypeConfig.ONE_BY_ONE )
{
/*
* Idea is to drain for each parameter mutations.
*/
for( SecurityCheckedParameter param : getParameterHolder().getParameterList() )
{
if( parameterMutations.containsKey( param ) )
if( parameterMutations.get( param ).size() > 0 )
{
TestProperty property = testStep.getProperties().get( param.getName() );
String value = context.expand( property.getValue() );
if( param.getXpath() == null || param.getXpath().trim().length() == 0 )
{
// no xpath ignore
}
else
{
// no value, do nothing.
if( value == null || value.trim().equals( "" ) )
continue;
// XmlObjectTreeModel model = new XmlObjectTreeModel(
// property.getSchemaType().getTypeSystem(),
// XmlObject.Factory.parse( value ) );
XmlObjectTreeModel model = new XmlObjectTreeModel( property.getSchemaType().getTypeSystem(),
XmlUtils.createXmlObject( value ) );
XmlTreeNode[] nodes = model.selectTreeNodes( context.expand( param.getXpath() ) );
StringBuffer buffer = new StringBuffer( value );
for( int cnt = 0; cnt < nodes.length; cnt++ )
{
// find right node
// this finds where node that needs updateing begins
int start = value.indexOf( "<" + nodes[cnt].getNodeName() ); // keeps
// node
// start
int cnt2 = 0;
// if have more than one node that matches xpath, find
// next one.
while( cnt2 < cnt )
{
start = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
cnt2++ ;
}
// get node xml
String nodeXml = getXmlForNode( nodes[cnt] );
// find end of target xml node
int end = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
if( end <= 0 )
{
if( nodeXml.endsWith( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ) )
{
end = value.indexOf( "</" + nodes[cnt].getDomNode().getNodeName() + ">" )
+ ( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ).length();
}
else
{
end = value.indexOf( ">", value.indexOf( "/", start ) );
}
}
if( end <= 0 || end <= start )
break;
// replace node with right value
buffer.replace( start, end + 1, parameterMutations.get( param ).get( 0 ) );
}
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
testStep.getProperties().get( param.getName() ).setValue( buffer.toString() );
}
break;
}
}
}
else
{
for( TestProperty property : testStep.getPropertyList() )
{
String value = context.expand( property.getValue() );
if( XmlUtils.seemsToBeXml( value ) )
{
StringBuffer buffer = new StringBuffer( value );
XmlObjectTreeModel model = null;
// model = new XmlObjectTreeModel(
// property.getSchemaType().getTypeSystem(),
// XmlObject.Factory.parse( value ) );
model = new XmlObjectTreeModel( property.getSchemaType().getTypeSystem(),
XmlUtils.createXmlObject( value ) );
for( SecurityCheckedParameter param : getParameterHolder().getParameterList() )
{
if( param.getXpath() == null || param.getXpath().trim().length() == 0 )
{
if( parameterMutations.containsKey( param ) )
{
testStep.getProperties().get( param.getName() )
.setValue( parameterMutations.get( param ).get( 0 ) );
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
}
}
else
{
// no value, do nothing.
if( value == null || value.trim().equals( "" ) )
continue;
if( param.getName().equals( property.getName() ) )
{
XmlTreeNode[] nodes = model.selectTreeNodes( context.expand( param.getXpath() ) );
if( parameterMutations.containsKey( param ) )
if( parameterMutations.get( param ).size() > 0 )
{
for( int cnt = 0; cnt < nodes.length; cnt++ )
{
// find right node
// keeps node start
int start = value.indexOf( "<" + nodes[cnt].getNodeName() );
int cnt2 = 0;
while( cnt2 < cnt )
{
start = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
cnt2++ ;
}
String nodeXml = getXmlForNode( nodes[cnt] );
int end = value.indexOf( "<" + nodes[cnt].getNodeName(), start + 1 );
if( end <= 0 )
{
if( nodeXml.endsWith( "</" + nodes[cnt].getDomNode().getNodeName() + ">" ) )
{
end = value.indexOf( "</" + nodes[cnt].getDomNode().getNodeName() + ">" );
}
else
{
end = value.indexOf( ">", value.indexOf( "/", start ) );
}
}
if( end <= 0 || end <= start )
break;
buffer.replace( start, end + 1, parameterMutations.get( param ).get( 0 ) );
}
params.put( param.getLabel(), parameterMutations.get( param ).get( 0 ) );
parameterMutations.get( param ).remove( 0 );
}
}
}
}
if( model != null )
property.setValue( buffer.toString() );
}
}
}
return params;
}
|
diff --git a/src/main/java/h2db/GuestBook.java b/src/main/java/h2db/GuestBook.java
index 87b18fa..907a124 100644
--- a/src/main/java/h2db/GuestBook.java
+++ b/src/main/java/h2db/GuestBook.java
@@ -1,31 +1,31 @@
package h2db;
import java.sql.SQLException;
import java.util.Scanner;
/**
* Hello world!
*/
public class GuestBook {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
GuestBookControllerImpl guestBookController;
guestBookController = new GuestBookControllerImpl("guestbook", "SYSDBA", "MASTERKEY");
for (Record rec : guestBookController.getRecords()) {
rec.print();
}
- System.out.println("Enter your message with DONE at end");
+ System.out.println("Enter your message:");
Scanner mScanner = new Scanner(System.in);
String record = "";
try {
record += mScanner.nextLine();
} catch (Exception e) {
e.printStackTrace();
}
guestBookController.addRecord(record);
guestBookController.close();
}
}
| true | true | public static void main(String[] args) throws SQLException, ClassNotFoundException {
GuestBookControllerImpl guestBookController;
guestBookController = new GuestBookControllerImpl("guestbook", "SYSDBA", "MASTERKEY");
for (Record rec : guestBookController.getRecords()) {
rec.print();
}
System.out.println("Enter your message with DONE at end");
Scanner mScanner = new Scanner(System.in);
String record = "";
try {
record += mScanner.nextLine();
} catch (Exception e) {
e.printStackTrace();
}
guestBookController.addRecord(record);
guestBookController.close();
}
| public static void main(String[] args) throws SQLException, ClassNotFoundException {
GuestBookControllerImpl guestBookController;
guestBookController = new GuestBookControllerImpl("guestbook", "SYSDBA", "MASTERKEY");
for (Record rec : guestBookController.getRecords()) {
rec.print();
}
System.out.println("Enter your message:");
Scanner mScanner = new Scanner(System.in);
String record = "";
try {
record += mScanner.nextLine();
} catch (Exception e) {
e.printStackTrace();
}
guestBookController.addRecord(record);
guestBookController.close();
}
|
diff --git a/plugins/org.eclipse.birt.report.viewer/src/org/eclipse/birt/report/viewer/utilities/ViewerClassPathHelper.java b/plugins/org.eclipse.birt.report.viewer/src/org/eclipse/birt/report/viewer/utilities/ViewerClassPathHelper.java
index 55281cac..82e7fd9b 100644
--- a/plugins/org.eclipse.birt.report.viewer/src/org/eclipse/birt/report/viewer/utilities/ViewerClassPathHelper.java
+++ b/plugins/org.eclipse.birt.report.viewer/src/org/eclipse/birt/report/viewer/utilities/ViewerClassPathHelper.java
@@ -1,256 +1,256 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.viewer.utilities;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.eclipse.birt.report.designer.ui.IReportClasspathResolver;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
/**
* Helper to handle viewer related classpath settings
*/
public class ViewerClassPathHelper
{
public static final String WORKSPACE_CLASSPATH_KEY = "workspace.projectclasspath"; //$NON-NLS-1$
private static final String FINDER_BUNDLE_NAME = "org.eclipse.birt.report.debug.ui"; //$NON-NLS-1$
private static final String FINDER_CLASSNAME = "org.eclipse.birt.report.debug.internal.ui.launcher.util.WorkspaceClassPathFinder"; //$NON-NLS-1$
static protected boolean inDevelopmentMode = false;
static protected String[] devDefaultClasspath;
static protected Properties devProperties = null;
public static final String PROPERTYSEPARATOR = File.pathSeparator;
static
{
// Check the osgi.dev property to see if dev classpath entries have been
// defined.
String osgiDev = System.getProperty( "osgi.dev" ); //$NON-NLS-1$
if ( osgiDev != null )
{
try
{
inDevelopmentMode = true;
URL location = new URL( osgiDev );
devProperties = load( location );
if ( devProperties != null )
devDefaultClasspath = getArrayFromList( devProperties.getProperty( "*" ) ); //$NON-NLS-1$
}
catch ( MalformedURLException e )
{
devDefaultClasspath = getArrayFromList( osgiDev );
}
}
}
public static String[] getDevClassPath( String id )
{
String[] result = null;
if ( id != null && devProperties != null )
{
String entry = devProperties.getProperty( id );
if ( entry != null )
result = getArrayFromList( entry );
}
if ( result == null )
result = devDefaultClasspath;
return result;
}
/**
* Returns the result of converting a list of comma-separated tokens into an
* array
*
* @return the array of string tokens
* @param prop
* the initial comma-separated string
*/
public static String[] getArrayFromList( String prop )
{
if ( prop == null || prop.trim( ).equals( "" ) ) //$NON-NLS-1$
return new String[0];
List<String> list = new ArrayList<String>( );
StringTokenizer tokens = new StringTokenizer( prop, "," ); //$NON-NLS-1$
while ( tokens.hasMoreTokens( ) )
{
String token = tokens.nextToken( ).trim( );
if ( !token.equals( "" ) ) //$NON-NLS-1$
list.add( token );
}
return list.isEmpty( ) ? new String[0]
: (String[]) list.toArray( new String[list.size( )] );
}
public static boolean inDevelopmentMode( )
{
return inDevelopmentMode;
}
/*
* Load the given properties file
*/
private static Properties load( URL url )
{
Properties props = new Properties( );
try
{
InputStream is = null;
try
{
is = url.openStream( );
props.load( is );
}
finally
{
if ( is != null )
is.close( );
}
}
catch ( IOException e )
{
// TODO consider logging here
}
return props;
}
/**
* Gets the workspace classpath
*
* @return
*
* @deprecated use {@link #getWorkspaceClassPath(String)}
*/
public static String getWorkspaceClassPath( )
{
try
{
Bundle bundle = Platform.getBundle( FINDER_BUNDLE_NAME );
if ( bundle != null )
{
if ( bundle.getState( ) == Bundle.RESOLVED )
{
bundle.start( Bundle.START_TRANSIENT );
}
}
if ( bundle == null )
return null;
Class<?> clz = bundle.loadClass( FINDER_CLASSNAME );
// register workspace classpath finder
IWorkspaceClasspathFinder finder = (IWorkspaceClasspathFinder) clz.newInstance( );
WorkspaceClasspathManager.registerClassPathFinder( finder );
// return the classpath property
return WorkspaceClasspathManager.getClassPath( );
}
catch ( Exception e )
{
e.printStackTrace( );
}
return null;
}
/**
* Returns the classpath associated with given report file.
*
* @param reportFilePath
* The full path of the report file.
* @return
*/
public static URL[] getWorkspaceClassPath( String reportFilePath )
{
ArrayList<URL> urls = new ArrayList<URL>( );
try
{
IReportClasspathResolver provider = ReportPlugin.getDefault( )
.getReportClasspathResolverService( );
if ( provider != null )
{
String[] classpaths = provider.resolveClasspath( reportFilePath );
if ( classpaths != null && classpaths.length != 0 )
{
for ( int j = 0; j < classpaths.length; j++ )
{
File file = new File( classpaths[j] );
try
{
urls.add( file.toURI( ).toURL( ) );
}
catch ( MalformedURLException e )
{
e.printStackTrace( );
}
}
}
}
}
- catch ( Exception e )
+ catch ( Throwable t )
{
// TODO consider logging here
}
return urls.toArray( new URL[urls.size( )] );
}
/**
* parse the URLs by input path string
*
* @param paths
* @return
*/
public static URL[] parseURLs( String paths )
{
ArrayList<URL> urls = new ArrayList<URL>( );
if ( paths != null && paths.trim( ).length( ) > 0 )
{
String[] classpaths = paths.split( PROPERTYSEPARATOR, -1 );
if ( classpaths != null && classpaths.length != 0 )
{
for ( int j = 0; j < classpaths.length; j++ )
{
File file = new File( classpaths[j] );
try
{
urls.add( file.toURI( ).toURL( ) );
}
catch ( MalformedURLException e )
{
e.printStackTrace( );
}
}
}
}
URL[] oUrls = new URL[urls.size( )];
urls.toArray( oUrls );
return oUrls;
}
}
| true | true | public static URL[] getWorkspaceClassPath( String reportFilePath )
{
ArrayList<URL> urls = new ArrayList<URL>( );
try
{
IReportClasspathResolver provider = ReportPlugin.getDefault( )
.getReportClasspathResolverService( );
if ( provider != null )
{
String[] classpaths = provider.resolveClasspath( reportFilePath );
if ( classpaths != null && classpaths.length != 0 )
{
for ( int j = 0; j < classpaths.length; j++ )
{
File file = new File( classpaths[j] );
try
{
urls.add( file.toURI( ).toURL( ) );
}
catch ( MalformedURLException e )
{
e.printStackTrace( );
}
}
}
}
}
catch ( Exception e )
{
// TODO consider logging here
}
return urls.toArray( new URL[urls.size( )] );
}
| public static URL[] getWorkspaceClassPath( String reportFilePath )
{
ArrayList<URL> urls = new ArrayList<URL>( );
try
{
IReportClasspathResolver provider = ReportPlugin.getDefault( )
.getReportClasspathResolverService( );
if ( provider != null )
{
String[] classpaths = provider.resolveClasspath( reportFilePath );
if ( classpaths != null && classpaths.length != 0 )
{
for ( int j = 0; j < classpaths.length; j++ )
{
File file = new File( classpaths[j] );
try
{
urls.add( file.toURI( ).toURL( ) );
}
catch ( MalformedURLException e )
{
e.printStackTrace( );
}
}
}
}
}
catch ( Throwable t )
{
// TODO consider logging here
}
return urls.toArray( new URL[urls.size( )] );
}
|
diff --git a/components/bio-formats/src/loci/formats/in/PDSReader.java b/components/bio-formats/src/loci/formats/in/PDSReader.java
index d9d3d1b20..4ad9e8ce6 100644
--- a/components/bio-formats/src/loci/formats/in/PDSReader.java
+++ b/components/bio-formats/src/loci/formats/in/PDSReader.java
@@ -1,284 +1,287 @@
//
// PDSReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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 loci.formats.in;
import java.io.IOException;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
/**
* PDSReader is the file format reader for Perkin Elmer densitometer files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/PDSReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/PDSReader.java;hb=HEAD">Gitweb</a></dd></dl>
*/
public class PDSReader extends FormatReader {
// -- Constants --
private static final String PDS_MAGIC_STRING = " IDENTIFICATION";
private static final String DATE_FORMAT = "HH:mm:ss d-MMM-** yyyy";
// -- Fields --
private String pixelsFile;
private int recordWidth;
private int lutIndex = -1;
private boolean reverseX = false, reverseY = false;
// -- Constructor --
/** Constructs a new PDS reader. */
public PDSReader() {
super("Perkin Elmer Densitometer", new String[] {"hdr", "img"});
domains = new String[] {FormatTools.EM_DOMAIN};
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (!open) return false;
if (checkSuffix(name, "hdr")) return super.isThisType(name, open);
else if (checkSuffix(name, "img")) {
String headerFile = name.substring(0, name.lastIndexOf(".")) + ".hdr";
return new Location(headerFile).exists() && isThisType(headerFile, open);
}
return false;
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 15;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
return stream.readString(blockLen).equals(PDS_MAGIC_STRING);
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lutIndex < 0 || lutIndex >= 3) return null;
short[][] lut = new short[3][65536];
for (int i=0; i<lut[lutIndex].length; i++) {
lut[lutIndex][i] = (short) i;
}
return lut;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (noPixels) {
return new String[] {currentId};
}
return new String[] {currentId, pixelsFile};
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int pad = recordWidth - (getSizeX() % recordWidth);
RandomAccessInputStream pixels = new RandomAccessInputStream(pixelsFile);
readPlane(pixels, x, y, w, h, pad, buf);
pixels.close();
if (reverseX) {
for (int row=0; row<h; row++) {
for (int col=0; col<w/2; col++) {
int begin = 2 * (row * w + col);
int end = 2 * (row * w + (w - col - 1));
byte b0 = buf[begin];
byte b1 = buf[begin + 1];
buf[begin] = buf[end];
buf[begin + 1] = buf[end + 1];
buf[end] = b0;
buf[end + 1] = b1;
}
}
}
if (reverseY) {
for (int row=0; row<h/2; row++) {
byte[] b = new byte[w * 2];
int start = row * w * 2;
int end = (h - row - 1) * w * 2;
System.arraycopy(buf, start, b, 0, b.length);
System.arraycopy(buf, end, buf, start, b.length);
System.arraycopy(b, 0, buf, end, b.length);
}
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
recordWidth = 0;
pixelsFile = null;
lutIndex = -1;
reverseX = reverseY = false;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (!checkSuffix(id, "hdr")) {
String headerFile = id.substring(0, id.lastIndexOf(".")) + ".hdr";
if (!new Location(headerFile).exists()) {
headerFile = id.substring(0, id.lastIndexOf(".")) + ".HDR";
if (!new Location(headerFile).exists()) {
throw new FormatException("Could not find matching .hdr file.");
}
}
initFile(headerFile);
return;
}
super.initFile(id);
String[] headerData = DataTools.readFile(id).split("\r\n");
+ if (headerData.length == 1) {
+ headerData = headerData[0].split("\r");
+ }
Double xPos = null, yPos = null;
Double deltaX = null, deltaY = null;
String date = null;
for (String line : headerData) {
int eq = line.indexOf("=");
if (eq < 0) continue;
int end = line.indexOf("/");
if (end < 0) end = line.length();
String key = line.substring(0, eq).trim();
String value = line.substring(eq + 1, end).trim();
if (key.equals("NXP")) {
core[0].sizeX = Integer.parseInt(value);
}
else if (key.equals("NYP")) {
core[0].sizeY = Integer.parseInt(value);
}
else if (key.equals("XPOS")) {
xPos = new Double(value);
addGlobalMeta("X position for position #1", xPos);
}
else if (key.equals("YPOS")) {
yPos = new Double(value);
addGlobalMeta("Y position for position #1", yPos);
}
else if (key.equals("SIGNX")) {
reverseX = value.replaceAll("'", "").trim().equals("-");
}
else if (key.equals("SIGNY")) {
reverseY = value.replaceAll("'", "").trim().equals("-");
}
else if (key.equals("DELTAX")) {
deltaX = new Double(value);
}
else if (key.equals("DELTAY")) {
deltaY = new Double(value);
}
else if (key.equals("COLOR")) {
int color = Integer.parseInt(value);
if (color == 4) {
core[0].sizeC = 3;
core[0].rgb = true;
}
else {
core[0].sizeC = 1;
core[0].rgb = false;
lutIndex = color - 1;
core[0].indexed = lutIndex >= 0;
}
}
else if (key.equals("SCAN TIME")) {
long modTime = new Location(currentId).getAbsoluteFile().lastModified();
String year = DateTools.convertDate(modTime, DateTools.UNIX, "yyyy");
date = value.replaceAll("'", "") + " " + year;
date = DateTools.formatDate(date, DATE_FORMAT);
}
else if (key.equals("FILE REC LEN")) {
recordWidth = Integer.parseInt(value) / 2;
}
addGlobalMeta(key, value);
}
core[0].sizeZ = 1;
core[0].sizeT = 1;
core[0].imageCount = 1;
core[0].dimensionOrder = "XYCZT";
core[0].pixelType = FormatTools.UINT16;
core[0].littleEndian = true;
String base = currentId.substring(0, currentId.lastIndexOf("."));
pixelsFile = base + ".IMG";
if (!new Location(pixelsFile).exists()) {
pixelsFile = base + ".img";
}
boolean minimumMetadata =
getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, !minimumMetadata);
if (date == null) {
MetadataTools.setDefaultCreationDate(store, currentId, 0);
}
else store.setImageAcquiredDate(date, 0);
if (!minimumMetadata) {
store.setPlanePositionX(xPos, 0, 0);
store.setPlanePositionY(yPos, 0, 0);
if (deltaX != null) {
store.setPixelsPhysicalSizeX(deltaX, 0);
}
if (deltaY != null) {
store.setPixelsPhysicalSizeY(deltaY, 0);
}
}
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
if (!checkSuffix(id, "hdr")) {
String headerFile = id.substring(0, id.lastIndexOf(".")) + ".hdr";
if (!new Location(headerFile).exists()) {
headerFile = id.substring(0, id.lastIndexOf(".")) + ".HDR";
if (!new Location(headerFile).exists()) {
throw new FormatException("Could not find matching .hdr file.");
}
}
initFile(headerFile);
return;
}
super.initFile(id);
String[] headerData = DataTools.readFile(id).split("\r\n");
Double xPos = null, yPos = null;
Double deltaX = null, deltaY = null;
String date = null;
for (String line : headerData) {
int eq = line.indexOf("=");
if (eq < 0) continue;
int end = line.indexOf("/");
if (end < 0) end = line.length();
String key = line.substring(0, eq).trim();
String value = line.substring(eq + 1, end).trim();
if (key.equals("NXP")) {
core[0].sizeX = Integer.parseInt(value);
}
else if (key.equals("NYP")) {
core[0].sizeY = Integer.parseInt(value);
}
else if (key.equals("XPOS")) {
xPos = new Double(value);
addGlobalMeta("X position for position #1", xPos);
}
else if (key.equals("YPOS")) {
yPos = new Double(value);
addGlobalMeta("Y position for position #1", yPos);
}
else if (key.equals("SIGNX")) {
reverseX = value.replaceAll("'", "").trim().equals("-");
}
else if (key.equals("SIGNY")) {
reverseY = value.replaceAll("'", "").trim().equals("-");
}
else if (key.equals("DELTAX")) {
deltaX = new Double(value);
}
else if (key.equals("DELTAY")) {
deltaY = new Double(value);
}
else if (key.equals("COLOR")) {
int color = Integer.parseInt(value);
if (color == 4) {
core[0].sizeC = 3;
core[0].rgb = true;
}
else {
core[0].sizeC = 1;
core[0].rgb = false;
lutIndex = color - 1;
core[0].indexed = lutIndex >= 0;
}
}
else if (key.equals("SCAN TIME")) {
long modTime = new Location(currentId).getAbsoluteFile().lastModified();
String year = DateTools.convertDate(modTime, DateTools.UNIX, "yyyy");
date = value.replaceAll("'", "") + " " + year;
date = DateTools.formatDate(date, DATE_FORMAT);
}
else if (key.equals("FILE REC LEN")) {
recordWidth = Integer.parseInt(value) / 2;
}
addGlobalMeta(key, value);
}
core[0].sizeZ = 1;
core[0].sizeT = 1;
core[0].imageCount = 1;
core[0].dimensionOrder = "XYCZT";
core[0].pixelType = FormatTools.UINT16;
core[0].littleEndian = true;
String base = currentId.substring(0, currentId.lastIndexOf("."));
pixelsFile = base + ".IMG";
if (!new Location(pixelsFile).exists()) {
pixelsFile = base + ".img";
}
boolean minimumMetadata =
getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, !minimumMetadata);
if (date == null) {
MetadataTools.setDefaultCreationDate(store, currentId, 0);
}
else store.setImageAcquiredDate(date, 0);
if (!minimumMetadata) {
store.setPlanePositionX(xPos, 0, 0);
store.setPlanePositionY(yPos, 0, 0);
if (deltaX != null) {
store.setPixelsPhysicalSizeX(deltaX, 0);
}
if (deltaY != null) {
store.setPixelsPhysicalSizeY(deltaY, 0);
}
}
}
| protected void initFile(String id) throws FormatException, IOException {
if (!checkSuffix(id, "hdr")) {
String headerFile = id.substring(0, id.lastIndexOf(".")) + ".hdr";
if (!new Location(headerFile).exists()) {
headerFile = id.substring(0, id.lastIndexOf(".")) + ".HDR";
if (!new Location(headerFile).exists()) {
throw new FormatException("Could not find matching .hdr file.");
}
}
initFile(headerFile);
return;
}
super.initFile(id);
String[] headerData = DataTools.readFile(id).split("\r\n");
if (headerData.length == 1) {
headerData = headerData[0].split("\r");
}
Double xPos = null, yPos = null;
Double deltaX = null, deltaY = null;
String date = null;
for (String line : headerData) {
int eq = line.indexOf("=");
if (eq < 0) continue;
int end = line.indexOf("/");
if (end < 0) end = line.length();
String key = line.substring(0, eq).trim();
String value = line.substring(eq + 1, end).trim();
if (key.equals("NXP")) {
core[0].sizeX = Integer.parseInt(value);
}
else if (key.equals("NYP")) {
core[0].sizeY = Integer.parseInt(value);
}
else if (key.equals("XPOS")) {
xPos = new Double(value);
addGlobalMeta("X position for position #1", xPos);
}
else if (key.equals("YPOS")) {
yPos = new Double(value);
addGlobalMeta("Y position for position #1", yPos);
}
else if (key.equals("SIGNX")) {
reverseX = value.replaceAll("'", "").trim().equals("-");
}
else if (key.equals("SIGNY")) {
reverseY = value.replaceAll("'", "").trim().equals("-");
}
else if (key.equals("DELTAX")) {
deltaX = new Double(value);
}
else if (key.equals("DELTAY")) {
deltaY = new Double(value);
}
else if (key.equals("COLOR")) {
int color = Integer.parseInt(value);
if (color == 4) {
core[0].sizeC = 3;
core[0].rgb = true;
}
else {
core[0].sizeC = 1;
core[0].rgb = false;
lutIndex = color - 1;
core[0].indexed = lutIndex >= 0;
}
}
else if (key.equals("SCAN TIME")) {
long modTime = new Location(currentId).getAbsoluteFile().lastModified();
String year = DateTools.convertDate(modTime, DateTools.UNIX, "yyyy");
date = value.replaceAll("'", "") + " " + year;
date = DateTools.formatDate(date, DATE_FORMAT);
}
else if (key.equals("FILE REC LEN")) {
recordWidth = Integer.parseInt(value) / 2;
}
addGlobalMeta(key, value);
}
core[0].sizeZ = 1;
core[0].sizeT = 1;
core[0].imageCount = 1;
core[0].dimensionOrder = "XYCZT";
core[0].pixelType = FormatTools.UINT16;
core[0].littleEndian = true;
String base = currentId.substring(0, currentId.lastIndexOf("."));
pixelsFile = base + ".IMG";
if (!new Location(pixelsFile).exists()) {
pixelsFile = base + ".img";
}
boolean minimumMetadata =
getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, !minimumMetadata);
if (date == null) {
MetadataTools.setDefaultCreationDate(store, currentId, 0);
}
else store.setImageAcquiredDate(date, 0);
if (!minimumMetadata) {
store.setPlanePositionX(xPos, 0, 0);
store.setPlanePositionY(yPos, 0, 0);
if (deltaX != null) {
store.setPixelsPhysicalSizeX(deltaX, 0);
}
if (deltaY != null) {
store.setPixelsPhysicalSizeY(deltaY, 0);
}
}
}
|
diff --git a/drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/rulebuilder/ui/ConstraintValueEditor.java b/drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/rulebuilder/ui/ConstraintValueEditor.java
index 9672676f..61cd5891 100644
--- a/drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/rulebuilder/ui/ConstraintValueEditor.java
+++ b/drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/rulebuilder/ui/ConstraintValueEditor.java
@@ -1,267 +1,267 @@
package org.drools.eclipse.rulebuilder.ui;
import java.util.List;
import org.drools.eclipse.DroolsEclipsePlugin;
import org.drools.guvnor.client.modeldriven.DropDownData;
import org.drools.guvnor.client.modeldriven.SuggestionCompletionEngine;
import org.drools.guvnor.client.modeldriven.brl.FactPattern;
import org.drools.guvnor.client.modeldriven.brl.ISingleFieldConstraint;
import org.drools.guvnor.client.modeldriven.brl.SingleFieldConstraint;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.events.IHyperlinkListener;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
public class ConstraintValueEditor {
private Composite composite;
private ISingleFieldConstraint constraint;
private FormToolkit toolkit;
private RuleModeller modeller;
private boolean numericValue;
private FactPattern pattern;
public ConstraintValueEditor(Composite composite,
ISingleFieldConstraint constraint,
FormToolkit toolkit,
RuleModeller modeller,
String numericType /* e.g. is "Numeric" */) {
this( composite,
constraint,
toolkit,
modeller,
numericType,
null );
}
public ConstraintValueEditor(Composite parent,
ISingleFieldConstraint c,
FormToolkit toolkit,
RuleModeller modeller,
String type,
FactPattern pattern) {
this.pattern = pattern;
this.composite = parent;
this.constraint = c;
this.toolkit = toolkit;
this.modeller = modeller;
if ( SuggestionCompletionEngine.TYPE_NUMERIC.equals( type ) ) {
this.numericValue = true;
}
create();
}
private void create() {
if ( constraint.constraintValueType == ISingleFieldConstraint.TYPE_UNDEFINED ) {
ImageHyperlink link = addImage( composite,
"icons/edit.gif" );
link.setToolTipText( "Choose value editor type" );
link.addHyperlinkListener( new IHyperlinkListener() {
public void linkActivated(HyperlinkEvent e) {
RuleDialog popup = new ValueEditorTypeSelectionDialog( composite.getShell(),
toolkit,
modeller,
constraint );
popup.open();
}
public void linkEntered(HyperlinkEvent e) {
}
public void linkExited(HyperlinkEvent e) {
}
} );
GridData gd = new GridData( GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING );
gd.horizontalSpan = 2;
link.setLayoutData( gd );
} else {
switch ( constraint.constraintValueType ) {
case ISingleFieldConstraint.TYPE_LITERAL :
literalValueEditor( composite,
constraint,
new GridData( GridData.FILL_HORIZONTAL ) );
break;
case ISingleFieldConstraint.TYPE_RET_VALUE :
addImage( composite,
"icons/function_assets.gif" );
formulaValueEditor( composite,
constraint,
new GridData( GridData.FILL_HORIZONTAL ) );
break;
case ISingleFieldConstraint.TYPE_VARIABLE :
variableEditor( composite,
constraint,
new GridData( GridData.FILL_HORIZONTAL ) );
break;
default :
break;
}
}
}
private void literalValueEditor(Composite parent,
final ISingleFieldConstraint c,
GridData gd) {
String fieldName = ((SingleFieldConstraint) c).fieldName;
DropDownData enums = modeller.getSuggestionCompletionEngine().getEnums( pattern,
fieldName );
boolean found = false;
if ( enums != null && enums.fixedList.length > 0 ) {
String[] list = enums.fixedList;
final Combo combo = new Combo( parent,
SWT.DROP_DOWN | SWT.READ_ONLY );
for ( int i = 0; i < list.length; i++ ) {
String e = list[i];
combo.add( e );
if ( e.equals( c.value ) ) {
combo.select( i );
found = true;
}
}
if ( !found && c.value != null ) {
combo.add( c.value );
combo.select( combo.getItemCount() - 1 );
}
combo.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = combo.getItem( combo.getSelectionIndex() );
- modeller.reloadRhs();
+ modeller.reloadLhs();
modeller.setDirty( true );
}
} );
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
gd.minimumWidth = 100;
combo.setLayoutData( gd );
} else {
final Text box = toolkit.createText( parent,
"" );
if ( c.value != null ) {
box.setText( c.value );
}
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
gd.minimumWidth = 100;
box.setLayoutData( gd );
box.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = box.getText();
modeller.setDirty( true );
}
} );
if ( this.numericValue ) {
box.addKeyListener( new KeyListener() {
public void keyPressed(KeyEvent e) {
if ( Character.isLetter( e.character ) ) {
e.doit = false;
}
}
public void keyReleased(KeyEvent e) {
}
} );
}
}
}
private void formulaValueEditor(Composite parent,
final ISingleFieldConstraint c,
GridData gd) {
final Text box = toolkit.createText( parent,
"" );
if ( c.value != null ) {
box.setText( c.value );
}
gd.grabExcessHorizontalSpace = true;
gd.minimumWidth = 100;
box.setLayoutData( gd );
box.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = box.getText();
modeller.setDirty( true );
}
} );
}
private void variableEditor(Composite composite,
final ISingleFieldConstraint c,
GridData gd) {
List vars = modeller.getModel().getBoundVariablesInScope( c );
final Combo combo = new Combo( composite,
SWT.READ_ONLY );
gd.horizontalSpan = 2;
combo.setLayoutData( gd );
if ( c.value == null ) {
combo.add( "Choose ..." );
}
int idx = 0;
for ( int i = 0; i < vars.size(); i++ ) {
String var = (String) vars.get( i );
if ( c.value != null && c.value.equals( var ) ) {
idx = i;
}
combo.add( var );
}
combo.select( idx );
combo.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = combo.getText();
}
} );
}
public ImageHyperlink addImage(Composite parent,
String fileName) {
ImageHyperlink imageHyperlink = toolkit.createImageHyperlink( parent,
0 );
ImageDescriptor imageDescriptor = DroolsEclipsePlugin.getImageDescriptor( fileName );
imageHyperlink.setImage( imageDescriptor.createImage() );
return imageHyperlink;
}
}
| true | true | private void literalValueEditor(Composite parent,
final ISingleFieldConstraint c,
GridData gd) {
String fieldName = ((SingleFieldConstraint) c).fieldName;
DropDownData enums = modeller.getSuggestionCompletionEngine().getEnums( pattern,
fieldName );
boolean found = false;
if ( enums != null && enums.fixedList.length > 0 ) {
String[] list = enums.fixedList;
final Combo combo = new Combo( parent,
SWT.DROP_DOWN | SWT.READ_ONLY );
for ( int i = 0; i < list.length; i++ ) {
String e = list[i];
combo.add( e );
if ( e.equals( c.value ) ) {
combo.select( i );
found = true;
}
}
if ( !found && c.value != null ) {
combo.add( c.value );
combo.select( combo.getItemCount() - 1 );
}
combo.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = combo.getItem( combo.getSelectionIndex() );
modeller.reloadRhs();
modeller.setDirty( true );
}
} );
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
gd.minimumWidth = 100;
combo.setLayoutData( gd );
} else {
final Text box = toolkit.createText( parent,
"" );
if ( c.value != null ) {
box.setText( c.value );
}
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
gd.minimumWidth = 100;
box.setLayoutData( gd );
box.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = box.getText();
modeller.setDirty( true );
}
} );
if ( this.numericValue ) {
box.addKeyListener( new KeyListener() {
public void keyPressed(KeyEvent e) {
if ( Character.isLetter( e.character ) ) {
e.doit = false;
}
}
public void keyReleased(KeyEvent e) {
}
} );
}
}
}
| private void literalValueEditor(Composite parent,
final ISingleFieldConstraint c,
GridData gd) {
String fieldName = ((SingleFieldConstraint) c).fieldName;
DropDownData enums = modeller.getSuggestionCompletionEngine().getEnums( pattern,
fieldName );
boolean found = false;
if ( enums != null && enums.fixedList.length > 0 ) {
String[] list = enums.fixedList;
final Combo combo = new Combo( parent,
SWT.DROP_DOWN | SWT.READ_ONLY );
for ( int i = 0; i < list.length; i++ ) {
String e = list[i];
combo.add( e );
if ( e.equals( c.value ) ) {
combo.select( i );
found = true;
}
}
if ( !found && c.value != null ) {
combo.add( c.value );
combo.select( combo.getItemCount() - 1 );
}
combo.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = combo.getItem( combo.getSelectionIndex() );
modeller.reloadLhs();
modeller.setDirty( true );
}
} );
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
gd.minimumWidth = 100;
combo.setLayoutData( gd );
} else {
final Text box = toolkit.createText( parent,
"" );
if ( c.value != null ) {
box.setText( c.value );
}
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
gd.minimumWidth = 100;
box.setLayoutData( gd );
box.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
c.value = box.getText();
modeller.setDirty( true );
}
} );
if ( this.numericValue ) {
box.addKeyListener( new KeyListener() {
public void keyPressed(KeyEvent e) {
if ( Character.isLetter( e.character ) ) {
e.doit = false;
}
}
public void keyReleased(KeyEvent e) {
}
} );
}
}
}
|
diff --git a/test/core/001-black-diamond-vanilla-condor/BlackDiamondDAX.java b/test/core/001-black-diamond-vanilla-condor/BlackDiamondDAX.java
index d22d3f3ad..08541f09f 100644
--- a/test/core/001-black-diamond-vanilla-condor/BlackDiamondDAX.java
+++ b/test/core/001-black-diamond-vanilla-condor/BlackDiamondDAX.java
@@ -1,117 +1,117 @@
/**
* Copyright 2007-2008 University Of Southern California
*
* 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.
*/
import edu.isi.pegasus.planner.dax.*;
public class BlackDiamondDAX {
/**
* Create an example DIAMOND DAX
* @param args
*/
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java ADAG <site_handle> <pegasus_location> <filename.dax>");
System.exit(1);
}
try {
Diamond(args[0]).writeToFile(args[1]);
}
catch (Exception e) {
e.printStackTrace();
}
}
private static ADAG Diamond(String pegasus_location) throws Exception {
java.io.File cwdFile = new java.io.File (".");
String cwd = cwdFile.getCanonicalPath();
ADAG dax = new ADAG("blackdiamond");
File fa = new File("f.a");
fa.addPhysicalFile("file://" + cwd + "/f.a", "local");
dax.addFile(fa);
File fb1 = new File("f.b1");
File fb2 = new File("f.b2");
File fc1 = new File("f.c1");
File fc2 = new File("f.c2");
File fd = new File("f.d");
fd.setRegister(true);
Executable preprocess = new Executable("pegasus", "preprocess", "4.0");
preprocess.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
preprocess.setInstalled(true);
- preprocess.addPhysicalFile("file://" + pegasus_location + "/bin/keg", "condorpool");
+ preprocess.addPhysicalFile("file://" + pegasus_location + "/bin/pegasus-keg", "condorpool");
Executable findrange = new Executable("pegasus", "findrange", "4.0");
findrange.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
findrange.setInstalled(true);
- findrange.addPhysicalFile("file://" + pegasus_location + "/bin/keg", "condorpool");
+ findrange.addPhysicalFile("file://" + pegasus_location + "/bin/pegasus-keg", "condorpool");
Executable analyze = new Executable("pegasus", "analyze", "4.0");
analyze.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
analyze.setInstalled(true);
- analyze.addPhysicalFile("file://" + pegasus_location + "/bin/keg", "condorpool");
+ analyze.addPhysicalFile("file://" + pegasus_location + "/bin/pegasus-keg", "condorpool");
dax.addExecutable(preprocess).addExecutable(findrange).addExecutable(analyze);
// Add a preprocess job
Job j1 = new Job("j1", "pegasus", "preprocess", "4.0");
j1.addArgument("-a preprocess -T 60 -i ").addArgument(fa);
j1.addArgument("-o ").addArgument(fb1);
j1.addArgument(" ").addArgument(fb2);
j1.uses(fa, File.LINK.INPUT);
j1.uses(fb1, File.LINK.OUTPUT);
j1.uses(fb2, File.LINK.OUTPUT);
dax.addJob(j1);
// Add left Findrange job
Job j2 = new Job("j2", "pegasus", "findrange", "4.0");
j2.addArgument("-a findrange -T 60 -i ").addArgument(fb1);
j2.addArgument("-o ").addArgument(fc1);
j2.uses(fb1, File.LINK.INPUT);
j2.uses(fc1, File.LINK.OUTPUT);
dax.addJob(j2);
// Add right Findrange job
Job j3 = new Job("j3", "pegasus", "findrange", "4.0");
j3.addArgument("-a findrange -T 60 -i ").addArgument(fb2);
j3.addArgument("-o ").addArgument(fc2);
j3.uses(fb2, File.LINK.INPUT);
j3.uses(fc2, File.LINK.OUTPUT);
dax.addJob(j3);
// Add analyze job
Job j4 = new Job("j4", "pegasus", "analyze", "4.0");
j4.addArgument("-a analyze -T 60 -i ").addArgument(fc1);
j4.addArgument(" ").addArgument(fc2);
j4.addArgument("-o ").addArgument(fd);
j4.uses(fc1, File.LINK.INPUT);
j4.uses(fc2, File.LINK.INPUT);
j4.uses(fd, File.LINK.OUTPUT);
dax.addJob(j4);
dax.addDependency("j1", "j2");
dax.addDependency("j1", "j3");
dax.addDependency("j2", "j4");
dax.addDependency("j3", "j4");
return dax;
}
}
| false | true | private static ADAG Diamond(String pegasus_location) throws Exception {
java.io.File cwdFile = new java.io.File (".");
String cwd = cwdFile.getCanonicalPath();
ADAG dax = new ADAG("blackdiamond");
File fa = new File("f.a");
fa.addPhysicalFile("file://" + cwd + "/f.a", "local");
dax.addFile(fa);
File fb1 = new File("f.b1");
File fb2 = new File("f.b2");
File fc1 = new File("f.c1");
File fc2 = new File("f.c2");
File fd = new File("f.d");
fd.setRegister(true);
Executable preprocess = new Executable("pegasus", "preprocess", "4.0");
preprocess.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
preprocess.setInstalled(true);
preprocess.addPhysicalFile("file://" + pegasus_location + "/bin/keg", "condorpool");
Executable findrange = new Executable("pegasus", "findrange", "4.0");
findrange.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
findrange.setInstalled(true);
findrange.addPhysicalFile("file://" + pegasus_location + "/bin/keg", "condorpool");
Executable analyze = new Executable("pegasus", "analyze", "4.0");
analyze.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
analyze.setInstalled(true);
analyze.addPhysicalFile("file://" + pegasus_location + "/bin/keg", "condorpool");
dax.addExecutable(preprocess).addExecutable(findrange).addExecutable(analyze);
// Add a preprocess job
Job j1 = new Job("j1", "pegasus", "preprocess", "4.0");
j1.addArgument("-a preprocess -T 60 -i ").addArgument(fa);
j1.addArgument("-o ").addArgument(fb1);
j1.addArgument(" ").addArgument(fb2);
j1.uses(fa, File.LINK.INPUT);
j1.uses(fb1, File.LINK.OUTPUT);
j1.uses(fb2, File.LINK.OUTPUT);
dax.addJob(j1);
// Add left Findrange job
Job j2 = new Job("j2", "pegasus", "findrange", "4.0");
j2.addArgument("-a findrange -T 60 -i ").addArgument(fb1);
j2.addArgument("-o ").addArgument(fc1);
j2.uses(fb1, File.LINK.INPUT);
j2.uses(fc1, File.LINK.OUTPUT);
dax.addJob(j2);
// Add right Findrange job
Job j3 = new Job("j3", "pegasus", "findrange", "4.0");
j3.addArgument("-a findrange -T 60 -i ").addArgument(fb2);
j3.addArgument("-o ").addArgument(fc2);
j3.uses(fb2, File.LINK.INPUT);
j3.uses(fc2, File.LINK.OUTPUT);
dax.addJob(j3);
// Add analyze job
Job j4 = new Job("j4", "pegasus", "analyze", "4.0");
j4.addArgument("-a analyze -T 60 -i ").addArgument(fc1);
j4.addArgument(" ").addArgument(fc2);
j4.addArgument("-o ").addArgument(fd);
j4.uses(fc1, File.LINK.INPUT);
j4.uses(fc2, File.LINK.INPUT);
j4.uses(fd, File.LINK.OUTPUT);
dax.addJob(j4);
dax.addDependency("j1", "j2");
dax.addDependency("j1", "j3");
dax.addDependency("j2", "j4");
dax.addDependency("j3", "j4");
return dax;
}
| private static ADAG Diamond(String pegasus_location) throws Exception {
java.io.File cwdFile = new java.io.File (".");
String cwd = cwdFile.getCanonicalPath();
ADAG dax = new ADAG("blackdiamond");
File fa = new File("f.a");
fa.addPhysicalFile("file://" + cwd + "/f.a", "local");
dax.addFile(fa);
File fb1 = new File("f.b1");
File fb2 = new File("f.b2");
File fc1 = new File("f.c1");
File fc2 = new File("f.c2");
File fd = new File("f.d");
fd.setRegister(true);
Executable preprocess = new Executable("pegasus", "preprocess", "4.0");
preprocess.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
preprocess.setInstalled(true);
preprocess.addPhysicalFile("file://" + pegasus_location + "/bin/pegasus-keg", "condorpool");
Executable findrange = new Executable("pegasus", "findrange", "4.0");
findrange.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
findrange.setInstalled(true);
findrange.addPhysicalFile("file://" + pegasus_location + "/bin/pegasus-keg", "condorpool");
Executable analyze = new Executable("pegasus", "analyze", "4.0");
analyze.setArchitecture(Executable.ARCH.X86).setOS(Executable.OS.LINUX);
analyze.setInstalled(true);
analyze.addPhysicalFile("file://" + pegasus_location + "/bin/pegasus-keg", "condorpool");
dax.addExecutable(preprocess).addExecutable(findrange).addExecutable(analyze);
// Add a preprocess job
Job j1 = new Job("j1", "pegasus", "preprocess", "4.0");
j1.addArgument("-a preprocess -T 60 -i ").addArgument(fa);
j1.addArgument("-o ").addArgument(fb1);
j1.addArgument(" ").addArgument(fb2);
j1.uses(fa, File.LINK.INPUT);
j1.uses(fb1, File.LINK.OUTPUT);
j1.uses(fb2, File.LINK.OUTPUT);
dax.addJob(j1);
// Add left Findrange job
Job j2 = new Job("j2", "pegasus", "findrange", "4.0");
j2.addArgument("-a findrange -T 60 -i ").addArgument(fb1);
j2.addArgument("-o ").addArgument(fc1);
j2.uses(fb1, File.LINK.INPUT);
j2.uses(fc1, File.LINK.OUTPUT);
dax.addJob(j2);
// Add right Findrange job
Job j3 = new Job("j3", "pegasus", "findrange", "4.0");
j3.addArgument("-a findrange -T 60 -i ").addArgument(fb2);
j3.addArgument("-o ").addArgument(fc2);
j3.uses(fb2, File.LINK.INPUT);
j3.uses(fc2, File.LINK.OUTPUT);
dax.addJob(j3);
// Add analyze job
Job j4 = new Job("j4", "pegasus", "analyze", "4.0");
j4.addArgument("-a analyze -T 60 -i ").addArgument(fc1);
j4.addArgument(" ").addArgument(fc2);
j4.addArgument("-o ").addArgument(fd);
j4.uses(fc1, File.LINK.INPUT);
j4.uses(fc2, File.LINK.INPUT);
j4.uses(fd, File.LINK.OUTPUT);
dax.addJob(j4);
dax.addDependency("j1", "j2");
dax.addDependency("j1", "j3");
dax.addDependency("j2", "j4");
dax.addDependency("j3", "j4");
return dax;
}
|
diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java b/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java
index 96c6964e..cdecd8b1 100644
--- a/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java
+++ b/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java
@@ -1,356 +1,359 @@
/*****************************************************************
Copyright � 2007 52�North Initiative for Geospatial Open Source Software GmbH
Author: foerster
Contact: Andreas Wytzisk,
52�North Initiative for Geospatial Open Source SoftwareGmbH,
Martin-Luther-King-Weg 24,
48155 Muenster, Germany,
[email protected]
This program 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 program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA or visit the Free
Software Foundation�s web page, http://www.fsf.org.
***************************************************************/
package org.n52.wps.server.response;
import java.util.ArrayList;
import java.util.List;
import net.opengis.wps.x100.ComplexDataDescriptionType;
import net.opengis.wps.x100.OutputDescriptionType;
import net.opengis.wps.x100.ProcessDescriptionType;
import org.apache.log4j.Logger;
import org.n52.wps.io.GeneratorFactory;
import org.n52.wps.io.IGenerator;
import org.n52.wps.io.data.IData;
import org.n52.wps.server.ExceptionReport;
import org.n52.wps.server.RepositoryManager;
/*
* @author foerster
* This and the inheriting classes in charge of populating the ExecuteResponseDocument.
*/
public abstract class ResponseData {
private static Logger LOGGER = Logger.getLogger(ResponseData.class);
protected IData obj = null;
protected String id;
protected String schema;
protected String encoding;
protected String mimeType;
protected IGenerator generator = null;
protected String algorithmIdentifier = null;
protected ProcessDescriptionType description = null;
public ResponseData(IData obj, String id, String schema, String encoding,
String mimeType, String algorithmIdentifier, ProcessDescriptionType description) throws ExceptionReport {
this.obj = obj;
this.id = id;
this.algorithmIdentifier = algorithmIdentifier;
this.description = description;
+ this.encoding = encoding;
OutputDescriptionType outputType =null;
OutputDescriptionType[] describeProcessOutput = description.getProcessOutputs().getOutputArray();
for(OutputDescriptionType tempOutputType : describeProcessOutput){
if(tempOutputType.getIdentifier().getStringValue().equalsIgnoreCase(id)){
outputType = tempOutputType;
}
}
//select generator
//0. complex output set? --> no: skip
//1. mimeType set?
//yes--> set it
//1.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> schema or/and encoding are set?
//yes-->use it, look if only one mime type can be found
//not-->use default values
String finalSchema = null;
String finalMimeType = null;
String finalEncoding = null;
if (outputType.isSetComplexOutput()){
if (mimeType != null){
//mime type in request
ComplexDataDescriptionType format = null;
String defaultMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potenitalFormat = outputType.getComplexOutput().getDefault().getFormat();
if(schema != null && encoding == null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema == null && encoding != null){
if(encoding.equalsIgnoreCase(potenitalFormat.getEncoding())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema != null && encoding != null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && encoding.equalsIgnoreCase(potenitalFormat.getEncoding())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema == null && encoding == null){
canUseDefault = true;
format = potenitalFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats =outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType potenitalFormat : formats){
if(potenitalFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(schema != null && encoding == null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema())){
format = potenitalFormat;
}
}
if(schema == null && encoding != null){
if(encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null){
format = potenitalFormat;
}
}
if(schema != null && encoding != null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && ((encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null) )){
format = potenitalFormat;
}
}
if(schema == null && encoding == null){
format = potenitalFormat;
}
}
}
}
if(format == null){
throw new ExceptionReport("Could not determine output format", ExceptionReport.INVALID_PARAMETER_VALUE);
}
finalMimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
finalEncoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
finalSchema = format.getSchema();
}
}else{
//mimeType not in request
if(mimeType==null && encoding==null && schema == null){
//nothing set, use default values
finalSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
finalMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType();
finalEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
}else{
//do a smart search an look if a mimeType can be found for either schema and/or encoding
if(mimeType==null){
if(encoding!=null && schema==null){
//encoding set only
ComplexDataDescriptionType encodingFormat = null;
String defaultEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
int found = 0;
String foundEncoding = null;
if(defaultEncoding.equalsIgnoreCase(encoding)){
foundEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
encodingFormat = outputType.getComplexOutput().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(encoding)){
foundEncoding = tempFormat.getEncoding();
encodingFormat = tempFormat;
found = found +1;
}
}
}
if(found == 1){
finalEncoding = foundEncoding;
finalMimeType = encodingFormat.getMimeType();
if(encodingFormat.isSetSchema()){
finalSchema = encodingFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(schema != null && encoding==null){
//schema set only
ComplexDataDescriptionType schemaFormat = null;
String defaultSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
int found = 0;
String foundSchema = null;
if(defaultSchema.equalsIgnoreCase(schema)){
foundSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
schemaFormat = outputType.getComplexOutput().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(schema)){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
}
}
if(found == 1){
finalSchema = foundSchema;
finalMimeType = schemaFormat.getMimeType();
if(schemaFormat.isSetEncoding()){
finalEncoding = schemaFormat.getEncoding();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(encoding!=null && schema!=null){
//schema and encoding set
//encoding
String defaultEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
List<ComplexDataDescriptionType> foundEncodingList = new ArrayList<ComplexDataDescriptionType>();
if(defaultEncoding.equalsIgnoreCase(encoding)){
foundEncodingList.add(outputType.getComplexOutput().getDefault().getFormat());
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(encoding)){
foundEncodingList.add(tempFormat);
}
}
//schema
List<ComplexDataDescriptionType> foundSchemaList = new ArrayList<ComplexDataDescriptionType>();
String defaultSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
if(defaultSchema.equalsIgnoreCase(schema)){
foundSchemaList.add(outputType.getComplexOutput().getDefault().getFormat());
}else{
formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(schema)){
foundSchemaList.add(tempFormat);
}
}
}
//results
ComplexDataDescriptionType foundCommonFormat = null;
for(ComplexDataDescriptionType encodingFormat : foundEncodingList){
for(ComplexDataDescriptionType schemaFormat : foundSchemaList){
if(encodingFormat.equals(schemaFormat)){
foundCommonFormat = encodingFormat;
}
}
}
if(foundCommonFormat!=null){
mimeType = foundCommonFormat.getMimeType();
if(foundCommonFormat.isSetEncoding()){
finalEncoding = foundCommonFormat.getEncoding();
}
if(foundCommonFormat.isSetSchema()){
finalSchema = foundCommonFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
}
}
}
}
}
this.schema = finalSchema;
- this.encoding = finalEncoding;
+ if(this.encoding==null){
+ this.encoding = finalEncoding;
+ }
this.mimeType = finalMimeType;
}
protected void prepareGenerator() throws ExceptionReport {
Class algorithmOutput = RepositoryManager.getInstance().getOutputDataTypeForAlgorithm(this.algorithmIdentifier, id);
LOGGER.debug("Looking for matching Generator ..." +
" schema: " + schema +
" mimeType: " + mimeType +
" encoding: " + encoding);
this.generator = GeneratorFactory.getInstance().getGenerator(this.schema, this.mimeType, this.encoding, algorithmOutput);
if(this.generator != null){
LOGGER.info("Using generator " + generator.getClass().getName() + " for Schema: " + schema);
}
if(this.generator == null) {
throw new ExceptionReport("Could not find an appropriate generator based on given mimetype/schema/encoding for output", ExceptionReport.NO_APPLICABLE_CODE);
}
}
}
| false | true | public ResponseData(IData obj, String id, String schema, String encoding,
String mimeType, String algorithmIdentifier, ProcessDescriptionType description) throws ExceptionReport {
this.obj = obj;
this.id = id;
this.algorithmIdentifier = algorithmIdentifier;
this.description = description;
OutputDescriptionType outputType =null;
OutputDescriptionType[] describeProcessOutput = description.getProcessOutputs().getOutputArray();
for(OutputDescriptionType tempOutputType : describeProcessOutput){
if(tempOutputType.getIdentifier().getStringValue().equalsIgnoreCase(id)){
outputType = tempOutputType;
}
}
//select generator
//0. complex output set? --> no: skip
//1. mimeType set?
//yes--> set it
//1.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> schema or/and encoding are set?
//yes-->use it, look if only one mime type can be found
//not-->use default values
String finalSchema = null;
String finalMimeType = null;
String finalEncoding = null;
if (outputType.isSetComplexOutput()){
if (mimeType != null){
//mime type in request
ComplexDataDescriptionType format = null;
String defaultMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potenitalFormat = outputType.getComplexOutput().getDefault().getFormat();
if(schema != null && encoding == null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema == null && encoding != null){
if(encoding.equalsIgnoreCase(potenitalFormat.getEncoding())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema != null && encoding != null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && encoding.equalsIgnoreCase(potenitalFormat.getEncoding())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema == null && encoding == null){
canUseDefault = true;
format = potenitalFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats =outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType potenitalFormat : formats){
if(potenitalFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(schema != null && encoding == null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema())){
format = potenitalFormat;
}
}
if(schema == null && encoding != null){
if(encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null){
format = potenitalFormat;
}
}
if(schema != null && encoding != null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && ((encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null) )){
format = potenitalFormat;
}
}
if(schema == null && encoding == null){
format = potenitalFormat;
}
}
}
}
if(format == null){
throw new ExceptionReport("Could not determine output format", ExceptionReport.INVALID_PARAMETER_VALUE);
}
finalMimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
finalEncoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
finalSchema = format.getSchema();
}
}else{
//mimeType not in request
if(mimeType==null && encoding==null && schema == null){
//nothing set, use default values
finalSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
finalMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType();
finalEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
}else{
//do a smart search an look if a mimeType can be found for either schema and/or encoding
if(mimeType==null){
if(encoding!=null && schema==null){
//encoding set only
ComplexDataDescriptionType encodingFormat = null;
String defaultEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
int found = 0;
String foundEncoding = null;
if(defaultEncoding.equalsIgnoreCase(encoding)){
foundEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
encodingFormat = outputType.getComplexOutput().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(encoding)){
foundEncoding = tempFormat.getEncoding();
encodingFormat = tempFormat;
found = found +1;
}
}
}
if(found == 1){
finalEncoding = foundEncoding;
finalMimeType = encodingFormat.getMimeType();
if(encodingFormat.isSetSchema()){
finalSchema = encodingFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(schema != null && encoding==null){
//schema set only
ComplexDataDescriptionType schemaFormat = null;
String defaultSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
int found = 0;
String foundSchema = null;
if(defaultSchema.equalsIgnoreCase(schema)){
foundSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
schemaFormat = outputType.getComplexOutput().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(schema)){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
}
}
if(found == 1){
finalSchema = foundSchema;
finalMimeType = schemaFormat.getMimeType();
if(schemaFormat.isSetEncoding()){
finalEncoding = schemaFormat.getEncoding();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(encoding!=null && schema!=null){
//schema and encoding set
//encoding
String defaultEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
List<ComplexDataDescriptionType> foundEncodingList = new ArrayList<ComplexDataDescriptionType>();
if(defaultEncoding.equalsIgnoreCase(encoding)){
foundEncodingList.add(outputType.getComplexOutput().getDefault().getFormat());
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(encoding)){
foundEncodingList.add(tempFormat);
}
}
//schema
List<ComplexDataDescriptionType> foundSchemaList = new ArrayList<ComplexDataDescriptionType>();
String defaultSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
if(defaultSchema.equalsIgnoreCase(schema)){
foundSchemaList.add(outputType.getComplexOutput().getDefault().getFormat());
}else{
formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(schema)){
foundSchemaList.add(tempFormat);
}
}
}
//results
ComplexDataDescriptionType foundCommonFormat = null;
for(ComplexDataDescriptionType encodingFormat : foundEncodingList){
for(ComplexDataDescriptionType schemaFormat : foundSchemaList){
if(encodingFormat.equals(schemaFormat)){
foundCommonFormat = encodingFormat;
}
}
}
if(foundCommonFormat!=null){
mimeType = foundCommonFormat.getMimeType();
if(foundCommonFormat.isSetEncoding()){
finalEncoding = foundCommonFormat.getEncoding();
}
if(foundCommonFormat.isSetSchema()){
finalSchema = foundCommonFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
}
}
}
}
}
this.schema = finalSchema;
this.encoding = finalEncoding;
this.mimeType = finalMimeType;
}
| public ResponseData(IData obj, String id, String schema, String encoding,
String mimeType, String algorithmIdentifier, ProcessDescriptionType description) throws ExceptionReport {
this.obj = obj;
this.id = id;
this.algorithmIdentifier = algorithmIdentifier;
this.description = description;
this.encoding = encoding;
OutputDescriptionType outputType =null;
OutputDescriptionType[] describeProcessOutput = description.getProcessOutputs().getOutputArray();
for(OutputDescriptionType tempOutputType : describeProcessOutput){
if(tempOutputType.getIdentifier().getStringValue().equalsIgnoreCase(id)){
outputType = tempOutputType;
}
}
//select generator
//0. complex output set? --> no: skip
//1. mimeType set?
//yes--> set it
//1.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> schema or/and encoding are set?
//yes-->use it, look if only one mime type can be found
//not-->use default values
String finalSchema = null;
String finalMimeType = null;
String finalEncoding = null;
if (outputType.isSetComplexOutput()){
if (mimeType != null){
//mime type in request
ComplexDataDescriptionType format = null;
String defaultMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potenitalFormat = outputType.getComplexOutput().getDefault().getFormat();
if(schema != null && encoding == null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema == null && encoding != null){
if(encoding.equalsIgnoreCase(potenitalFormat.getEncoding())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema != null && encoding != null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && encoding.equalsIgnoreCase(potenitalFormat.getEncoding())){
canUseDefault = true;
format = potenitalFormat;
}
}
if(schema == null && encoding == null){
canUseDefault = true;
format = potenitalFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats =outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType potenitalFormat : formats){
if(potenitalFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(schema != null && encoding == null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema())){
format = potenitalFormat;
}
}
if(schema == null && encoding != null){
if(encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null){
format = potenitalFormat;
}
}
if(schema != null && encoding != null){
if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && ((encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null) )){
format = potenitalFormat;
}
}
if(schema == null && encoding == null){
format = potenitalFormat;
}
}
}
}
if(format == null){
throw new ExceptionReport("Could not determine output format", ExceptionReport.INVALID_PARAMETER_VALUE);
}
finalMimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
finalEncoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
finalSchema = format.getSchema();
}
}else{
//mimeType not in request
if(mimeType==null && encoding==null && schema == null){
//nothing set, use default values
finalSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
finalMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType();
finalEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
}else{
//do a smart search an look if a mimeType can be found for either schema and/or encoding
if(mimeType==null){
if(encoding!=null && schema==null){
//encoding set only
ComplexDataDescriptionType encodingFormat = null;
String defaultEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
int found = 0;
String foundEncoding = null;
if(defaultEncoding.equalsIgnoreCase(encoding)){
foundEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
encodingFormat = outputType.getComplexOutput().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(encoding)){
foundEncoding = tempFormat.getEncoding();
encodingFormat = tempFormat;
found = found +1;
}
}
}
if(found == 1){
finalEncoding = foundEncoding;
finalMimeType = encodingFormat.getMimeType();
if(encodingFormat.isSetSchema()){
finalSchema = encodingFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(schema != null && encoding==null){
//schema set only
ComplexDataDescriptionType schemaFormat = null;
String defaultSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
int found = 0;
String foundSchema = null;
if(defaultSchema.equalsIgnoreCase(schema)){
foundSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
schemaFormat = outputType.getComplexOutput().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(schema)){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
}
}
if(found == 1){
finalSchema = foundSchema;
finalMimeType = schemaFormat.getMimeType();
if(schemaFormat.isSetEncoding()){
finalEncoding = schemaFormat.getEncoding();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(encoding!=null && schema!=null){
//schema and encoding set
//encoding
String defaultEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding();
List<ComplexDataDescriptionType> foundEncodingList = new ArrayList<ComplexDataDescriptionType>();
if(defaultEncoding.equalsIgnoreCase(encoding)){
foundEncodingList.add(outputType.getComplexOutput().getDefault().getFormat());
}else{
ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(encoding)){
foundEncodingList.add(tempFormat);
}
}
//schema
List<ComplexDataDescriptionType> foundSchemaList = new ArrayList<ComplexDataDescriptionType>();
String defaultSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema();
if(defaultSchema.equalsIgnoreCase(schema)){
foundSchemaList.add(outputType.getComplexOutput().getDefault().getFormat());
}else{
formats = outputType.getComplexOutput().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(schema)){
foundSchemaList.add(tempFormat);
}
}
}
//results
ComplexDataDescriptionType foundCommonFormat = null;
for(ComplexDataDescriptionType encodingFormat : foundEncodingList){
for(ComplexDataDescriptionType schemaFormat : foundSchemaList){
if(encodingFormat.equals(schemaFormat)){
foundCommonFormat = encodingFormat;
}
}
}
if(foundCommonFormat!=null){
mimeType = foundCommonFormat.getMimeType();
if(foundCommonFormat.isSetEncoding()){
finalEncoding = foundCommonFormat.getEncoding();
}
if(foundCommonFormat.isSetSchema()){
finalSchema = foundCommonFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
}
}
}
}
}
this.schema = finalSchema;
if(this.encoding==null){
this.encoding = finalEncoding;
}
this.mimeType = finalMimeType;
}
|
diff --git a/src/me/silentdojo/prestige/PrestigeCommandExecutor.java b/src/me/silentdojo/prestige/PrestigeCommandExecutor.java
index 8b51b53..04cde38 100644
--- a/src/me/silentdojo/prestige/PrestigeCommandExecutor.java
+++ b/src/me/silentdojo/prestige/PrestigeCommandExecutor.java
@@ -1,200 +1,200 @@
package me.silentdojo.prestige;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.gmail.nossr50.Users;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.datatypes.SkillType;
import com.gmail.nossr50.skills.Skills;
public class PrestigeCommandExecutor implements CommandExecutor{
private Permission permission;
public PrestigeCommandExecutor(Prestige plugin, Permission permission){
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(command.getName().equalsIgnoreCase("prestige")){
if(args.length == 0){
sender.sendMessage(ChatColor.UNDERLINE + " ");
sender.sendMessage(ChatColor.DARK_GREEN + "Prestige is a new way to advance your skills.");
sender.sendMessage(" - " + ChatColor.AQUA + "Gain amazing new abilities by focusing on specific Skills.");
sender.sendMessage(" - " + ChatColor.AQUA + "Choose wisely. Benefits come at a price!");
sender.sendMessage(" - " + ChatColor.AQUA + "Each Prestige resets your Skill Level.");
sender.sendMessage(" - " + ChatColor.AQUA + "PvP Skill Prestige will remove a PvE Ability.");
sender.sendMessage(" - " + ChatColor.AQUA + "PvE Skill Prestige will remove a PvP Ability.");
sender.sendMessage(" - " + ChatColor.DARK_RED + "Use " + ChatColor.ITALIC + "/prestige <Skillname>");
sender.sendMessage(ChatColor.UNDERLINE + " ");
sender.sendMessage(" ");
return false;
}
Player player = (Player) sender;
PlayerProfile PP = Users.getProfile(player);
int skillLevel = 0;
SkillType type = null;
type = Skills.getSkillType(args[0]);
skillLevel = PP.getSkillLevel(type);
PP.modifyskill(type, 0);
switch(type){
case ACROBATICS: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.acrobatics.gracefulroll");
player.setAllowFlight(true);
sender.sendMessage("you have upgraded your acrobatics skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;}
case UNARMED: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.unarmed.bonusdamage");
sender.sendMessage("you have upgraded your unarmed skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case MINING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.mining.doubledrops");
sender.sendMessage("you have upgraded your mining skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case WOODCUTTING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.woodcutting.doubledrops");
sender.sendMessage("you have upgraded your woodcutting skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case HERBALISM: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.herbalism.doubledrops");
sender.sendMessage("you have upgraded your herbalism skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case AXES: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.axes.bonusdamage");
sender.sendMessage("you have upgraded your axes skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case SWORDS: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.swords.serratedstrikes");
sender.sendMessage("you have upgraded your swords skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case TAMING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.taming.callofthewild");
sender.sendMessage("you have upgraded your taming skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case FISHING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.fishing.shakemob");
sender.sendMessage("you have upgraded your fishing skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case EXCAVATION: {
if (skillLevel >= 1000){
ItemStack itemToGive = new ItemStack(Material.DIAMOND,30);
player.getInventory().addItem(itemToGive);
sender.sendMessage("you have recieved a bonus for excavation");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case REPAIR: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.repair.armorrepair");
sender.sendMessage("you have upgraded your repair skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case ARCHERY: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.archery.ignition");
sender.sendMessage("you have upgraded your archery skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
}
return true;
}
// Test Command
if(command.getName().equalsIgnoreCase("test")){
if(args.length == 0){
sender.sendMessage("Use /test <SkillName>");
}else{
Player player = (Player) sender;
PlayerProfile PP = Users.getProfile(player);
SkillType type2 = Skills.getSkillType(args[0]);
- PP.addXP(type2, 1000, player);
+ PP.addLevels(type2, 1000);
sender.sendMessage("You added 1000 Levels to " + type2);
}
return false;
}
// PowerUp Command
if(command.getName().equalsIgnoreCase("powerup")){
if(args.length == 0){
final Player player = (Player) sender;
float exp = player.getExp();
if(exp >= 0){
System.out.println("Exp is: " + exp);
player.setAllowFlight(true);
player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 300, 3));
player.sendMessage("Hey Hey Hey!");
}
return false;
}
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(command.getName().equalsIgnoreCase("prestige")){
if(args.length == 0){
sender.sendMessage(ChatColor.UNDERLINE + " ");
sender.sendMessage(ChatColor.DARK_GREEN + "Prestige is a new way to advance your skills.");
sender.sendMessage(" - " + ChatColor.AQUA + "Gain amazing new abilities by focusing on specific Skills.");
sender.sendMessage(" - " + ChatColor.AQUA + "Choose wisely. Benefits come at a price!");
sender.sendMessage(" - " + ChatColor.AQUA + "Each Prestige resets your Skill Level.");
sender.sendMessage(" - " + ChatColor.AQUA + "PvP Skill Prestige will remove a PvE Ability.");
sender.sendMessage(" - " + ChatColor.AQUA + "PvE Skill Prestige will remove a PvP Ability.");
sender.sendMessage(" - " + ChatColor.DARK_RED + "Use " + ChatColor.ITALIC + "/prestige <Skillname>");
sender.sendMessage(ChatColor.UNDERLINE + " ");
sender.sendMessage(" ");
return false;
}
Player player = (Player) sender;
PlayerProfile PP = Users.getProfile(player);
int skillLevel = 0;
SkillType type = null;
type = Skills.getSkillType(args[0]);
skillLevel = PP.getSkillLevel(type);
PP.modifyskill(type, 0);
switch(type){
case ACROBATICS: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.acrobatics.gracefulroll");
player.setAllowFlight(true);
sender.sendMessage("you have upgraded your acrobatics skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;}
case UNARMED: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.unarmed.bonusdamage");
sender.sendMessage("you have upgraded your unarmed skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case MINING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.mining.doubledrops");
sender.sendMessage("you have upgraded your mining skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case WOODCUTTING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.woodcutting.doubledrops");
sender.sendMessage("you have upgraded your woodcutting skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case HERBALISM: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.herbalism.doubledrops");
sender.sendMessage("you have upgraded your herbalism skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case AXES: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.axes.bonusdamage");
sender.sendMessage("you have upgraded your axes skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case SWORDS: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.swords.serratedstrikes");
sender.sendMessage("you have upgraded your swords skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case TAMING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.taming.callofthewild");
sender.sendMessage("you have upgraded your taming skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case FISHING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.fishing.shakemob");
sender.sendMessage("you have upgraded your fishing skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case EXCAVATION: {
if (skillLevel >= 1000){
ItemStack itemToGive = new ItemStack(Material.DIAMOND,30);
player.getInventory().addItem(itemToGive);
sender.sendMessage("you have recieved a bonus for excavation");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case REPAIR: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.repair.armorrepair");
sender.sendMessage("you have upgraded your repair skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case ARCHERY: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.archery.ignition");
sender.sendMessage("you have upgraded your archery skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
}
return true;
}
// Test Command
if(command.getName().equalsIgnoreCase("test")){
if(args.length == 0){
sender.sendMessage("Use /test <SkillName>");
}else{
Player player = (Player) sender;
PlayerProfile PP = Users.getProfile(player);
SkillType type2 = Skills.getSkillType(args[0]);
PP.addXP(type2, 1000, player);
sender.sendMessage("You added 1000 Levels to " + type2);
}
return false;
}
// PowerUp Command
if(command.getName().equalsIgnoreCase("powerup")){
if(args.length == 0){
final Player player = (Player) sender;
float exp = player.getExp();
if(exp >= 0){
System.out.println("Exp is: " + exp);
player.setAllowFlight(true);
player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 300, 3));
player.sendMessage("Hey Hey Hey!");
}
return false;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(command.getName().equalsIgnoreCase("prestige")){
if(args.length == 0){
sender.sendMessage(ChatColor.UNDERLINE + " ");
sender.sendMessage(ChatColor.DARK_GREEN + "Prestige is a new way to advance your skills.");
sender.sendMessage(" - " + ChatColor.AQUA + "Gain amazing new abilities by focusing on specific Skills.");
sender.sendMessage(" - " + ChatColor.AQUA + "Choose wisely. Benefits come at a price!");
sender.sendMessage(" - " + ChatColor.AQUA + "Each Prestige resets your Skill Level.");
sender.sendMessage(" - " + ChatColor.AQUA + "PvP Skill Prestige will remove a PvE Ability.");
sender.sendMessage(" - " + ChatColor.AQUA + "PvE Skill Prestige will remove a PvP Ability.");
sender.sendMessage(" - " + ChatColor.DARK_RED + "Use " + ChatColor.ITALIC + "/prestige <Skillname>");
sender.sendMessage(ChatColor.UNDERLINE + " ");
sender.sendMessage(" ");
return false;
}
Player player = (Player) sender;
PlayerProfile PP = Users.getProfile(player);
int skillLevel = 0;
SkillType type = null;
type = Skills.getSkillType(args[0]);
skillLevel = PP.getSkillLevel(type);
PP.modifyskill(type, 0);
switch(type){
case ACROBATICS: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.acrobatics.gracefulroll");
player.setAllowFlight(true);
sender.sendMessage("you have upgraded your acrobatics skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;}
case UNARMED: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.unarmed.bonusdamage");
sender.sendMessage("you have upgraded your unarmed skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case MINING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.mining.doubledrops");
sender.sendMessage("you have upgraded your mining skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case WOODCUTTING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.woodcutting.doubledrops");
sender.sendMessage("you have upgraded your woodcutting skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case HERBALISM: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.herbalism.doubledrops");
sender.sendMessage("you have upgraded your herbalism skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case AXES: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.axes.bonusdamage");
sender.sendMessage("you have upgraded your axes skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case SWORDS: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.swords.serratedstrikes");
sender.sendMessage("you have upgraded your swords skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case TAMING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.taming.callofthewild");
sender.sendMessage("you have upgraded your taming skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case FISHING: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.fishing.shakemob");
sender.sendMessage("you have upgraded your fishing skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case EXCAVATION: {
if (skillLevel >= 1000){
ItemStack itemToGive = new ItemStack(Material.DIAMOND,30);
player.getInventory().addItem(itemToGive);
sender.sendMessage("you have recieved a bonus for excavation");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case REPAIR: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.repair.armorrepair");
sender.sendMessage("you have upgraded your repair skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
case ARCHERY: {
if (skillLevel >= 1000){
permission.playerAdd(player, "mcmmo.ability.archery.ignition");
sender.sendMessage("you have upgraded your archery skill");
}else
sender.sendMessage("Skill Level is Not 1000 yet try again later!!");
break;
}
}
return true;
}
// Test Command
if(command.getName().equalsIgnoreCase("test")){
if(args.length == 0){
sender.sendMessage("Use /test <SkillName>");
}else{
Player player = (Player) sender;
PlayerProfile PP = Users.getProfile(player);
SkillType type2 = Skills.getSkillType(args[0]);
PP.addLevels(type2, 1000);
sender.sendMessage("You added 1000 Levels to " + type2);
}
return false;
}
// PowerUp Command
if(command.getName().equalsIgnoreCase("powerup")){
if(args.length == 0){
final Player player = (Player) sender;
float exp = player.getExp();
if(exp >= 0){
System.out.println("Exp is: " + exp);
player.setAllowFlight(true);
player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 300, 3));
player.sendMessage("Hey Hey Hey!");
}
return false;
}
}
return false;
}
|
diff --git a/wings2/src/java/org/wings/plaf/css/FrameCG.java b/wings2/src/java/org/wings/plaf/css/FrameCG.java
index 351ab459..7badb742 100644
--- a/wings2/src/java/org/wings/plaf/css/FrameCG.java
+++ b/wings2/src/java/org/wings/plaf/css/FrameCG.java
@@ -1,376 +1,376 @@
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wings.*;
import org.wings.externalizer.ExternalizeManager;
import org.wings.header.Link;
import org.wings.header.Script;
import org.wings.io.Device;
import org.wings.plaf.CGManager;
import org.wings.resource.ClassPathStylesheetResource;
import org.wings.resource.ClasspathResource;
import org.wings.resource.DefaultURLResource;
import org.wings.resource.DynamicCodeResource;
import org.wings.script.DynamicScriptResource;
import org.wings.script.JavaScriptListener;
import org.wings.script.ScriptListener;
import org.wings.session.Browser;
import org.wings.session.BrowserType;
import org.wings.session.SessionManager;
import org.wings.style.CSSSelector;
import org.wings.style.DynamicStyleSheetResource;
import java.io.IOException;
import java.util.*;
public class FrameCG implements org.wings.plaf.FrameCG {
private final transient static Log log = LogFactory.getLog(FrameCG.class);
/**
* The default DOCTYPE enforcing standard (non-quirks mode) in all current browsers.
* Please be aware, that changing the DOCTYPE may change the way how browser renders the generate
* document i.e. esp. the CSS attribute inheritance does not work correctly on <code>table</code> elements.
* See i.e. http://www.ericmeyeroncss.com/bonus/render-mode.html
*/
public final static String STRICT_DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" " +
"\"http://www.w3.org/TR/REC-html40/strict.dtd\">";
/**
* The HTML DOCTYPE setting all browsers to Quirks mode.
* We need this to force IE to use the correct box rendering model. It's the only browser
* you cannot reconfigure via an CSS tag.
*/
public final static String QUIRKS_DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">";
private String documentType = STRICT_DOCTYPE;
private Boolean renderXmlDeclaration = Boolean.FALSE;
/**
* Initialize properties from config
*/
public FrameCG() {
final CGManager manager = SessionManager.getSession().getCGManager();
final String userDocType = (String) manager.getObject("FrameCG.userDocType", String.class);
final Boolean userRenderXmlDecl = (Boolean) manager.getObject("FrameCG.renderXmlDeclaration", Boolean.class);
if (userDocType != null)
setDocumentType(userDocType);
if (userRenderXmlDecl != null)
setRenderXmlDeclaration(userRenderXmlDecl);
}
private static final String PROPERTY_STYLESHEET = "Stylesheet.";
private static final String BROWSER_DEFAULT = "default";
private final static Set javascriptResourceKeys;
static {
javascriptResourceKeys = new HashSet();
javascriptResourceKeys.add("JScripts.domlib");
javascriptResourceKeys.add("JScripts.domtt");
}
/**
* Externalizes the style sheet(s) for this session.
* Look up according style sheet file name in org.wings.plaf.css.properties file under Stylesheet.BROWSERNAME.
* The style sheet is loaded from the class path.
* @return the URLs under which the css file(s) was externalized
*/
private List externalizeBrowserStylesheets() {
final ExternalizeManager extManager = SessionManager.getSession().getExternalizeManager();
final CGManager manager = SessionManager.getSession().getCGManager();
final String browserName = SessionManager.getSession().getUserAgent().getBrowserType().getShortName();
final String cssResource = PROPERTY_STYLESHEET + browserName;
String cssClassPaths = (String)manager.getObject(cssResource, String.class);
// catch missing browser entry in properties file
if (cssClassPaths == null) {
cssClassPaths = (String)manager.getObject(PROPERTY_STYLESHEET + BROWSER_DEFAULT, String.class);
}
StringTokenizer tokenizer = new StringTokenizer(cssClassPaths,",");
ArrayList cssUrls = new ArrayList();
while (tokenizer.hasMoreTokens()) {
String cssClassPath = tokenizer.nextToken();
ClassPathStylesheetResource res = new ClassPathStylesheetResource(cssClassPath, "text/css");
String cssUrl = extManager.externalize(res, ExternalizeManager.GLOBAL);
if (cssUrl != null)
cssUrls.add(cssUrl);
}
return cssUrls;
}
/**
* @param jsResKey
* @return
*/
private String externalizeJavaScript(String jsResKey) {
final ExternalizeManager extManager = SessionManager.getSession().getExternalizeManager();
final CGManager manager = SessionManager.getSession().getCGManager();
String jsClassPath = (String)manager.getObject(jsResKey, String.class);
// catch missing script entry in properties file
if (jsClassPath != null) {
ClasspathResource res = new ClasspathResource(jsClassPath, "text/javascript");
return extManager.externalize(res, ExternalizeManager.GLOBAL);
}
return null;
}
public static final String UTILS_SCRIPT = (String) SessionManager
.getSession().getCGManager().getObject("JScripts.utils",
String.class);
public static final String FORM_SCRIPT = (String) SessionManager
.getSession().getCGManager().getObject("JScripts.form",
String.class);
public static final JavaScriptListener FOCUS_SCRIPT =
new JavaScriptListener("onfocus", "storeFocus(event)");
public static final JavaScriptListener SCROLL_POSITION_SCRIPT =
new JavaScriptListener("onscroll", "storeScrollPosition(event)");
public void installCG(final SComponent comp) {
final SFrame component = (SFrame) comp;
DynamicCodeResource dynamicCodeRessource;
DynamicStyleSheetResource styleSheetResource;
DynamicScriptResource scriptResource;
Link stylesheetLink;
// dynamic code resource.
dynamicCodeRessource = new DynamicCodeResource(component);
component.addDynamicResource(dynamicCodeRessource);
// dynamic stylesheet resource.
styleSheetResource = new DynamicStyleSheetResource(component);
stylesheetLink = new Link("stylesheet", null, "text/css", null, styleSheetResource);
component.addDynamicResource(styleSheetResource);
component.addHeader(stylesheetLink);
// dynamic java script resource.
scriptResource = new DynamicScriptResource(component);
component.addDynamicResource(scriptResource);
component.addHeader(new Script("text/javascript", scriptResource));
Iterator iter = javascriptResourceKeys.iterator();
while (iter.hasNext()) {
String jsResKey = (String) iter.next();
String jScriptUrl = externalizeJavaScript(jsResKey);
if (jScriptUrl != null) {
component.addHeader(new Script("text/javascript", new DefaultURLResource(jScriptUrl)));
}
}
final List externalizedBrowserCssUrls = externalizeBrowserStylesheets();
for (int i = 0; i < externalizedBrowserCssUrls.size(); i++) {
component.headers().add(i, new Link("stylesheet", null, "text/css", null, new DefaultURLResource((String) externalizedBrowserCssUrls.get(i))));;
}
addExternalizedHeader(component, UTILS_SCRIPT, "text/javascript");
addExternalizedHeader(component, FORM_SCRIPT, "text/javascript");
component.addScriptListener(FOCUS_SCRIPT);
component.addScriptListener(SCROLL_POSITION_SCRIPT);
CaptureDefaultBindingsScriptListener.install(component);
}
/**
* adds the file found at the classPath to the parentFrame header with
* the specified mimeType
* @param classPath the classPath to look in for the file
* @param mimeType the mimetype of the file
*/
private void addExternalizedHeader(SFrame parentFrame, String classPath, String mimeType) {
ClasspathResource res = new ClasspathResource(classPath, mimeType);
String jScriptUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
parentFrame.addHeader(new Script(mimeType, new DefaultURLResource(jScriptUrl)));
}
public void uninstallCG(final SComponent comp) {
final SFrame component = (SFrame) comp;
component.removeDynamicResource(DynamicCodeResource.class);
component.removeDynamicResource(DynamicStyleSheetResource.class);
component.removeDynamicResource(DynamicScriptResource.class);
component.clearHeaders();
}
public void write(final Device device, final SComponent _c)
throws IOException {
if (!_c.isVisible()) return;
_c.fireRenderEvent(SComponent.START_RENDERING);
final SFrame component = (SFrame) _c;
Browser browser = SessionManager.getSession().getUserAgent();
SFrame frame = (SFrame) component;
String language = SessionManager.getSession().getLocale().getLanguage();
String title = frame.getTitle();
List headers = frame.headers();
String encoding = SessionManager.getSession().getCharacterEncoding();
/**
* We need to put IE6 into quirks mode
* for box model compatibility. (border-box).
* For that we make use of a comment in the first line.
* This is a known bug in IE6
*/
if (BrowserType.IE.equals(browser.getBrowserType())) {
if (browser.getMajorVersion() == 6) {
device.print("<!-- IE6 quirks mode switch -->\n");
}
}
if (renderXmlDeclaration == null || renderXmlDeclaration.booleanValue()) {
device.print("<?xml version=\"1.0\" encoding=\"");
Utils.write(device, encoding);
device.print("\"?>\n");
}
Utils.writeRaw(device, documentType);
device.print("\n");
device.print("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"");
Utils.write(device, language);
device.print("\" lang=\"");
Utils.write(device, language);
- device.print("\" />\n");
+ device.print("\">\n");
/* Insert version and compile time.
* Since the Version Class is generated on compile time, build errors
* in SDK's are quite normal. Just run the Version.java ant task.
*/
device.print("<!-- This is wingS (http://www.j-wings.org) version ");
device.print(Version.getVersion());
device.print(" (Build date: ");
device.print(Version.getCompileTime());
device.print(") -->\n");
device.print("<head>");
if (title != null) {
device.print("<title>");
Utils.write(device, title);
device.print("</title>\n");
}
device.print("<meta http-equiv=\"Content-type\" content=\"text/html; charset=");
Utils.write(device, encoding);
device.print("\"/>\n");
for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
Object next = iterator.next();
if (next instanceof Renderable) {
((Renderable) next).write(device);
} else {
Utils.write(device, next.toString());
}
device.print("\n");
}
SComponent focus = frame.getFocus();
Object lastFocus = frame.getClientProperty("focus");
if (focus != lastFocus) {
if (lastFocus != null) {
ScriptListener[] scriptListeners = frame.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof FocusScriptListener)
component.removeScriptListener(scriptListener);
}
}
if (focus != null) {
FocusScriptListener listener = new FocusScriptListener("onload", "requestFocus('" + focus.getName() + "')");
frame.addScriptListener(listener);
}
frame.putClientProperty("focus", focus);
}
// let ie understand hover css styles on elements other than anchors
if (BrowserType.IE.equals(browser.getBrowserType())) {
// externalize hover behavior
final String classPath = (String)SessionManager.getSession().getCGManager().getObject("Behaviors.ieHover", String.class);
ClasspathResource res = new ClasspathResource(classPath, "text/x-component");
String behaviorUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
device.print("<style type=\"text/css\" media=\"screen\">\n");
device.print("body{behavior:url(");
device.print(behaviorUrl);
device.print(");}\n");
device.print("</style>\n");
}
// TODO: move this to a dynamic script resource
SToolTipManager toolTipManager = component.getSession().getToolTipManager();
device
.print("<script type=\"text/javascript\">\n")
.print("domTT_addPredefined('default', 'caption', false");
if (toolTipManager.isFollowMouse())
device.print(", 'trail', true");
device.print(", 'delay', ").print(toolTipManager.getInitialDelay());
device.print(", 'lifetime', ").print(toolTipManager.getDismissDelay());
device
.print(");\n")
.print("</script>\n");
device.print("</head>\n");
device.print("<body");
Utils.optAttribute(device, "id", frame.getName());
Utils.optAttribute(device, "class", frame.getStyle());
Utils.writeEvents(device, frame);
device.print(">\n");
if (frame.isVisible()) {
frame.getLayout().write(device);
device.print("\n");
// now add all menus
Iterator iter = frame.getMenus().iterator();
while (iter.hasNext()) {
SComponent menu = (SComponent)iter.next();
menu.write(device);
}
}
device.print("\n</body></html>\n");
_c.fireRenderEvent(SComponent.DONE_RENDERING);
}
public String getDocumentType() {
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
/**
* @return The current rendered DOCTYPE of this document. {@link #STRICT_DOCTYPE}
*/
public Boolean getRenderXmlDeclaration() {
return renderXmlDeclaration;
}
public void setRenderXmlDeclaration(Boolean renderXmlDeclaration) {
this.renderXmlDeclaration = renderXmlDeclaration;
}
public CSSSelector mapSelector(SComponent addressedComponent, CSSSelector selector) {
// Default: Do not map/modify the passed CSS selector.
return selector;
}
}
| true | true | public void write(final Device device, final SComponent _c)
throws IOException {
if (!_c.isVisible()) return;
_c.fireRenderEvent(SComponent.START_RENDERING);
final SFrame component = (SFrame) _c;
Browser browser = SessionManager.getSession().getUserAgent();
SFrame frame = (SFrame) component;
String language = SessionManager.getSession().getLocale().getLanguage();
String title = frame.getTitle();
List headers = frame.headers();
String encoding = SessionManager.getSession().getCharacterEncoding();
/**
* We need to put IE6 into quirks mode
* for box model compatibility. (border-box).
* For that we make use of a comment in the first line.
* This is a known bug in IE6
*/
if (BrowserType.IE.equals(browser.getBrowserType())) {
if (browser.getMajorVersion() == 6) {
device.print("<!-- IE6 quirks mode switch -->\n");
}
}
if (renderXmlDeclaration == null || renderXmlDeclaration.booleanValue()) {
device.print("<?xml version=\"1.0\" encoding=\"");
Utils.write(device, encoding);
device.print("\"?>\n");
}
Utils.writeRaw(device, documentType);
device.print("\n");
device.print("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"");
Utils.write(device, language);
device.print("\" lang=\"");
Utils.write(device, language);
device.print("\" />\n");
/* Insert version and compile time.
* Since the Version Class is generated on compile time, build errors
* in SDK's are quite normal. Just run the Version.java ant task.
*/
device.print("<!-- This is wingS (http://www.j-wings.org) version ");
device.print(Version.getVersion());
device.print(" (Build date: ");
device.print(Version.getCompileTime());
device.print(") -->\n");
device.print("<head>");
if (title != null) {
device.print("<title>");
Utils.write(device, title);
device.print("</title>\n");
}
device.print("<meta http-equiv=\"Content-type\" content=\"text/html; charset=");
Utils.write(device, encoding);
device.print("\"/>\n");
for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
Object next = iterator.next();
if (next instanceof Renderable) {
((Renderable) next).write(device);
} else {
Utils.write(device, next.toString());
}
device.print("\n");
}
SComponent focus = frame.getFocus();
Object lastFocus = frame.getClientProperty("focus");
if (focus != lastFocus) {
if (lastFocus != null) {
ScriptListener[] scriptListeners = frame.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof FocusScriptListener)
component.removeScriptListener(scriptListener);
}
}
if (focus != null) {
FocusScriptListener listener = new FocusScriptListener("onload", "requestFocus('" + focus.getName() + "')");
frame.addScriptListener(listener);
}
frame.putClientProperty("focus", focus);
}
// let ie understand hover css styles on elements other than anchors
if (BrowserType.IE.equals(browser.getBrowserType())) {
// externalize hover behavior
final String classPath = (String)SessionManager.getSession().getCGManager().getObject("Behaviors.ieHover", String.class);
ClasspathResource res = new ClasspathResource(classPath, "text/x-component");
String behaviorUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
device.print("<style type=\"text/css\" media=\"screen\">\n");
device.print("body{behavior:url(");
device.print(behaviorUrl);
device.print(");}\n");
device.print("</style>\n");
}
// TODO: move this to a dynamic script resource
SToolTipManager toolTipManager = component.getSession().getToolTipManager();
device
.print("<script type=\"text/javascript\">\n")
.print("domTT_addPredefined('default', 'caption', false");
if (toolTipManager.isFollowMouse())
device.print(", 'trail', true");
device.print(", 'delay', ").print(toolTipManager.getInitialDelay());
device.print(", 'lifetime', ").print(toolTipManager.getDismissDelay());
device
.print(");\n")
.print("</script>\n");
device.print("</head>\n");
device.print("<body");
Utils.optAttribute(device, "id", frame.getName());
Utils.optAttribute(device, "class", frame.getStyle());
Utils.writeEvents(device, frame);
device.print(">\n");
if (frame.isVisible()) {
frame.getLayout().write(device);
device.print("\n");
// now add all menus
Iterator iter = frame.getMenus().iterator();
while (iter.hasNext()) {
SComponent menu = (SComponent)iter.next();
menu.write(device);
}
}
device.print("\n</body></html>\n");
_c.fireRenderEvent(SComponent.DONE_RENDERING);
}
| public void write(final Device device, final SComponent _c)
throws IOException {
if (!_c.isVisible()) return;
_c.fireRenderEvent(SComponent.START_RENDERING);
final SFrame component = (SFrame) _c;
Browser browser = SessionManager.getSession().getUserAgent();
SFrame frame = (SFrame) component;
String language = SessionManager.getSession().getLocale().getLanguage();
String title = frame.getTitle();
List headers = frame.headers();
String encoding = SessionManager.getSession().getCharacterEncoding();
/**
* We need to put IE6 into quirks mode
* for box model compatibility. (border-box).
* For that we make use of a comment in the first line.
* This is a known bug in IE6
*/
if (BrowserType.IE.equals(browser.getBrowserType())) {
if (browser.getMajorVersion() == 6) {
device.print("<!-- IE6 quirks mode switch -->\n");
}
}
if (renderXmlDeclaration == null || renderXmlDeclaration.booleanValue()) {
device.print("<?xml version=\"1.0\" encoding=\"");
Utils.write(device, encoding);
device.print("\"?>\n");
}
Utils.writeRaw(device, documentType);
device.print("\n");
device.print("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"");
Utils.write(device, language);
device.print("\" lang=\"");
Utils.write(device, language);
device.print("\">\n");
/* Insert version and compile time.
* Since the Version Class is generated on compile time, build errors
* in SDK's are quite normal. Just run the Version.java ant task.
*/
device.print("<!-- This is wingS (http://www.j-wings.org) version ");
device.print(Version.getVersion());
device.print(" (Build date: ");
device.print(Version.getCompileTime());
device.print(") -->\n");
device.print("<head>");
if (title != null) {
device.print("<title>");
Utils.write(device, title);
device.print("</title>\n");
}
device.print("<meta http-equiv=\"Content-type\" content=\"text/html; charset=");
Utils.write(device, encoding);
device.print("\"/>\n");
for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
Object next = iterator.next();
if (next instanceof Renderable) {
((Renderable) next).write(device);
} else {
Utils.write(device, next.toString());
}
device.print("\n");
}
SComponent focus = frame.getFocus();
Object lastFocus = frame.getClientProperty("focus");
if (focus != lastFocus) {
if (lastFocus != null) {
ScriptListener[] scriptListeners = frame.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof FocusScriptListener)
component.removeScriptListener(scriptListener);
}
}
if (focus != null) {
FocusScriptListener listener = new FocusScriptListener("onload", "requestFocus('" + focus.getName() + "')");
frame.addScriptListener(listener);
}
frame.putClientProperty("focus", focus);
}
// let ie understand hover css styles on elements other than anchors
if (BrowserType.IE.equals(browser.getBrowserType())) {
// externalize hover behavior
final String classPath = (String)SessionManager.getSession().getCGManager().getObject("Behaviors.ieHover", String.class);
ClasspathResource res = new ClasspathResource(classPath, "text/x-component");
String behaviorUrl = SessionManager.getSession().getExternalizeManager().externalize(res, ExternalizeManager.GLOBAL);
device.print("<style type=\"text/css\" media=\"screen\">\n");
device.print("body{behavior:url(");
device.print(behaviorUrl);
device.print(");}\n");
device.print("</style>\n");
}
// TODO: move this to a dynamic script resource
SToolTipManager toolTipManager = component.getSession().getToolTipManager();
device
.print("<script type=\"text/javascript\">\n")
.print("domTT_addPredefined('default', 'caption', false");
if (toolTipManager.isFollowMouse())
device.print(", 'trail', true");
device.print(", 'delay', ").print(toolTipManager.getInitialDelay());
device.print(", 'lifetime', ").print(toolTipManager.getDismissDelay());
device
.print(");\n")
.print("</script>\n");
device.print("</head>\n");
device.print("<body");
Utils.optAttribute(device, "id", frame.getName());
Utils.optAttribute(device, "class", frame.getStyle());
Utils.writeEvents(device, frame);
device.print(">\n");
if (frame.isVisible()) {
frame.getLayout().write(device);
device.print("\n");
// now add all menus
Iterator iter = frame.getMenus().iterator();
while (iter.hasNext()) {
SComponent menu = (SComponent)iter.next();
menu.write(device);
}
}
device.print("\n</body></html>\n");
_c.fireRenderEvent(SComponent.DONE_RENDERING);
}
|
diff --git a/src/com/googlecode/jmeter/plugins/webdriver/sampler/gui/WebDriverSamplerGui.java b/src/com/googlecode/jmeter/plugins/webdriver/sampler/gui/WebDriverSamplerGui.java
index 2a2fb60a..65f275c6 100644
--- a/src/com/googlecode/jmeter/plugins/webdriver/sampler/gui/WebDriverSamplerGui.java
+++ b/src/com/googlecode/jmeter/plugins/webdriver/sampler/gui/WebDriverSamplerGui.java
@@ -1,121 +1,121 @@
package com.googlecode.jmeter.plugins.webdriver.sampler.gui;
import com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler;
import jsyntaxpane.DefaultSyntaxKit;
import kg.apc.jmeter.JMeterPluginsUtils;
import org.apache.jmeter.samplers.gui.AbstractSamplerGui;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import javax.swing.*;
import java.awt.*;
public class WebDriverSamplerGui extends AbstractSamplerGui {
private static final long serialVersionUID = 100L;
private static final Logger LOGGER = LoggingManager.getLoggerForClass();
static {
DefaultSyntaxKit.initKit();
}
JTextField parameters;
JEditorPane script;
public WebDriverSamplerGui() {
createGui();
}
@Override
public String getStaticLabel() {
return JMeterPluginsUtils.prefixLabel("Web Driver Sampler");
}
@Override
public String getLabelResource() {
return getClass().getCanonicalName();
}
@Override
public void configure(TestElement element) {
script.setText(element.getPropertyAsString(WebDriverSampler.SCRIPT));
parameters.setText(element.getPropertyAsString(WebDriverSampler.PARAMETERS));
super.configure(element);
}
@Override
public TestElement createTestElement() {
WebDriverSampler sampler = new WebDriverSampler();
modifyTestElement(sampler);
return sampler;
}
@Override
public void modifyTestElement(TestElement element) {
element.clear();
this.configureTestElement(element);
element.setProperty(WebDriverSampler.SCRIPT, script.getText());
element.setProperty(WebDriverSampler.PARAMETERS, parameters.getText());
}
@Override
public void clearGui() {
super.clearGui();
parameters.setText(""); //$NON-NLS-1$
script.setText(""); //$NON-NLS-1$
}
private void createGui() {
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
Box box = Box.createVerticalBox();
box.add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), "WebDriverSampler"));
box.add(createParameterPanel());
add(box, BorderLayout.NORTH);
JPanel panel = createScriptPanel();
add(panel, BorderLayout.CENTER);
// Don't let the input field shrink too much
add(Box.createVerticalStrut(panel.getPreferredSize().height),
BorderLayout.WEST);
}
private JPanel createParameterPanel() {
final JLabel label = new JLabel("Parameters (-> String Parameters and String[] args)");
parameters = new JTextField(10);
parameters.setName(WebDriverSampler.PARAMETERS);
label.setLabelFor(parameters);
final JPanel parameterPanel = new JPanel(new BorderLayout(5, 0));
parameterPanel.add(label, BorderLayout.WEST);
parameterPanel.add(parameters, BorderLayout.CENTER);
return parameterPanel;
}
private JPanel createScriptPanel() {
script = new JEditorPane();
final JScrollPane scrollPane = new JScrollPane(script);
script.setContentType("text/javascript");
script.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
final JLabel label = new JLabel("Script (see below for variables that are defined)"); // $NON-NLS-1$
label.setLabelFor(script);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(label, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
- final JTextArea explain = new JTextArea("The following variables are defined for the script\\:\\nLabel, Parameters, args, log, Browser, SampleResult, OUT");
+ final JTextArea explain = new JTextArea("The following variables are defined for the script: Label, Parameters, args, log, Browser, SampleResult, OUT");
explain.setLineWrap(true);
explain.setEditable(false);
explain.setBackground(this.getBackground());
panel.add(explain, BorderLayout.SOUTH);
return panel;
}
}
| true | true | private JPanel createScriptPanel() {
script = new JEditorPane();
final JScrollPane scrollPane = new JScrollPane(script);
script.setContentType("text/javascript");
script.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
final JLabel label = new JLabel("Script (see below for variables that are defined)"); // $NON-NLS-1$
label.setLabelFor(script);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(label, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
final JTextArea explain = new JTextArea("The following variables are defined for the script\\:\\nLabel, Parameters, args, log, Browser, SampleResult, OUT");
explain.setLineWrap(true);
explain.setEditable(false);
explain.setBackground(this.getBackground());
panel.add(explain, BorderLayout.SOUTH);
return panel;
}
| private JPanel createScriptPanel() {
script = new JEditorPane();
final JScrollPane scrollPane = new JScrollPane(script);
script.setContentType("text/javascript");
script.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
final JLabel label = new JLabel("Script (see below for variables that are defined)"); // $NON-NLS-1$
label.setLabelFor(script);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(label, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
final JTextArea explain = new JTextArea("The following variables are defined for the script: Label, Parameters, args, log, Browser, SampleResult, OUT");
explain.setLineWrap(true);
explain.setEditable(false);
explain.setBackground(this.getBackground());
panel.add(explain, BorderLayout.SOUTH);
return panel;
}
|
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java b/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
index 79a91e90..92ab7ef5 100644
--- a/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
+++ b/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
@@ -1,685 +1,685 @@
package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.loader.MetamodelGenerator;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
/** A convenience class to help with the handling of certain type declarations. */
public class TypeUtils {
final TypeDeclaration tuple;
final TypeDeclaration iterable;
final TypeDeclaration sequential;
final TypeDeclaration numeric;
final TypeDeclaration _integer;
final TypeDeclaration _float;
final TypeDeclaration _null;
final TypeDeclaration anything;
final TypeDeclaration callable;
final TypeDeclaration empty;
final TypeDeclaration metaClass;
TypeUtils(Module languageModule) {
com.redhat.ceylon.compiler.typechecker.model.Package pkg = languageModule.getPackage("ceylon.language");
tuple = (TypeDeclaration)pkg.getMember("Tuple", null, false);
iterable = (TypeDeclaration)pkg.getMember("Iterable", null, false);
sequential = (TypeDeclaration)pkg.getMember("Sequential", null, false);
numeric = (TypeDeclaration)pkg.getMember("Numeric", null, false);
_integer = (TypeDeclaration)pkg.getMember("Integer", null, false);
_float = (TypeDeclaration)pkg.getMember("Float", null, false);
_null = (TypeDeclaration)pkg.getMember("Null", null, false);
anything = (TypeDeclaration)pkg.getMember("Anything", null, false);
callable = (TypeDeclaration)pkg.getMember("Callable", null, false);
empty = (TypeDeclaration)pkg.getMember("Empty", null, false);
pkg = languageModule.getPackage("ceylon.language.model");
metaClass = (TypeDeclaration)pkg.getMember("Class", null, false);
}
/** Prints the type arguments, usually for their reification. */
public static void printTypeArguments(Node node, Map<TypeParameter,ProducedType> targs, GenerateJsVisitor gen) {
gen.out("{");
boolean first = true;
for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) {
if (first) {
first = false;
} else {
gen.out(",");
}
gen.out(e.getKey().getName(), ":");
final ProducedType pt = e.getValue();
if (pt == null) {
gen.out("'", e.getKey().getName(), "'");
continue;
}
final TypeDeclaration d = pt.getDeclaration();
boolean composite = d instanceof UnionType || d instanceof IntersectionType;
boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty();
boolean closeBracket = false;
if (composite) {
outputTypeList(node, d, gen, true);
} else if (d instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)d, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(
gen.isImported(node == null ? null : node.getUnit().getPackage(), pt.getDeclaration()),
pt, gen);
closeBracket = true;
}
if (hasParams) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
if (closeBracket) {
gen.out("}");
}
}
gen.out("}");
}
static void outputQualifiedTypename(final boolean imported, ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration t = pt.getDeclaration();
final String qname = t.getQualifiedNameString();
if (qname.equals("ceylon.language::Nothing")) {
//Hack in the model means hack here as well
gen.out(GenerateJsVisitor.getClAlias(), "Nothing");
} else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) {
gen.out(GenerateJsVisitor.getClAlias(), "Null");
} else if (pt.isUnknown()) {
gen.out(GenerateJsVisitor.getClAlias(), "Anything");
} else {
if (t.isAlias()) {
t = t.getExtendedTypeDeclaration();
}
boolean qual = false;
if (t.getScope() instanceof ClassOrInterface) {
List<ClassOrInterface> parents = new ArrayList<>();
ClassOrInterface parent = (ClassOrInterface)t.getScope();
parents.add(0, parent);
while (parent.getScope() instanceof ClassOrInterface) {
parent = (ClassOrInterface)parent.getScope();
parents.add(0, parent);
}
qual = true;
for (ClassOrInterface p : parents) {
gen.out(gen.getNames().name(p), ".");
}
} else if (imported) {
//This wasn't needed but now we seem to get imported decls with no package when compiling ceylon.language.model types
final String modAlias = gen.getNames().moduleAlias(t.getUnit().getPackage().getModule());
if (modAlias != null && !modAlias.isEmpty()) {
gen.out(modAlias, ".");
}
qual = true;
}
String tname = gen.getNames().name(t);
if (!qual && isReservedTypename(tname)) {
gen.out(tname, "$");
} else {
gen.out(tname);
}
}
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void typeNameOrList(Node node, ProducedType pt, GenerateJsVisitor gen, boolean typeReferences) {
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputTypeList(node, type, gen, typeReferences);
} else if (typeReferences) {
if (type instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)type, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen);
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
gen.out("}");
}
} else {
gen.out("'", type.getQualifiedNameString(), "'");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputTypeList(Node node, TypeDeclaration type, GenerateJsVisitor gen, boolean typeReferences) {
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
typeNameOrList(node, t, gen, typeReferences);
first = false;
}
gen.out("]}");
}
/** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */
static void resolveTypeParameter(Node node, TypeParameter tp, GenerateJsVisitor gen) {
Scope parent = node.getScope();
while (parent != null && parent != tp.getContainer()) {
parent = parent.getScope();
}
if (tp.getContainer() instanceof ClassOrInterface) {
if (parent == tp.getContainer()) {
if (((ClassOrInterface)tp.getContainer()).isAlias()) {
//when resolving for aliases we just take the type arguments from the alias call
gen.out("$$targs$$.", tp.getName());
} else {
gen.self((ClassOrInterface)tp.getContainer());
gen.out(".$$targs$$.", tp.getName());
}
} else {
//This can happen in expressions such as Singleton(n) when n is dynamic
gen.out("{/*NO PARENT*/t:", GenerateJsVisitor.getClAlias(), "Anything}");
}
} else {
//it has to be a method, right?
//We need to find the index of the parameter where the argument occurs
//...and it could be null...
int plistCount = -1;
ProducedType type = null;
for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator();
type == null && iter0.hasNext();) {
plistCount++;
for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator();
type == null && iter1.hasNext();) {
if (type == null) {
type = typeContainsTypeParameter(iter1.next().getType(), tp);
}
}
}
//The ProducedType that we find corresponds to a parameter, whose type can be:
//A type parameter in the method, in which case we just use the argument's type (may be null)
//A component of a union/intersection type, in which case we just use the argument's type (may be null)
//A type argument of the argument's type, in which case we must get the reified generic from the argument
if (tp.getContainer() == parent) {
gen.out("$$$mptypes.", tp.getName());
} else {
gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#",
tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "'");
}
}
}
static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) {
TypeDeclaration d = td.getDeclaration();
if (d == tp) {
return td;
} else if (d instanceof UnionType || d instanceof IntersectionType) {
List<ProducedType> comps = td.getCaseTypes();
if (comps == null) comps = td.getSupertypes();
for (ProducedType sub : comps) {
td = typeContainsTypeParameter(sub, tp);
if (td != null) {
return td;
}
}
} else if (d instanceof ClassOrInterface) {
for (ProducedType sub : td.getTypeArgumentList()) {
if (typeContainsTypeParameter(sub, tp) != null) {
return td;
}
}
}
return null;
}
static boolean isReservedTypename(String typeName) {
return JsCompiler.compilingLanguageModule && (typeName.equals("Object") || typeName.equals("Number")
|| typeName.equals("Array")) || typeName.equals("String") || typeName.equals("Boolean");
}
/** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */
static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) {
if (pt.getDeclaration().equals(d)) {
return pt;
}
List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes();
for (ProducedType t : list) {
if (t.getDeclaration().equals(d)) {
return t;
}
}
return null;
}
static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) {
if (params != null && targs != null && params.size() == targs.size()) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
for (int i = 0; i < targs.size(); i++) {
r.put(params.get(i), targs.get(i));
}
return r;
}
return null;
}
Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
r.put(iterable.getTypeParameters().get(0), pt);
r.put(iterable.getTypeParameters().get(1), _null.getType());
return r;
}
static boolean isUnknown(ProducedType pt) {
return pt == null || pt.isUnknown();
}
static boolean isUnknown(Parameter param) {
return param == null || isUnknown(param.getType());
}
static boolean isUnknown(Declaration d) {
return d == null || d.getQualifiedNameString().equals("UnknownType");
}
/** Generates the code to throw an Exception if a dynamic object is not of the specified type. */
static void generateDynamicCheck(Tree.Term term, final ProducedType t, final GenerateJsVisitor gen) {
String tmp = gen.getNames().createTempVariable();
gen.out("(", tmp, "=");
term.visit(gen);
gen.out(",", GenerateJsVisitor.getClAlias(), "isOfType(", tmp, ",");
TypeUtils.typeNameOrList(term, t, gen, true);
gen.out(")?", tmp, ":");
gen.generateThrow("dynamic objects cannot be used here", term);
gen.out(")");
}
static void encodeParameterListForRuntime(ParameterList plist, GenerateJsVisitor gen) {
boolean first = true;
gen.out("[");
for (Parameter p : plist.getParameters()) {
if (first) first=false; else gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getName(), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
if (p.isSequenced()) {
gen.out("seq:1,");
}
if (p.isDefaulted()) {
gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,");
}
gen.out(MetamodelGenerator.KEY_TYPE, ":");
metamodelTypeNameOrList(gen.getCurrentPackage(), p.getType(), gen);
gen.out("}");
}
gen.out("]");
}
/** This method encodes the type parameters of a Tuple (taken from a Callable) in the same way
* as a parameter list for runtime. */
void encodeTupleAsParameterListForRuntime(ProducedType _callable, GenerateJsVisitor gen) {
if (!_callable.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) {
gen.out("[/*WARNING: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]");
return;
}
List<ProducedType> targs = _callable.getTypeArgumentList();
if (targs == null || targs.size() != 2) {
gen.out("[/*WARNING: missing argument types for Callable*/]");
return;
}
ProducedType _tuple = targs.get(1);
gen.out("[");
int pos = 1;
while (!(empty.equals(_tuple.getDeclaration()) || _tuple.getDeclaration() instanceof TypeParameter)) {
if (pos > 1) gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos++), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
gen.out(MetamodelGenerator.KEY_TYPE, ":");
if (tuple.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen);
_tuple = _tuple.getTypeArgumentList().get(2);
} else if (sequential.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(0), gen);
_tuple = _tuple.getTypeArgumentList().get(0);
} else {
System.out.println("WTF? Tuple is actually " + _tuple.getProducedTypeQualifiedName() + ", " + _tuple.getClass().getName());
if (pos > 100) {
System.exit(1);
}
}
gen.out("}");
}
gen.out("]");
}
static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen) {
if (d.getAnnotations() == null || d.getAnnotations().isEmpty()) {
encodeForRuntime(d, gen, null);
} else {
encodeForRuntime(d, gen, new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":function(){return[");
boolean first = true;
for (Annotation a : d.getAnnotations()) {
if (first) first=false; else gen.out(",");
Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false);
if (ad instanceof Method) {
gen.qualify(null, ad);
gen.out(gen.getNames().name(ad), "(");
if (a.getPositionalArguments() == null) {
for (Parameter p : ((Method)ad).getParameterLists().get(0).getParameters()) {
String v = a.getNamedArguments().get(p.getName());
gen.out(v == null ? "undefined" : v);
}
} else {
boolean farg = true;
for (String s : a.getPositionalArguments()) {
if (farg)farg=false; else gen.out(",");
gen.out(s);
}
}
gen.out(")");
} else {
gen.out("null/*MISSING DECLARATION FOR ANNOTATION ", a.getName(), "*/");
}
}
gen.out("];}");
}
});
}
}
/** Output a metamodel map for runtime use. */
static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
final boolean include = annotations != null && !annotations.getAnnotations().isEmpty();
encodeForRuntime(d, gen, include ? new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":");
outputAnnotationsFunction(annotations, gen);
}
} : null);
}
static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
for(TypeParameter tp : tparms) {
boolean comma = false;
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out("'var':'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
- gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
- gen.out(d.getUnit().getPackage().getNameAsString(), "']");
+ //Path to its model
+ gen.out(",d:['", d.getUnit().getPackage().getNameAsString(), "'");
if (d.isToplevel()) {
- gen.out("['", d.getName(), "']");
+ gen.out(",'", d.getName(), "'");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
- gen.out("['", part, "']");
+ gen.out(",'", part, "'");
}
}
- gen.out("};}");
+ gen.out("]};}");
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void metamodelTypeNameOrList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
if (pt == null) {
//In dynamic blocks we sometimes get a null producedType
pt = ((TypeDeclaration)pkg.getModule().getLanguageModule().getDirectPackage(
"ceylon.language").getDirectMember("Anything", null, false)).getType();
}
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputMetamodelTypeList(pkg, pt, gen);
} else if (type instanceof TypeParameter) {
gen.out("'", type.getNameAsString(), "'");
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(pkg, type), pt, gen);
//Type Parameters
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:{");
boolean first = true;
for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) {
if (first) first=false; else gen.out(",");
gen.out(e.getKey().getNameAsString(), ":");
metamodelTypeNameOrList(pkg, e.getValue(), gen);
}
gen.out("}");
}
gen.out("}");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputMetamodelTypeList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration type = pt.getDeclaration();
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
metamodelTypeNameOrList(pkg, t, gen);
first = false;
}
gen.out("]}");
}
ProducedType tupleFromParameters(List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) {
if (params == null || params.isEmpty()) {
return empty.getType();
}
ProducedType tt = empty.getType();
ProducedType et = null;
for (int i = params.size()-1; i>=0; i--) {
com.redhat.ceylon.compiler.typechecker.model.Parameter p = params.get(i);
if (et == null) {
et = p.getType();
} else {
UnionType ut = new UnionType(p.getModel().getUnit());
ArrayList<ProducedType> types = new ArrayList<>();
if (et.getCaseTypes() == null || et.getCaseTypes().isEmpty()) {
types.add(et);
} else {
types.addAll(et.getCaseTypes());
}
types.add(p.getType());
ut.setCaseTypes(types);
et = ut.getType();
}
Map<TypeParameter,ProducedType> args = new HashMap<>();
for (TypeParameter tp : tuple.getTypeParameters()) {
if ("First".equals(tp.getName())) {
args.put(tp, p.getType());
} else if ("Element".equals(tp.getName())) {
args.put(tp, et);
} else if ("Rest".equals(tp.getName())) {
args.put(tp, tt);
}
}
if (i == params.size()-1) {
tt = tuple.getType();
}
tt = tt.substitute(args);
}
return tt;
}
/** Outputs a function that returns the specified annotations, so that they can be loaded lazily. */
static void outputAnnotationsFunction(final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
if (annotations == null || annotations.getAnnotations().isEmpty()) {
gen.out("[]");
} else {
gen.out("function(){return[");
boolean first = true;
for (Tree.Annotation a : annotations.getAnnotations()) {
if (first) first=false; else gen.out(",");
gen.getInvoker().generateInvocation(a);
}
gen.out("];}");
}
}
/** Abstraction for a callback that generates the runtime annotations list as part of the metamodel. */
static interface RuntimeMetamodelAnnotationGenerator {
public void generateAnnotations();
}
}
| false | true | static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
for(TypeParameter tp : tparms) {
boolean comma = false;
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out("'var':'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("};}");
}
| static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
for(TypeParameter tp : tparms) {
boolean comma = false;
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out("'var':'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
//Path to its model
gen.out(",d:['", d.getUnit().getPackage().getNameAsString(), "'");
if (d.isToplevel()) {
gen.out(",'", d.getName(), "'");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out(",'", part, "'");
}
}
gen.out("]};}");
}
|
diff --git a/bundles/org.eclipse.e4.tools.emf.editor3x/src/org/eclipse/e4/tools/emf/editor3x/PDEClassContributionProvider.java b/bundles/org.eclipse.e4.tools.emf.editor3x/src/org/eclipse/e4/tools/emf/editor3x/PDEClassContributionProvider.java
index 76f37692..0fb63750 100644
--- a/bundles/org.eclipse.e4.tools.emf.editor3x/src/org/eclipse/e4/tools/emf/editor3x/PDEClassContributionProvider.java
+++ b/bundles/org.eclipse.e4.tools.emf.editor3x/src/org/eclipse/e4/tools/emf/editor3x/PDEClassContributionProvider.java
@@ -1,157 +1,157 @@
/*******************************************************************************
* Copyright (c) 2010 BestSolution.at 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:
* Tom Schindl <[email protected]> - initial API and implementation
******************************************************************************/
package org.eclipse.e4.tools.emf.editor3x;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.e4.tools.emf.ui.common.IClassContributionProvider;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.TypeNameRequestor;
import org.eclipse.pde.internal.core.util.PDEJavaHelper;
public class PDEClassContributionProvider implements IClassContributionProvider {
private SearchEngine searchEngine;
public PDEClassContributionProvider() {
searchEngine = new SearchEngine();
}
@SuppressWarnings("restriction")
public void findContribution(final Filter filter, final ContributionResultHandler handler) {
System.err.println("Searching for: " + filter.namePattern);
IJavaSearchScope scope = PDEJavaHelper.getSearchScope(filter.project);
char[] packageName = null;
char[] typeName = null;
String currentContent = filter.namePattern;
int index = currentContent.lastIndexOf('.');
if (index == -1) {
// There is no package qualification
// Perform the search only on the type name
typeName = currentContent.toCharArray();
if( currentContent.startsWith("*") ) {
typeName = "".toCharArray();
if( ! currentContent.endsWith("*") ) {
currentContent += "*";
}
packageName = currentContent.toCharArray();
}
} else if ((index + 1) == currentContent.length()) {
// There is a package qualification and the last character is a
// dot
// Perform the search for all types under the given package
// Pattern for all types
typeName = "".toCharArray(); //$NON-NLS-1$
// Package name without the trailing dot
packageName = currentContent.substring(0, index).toCharArray();
} else {
// There is a package qualification, followed by a dot, and
// a type fragment
// Type name without the package qualification
typeName = currentContent.substring(index + 1).toCharArray();
// Package name without the trailing dot
packageName = currentContent.substring(0, index).toCharArray();
}
// char[] packageName = "at.bestsolution.e4.handlers".toCharArray();
// char[] typeName = "*".toCharArray();
TypeNameRequestor req = new TypeNameRequestor() {
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
// Accept search results from the JDT SearchEngine
String cName = new String(simpleTypeName);
String pName = new String(packageName);
// String label = cName + " - " + pName; //$NON-NLS-1$
- String content = pName + "." + cName; //$NON-NLS-1$
+ String content = pName.length() == 0 ? cName : pName + "." + cName; //$NON-NLS-1$
// System.err.println("Found: " + label + " => " + pName + " => " + path);
IResource resource = filter.project.getWorkspace().getRoot().findMember(path);
if( resource != null ) {
IProject project = resource.getProject();
IFile f = project.getFile("/META-INF/MANIFEST.MF");
if( f != null && f.exists() ) {
BufferedReader r = null;
try {
InputStream s = f.getContents();
r = new BufferedReader(new InputStreamReader(s));
String line;
while( (line = r.readLine()) != null ) {
if( line.startsWith("Bundle-SymbolicName:") ) {
int start = line.indexOf(':');
int end = line.indexOf(';');
if( end == -1 ) {
end = line.length();
}
ContributionData data = new ContributionData(line.substring(start+1,end).trim(), content, "Java", null);
handler.result(data);
break;
}
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if( r != null ) {
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//Image image = (Flags.isInterface(modifiers)) ? PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_INTERFACE) : PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS);
//addProposalToCollection(c, startOffset, length, label, content, image);
}
};
try {
searchEngine.searchAllTypeNames(
packageName,
SearchPattern.R_PATTERN_MATCH,
typeName,
SearchPattern.R_PREFIX_MATCH,
IJavaSearchConstants.CLASS,
scope,
req,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public void findContribution(final Filter filter, final ContributionResultHandler handler) {
System.err.println("Searching for: " + filter.namePattern);
IJavaSearchScope scope = PDEJavaHelper.getSearchScope(filter.project);
char[] packageName = null;
char[] typeName = null;
String currentContent = filter.namePattern;
int index = currentContent.lastIndexOf('.');
if (index == -1) {
// There is no package qualification
// Perform the search only on the type name
typeName = currentContent.toCharArray();
if( currentContent.startsWith("*") ) {
typeName = "".toCharArray();
if( ! currentContent.endsWith("*") ) {
currentContent += "*";
}
packageName = currentContent.toCharArray();
}
} else if ((index + 1) == currentContent.length()) {
// There is a package qualification and the last character is a
// dot
// Perform the search for all types under the given package
// Pattern for all types
typeName = "".toCharArray(); //$NON-NLS-1$
// Package name without the trailing dot
packageName = currentContent.substring(0, index).toCharArray();
} else {
// There is a package qualification, followed by a dot, and
// a type fragment
// Type name without the package qualification
typeName = currentContent.substring(index + 1).toCharArray();
// Package name without the trailing dot
packageName = currentContent.substring(0, index).toCharArray();
}
// char[] packageName = "at.bestsolution.e4.handlers".toCharArray();
// char[] typeName = "*".toCharArray();
TypeNameRequestor req = new TypeNameRequestor() {
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
// Accept search results from the JDT SearchEngine
String cName = new String(simpleTypeName);
String pName = new String(packageName);
// String label = cName + " - " + pName; //$NON-NLS-1$
String content = pName + "." + cName; //$NON-NLS-1$
// System.err.println("Found: " + label + " => " + pName + " => " + path);
IResource resource = filter.project.getWorkspace().getRoot().findMember(path);
if( resource != null ) {
IProject project = resource.getProject();
IFile f = project.getFile("/META-INF/MANIFEST.MF");
if( f != null && f.exists() ) {
BufferedReader r = null;
try {
InputStream s = f.getContents();
r = new BufferedReader(new InputStreamReader(s));
String line;
while( (line = r.readLine()) != null ) {
if( line.startsWith("Bundle-SymbolicName:") ) {
int start = line.indexOf(':');
int end = line.indexOf(';');
if( end == -1 ) {
end = line.length();
}
ContributionData data = new ContributionData(line.substring(start+1,end).trim(), content, "Java", null);
handler.result(data);
break;
}
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if( r != null ) {
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//Image image = (Flags.isInterface(modifiers)) ? PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_INTERFACE) : PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS);
//addProposalToCollection(c, startOffset, length, label, content, image);
}
};
try {
searchEngine.searchAllTypeNames(
packageName,
SearchPattern.R_PATTERN_MATCH,
typeName,
SearchPattern.R_PREFIX_MATCH,
IJavaSearchConstants.CLASS,
scope,
req,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void findContribution(final Filter filter, final ContributionResultHandler handler) {
System.err.println("Searching for: " + filter.namePattern);
IJavaSearchScope scope = PDEJavaHelper.getSearchScope(filter.project);
char[] packageName = null;
char[] typeName = null;
String currentContent = filter.namePattern;
int index = currentContent.lastIndexOf('.');
if (index == -1) {
// There is no package qualification
// Perform the search only on the type name
typeName = currentContent.toCharArray();
if( currentContent.startsWith("*") ) {
typeName = "".toCharArray();
if( ! currentContent.endsWith("*") ) {
currentContent += "*";
}
packageName = currentContent.toCharArray();
}
} else if ((index + 1) == currentContent.length()) {
// There is a package qualification and the last character is a
// dot
// Perform the search for all types under the given package
// Pattern for all types
typeName = "".toCharArray(); //$NON-NLS-1$
// Package name without the trailing dot
packageName = currentContent.substring(0, index).toCharArray();
} else {
// There is a package qualification, followed by a dot, and
// a type fragment
// Type name without the package qualification
typeName = currentContent.substring(index + 1).toCharArray();
// Package name without the trailing dot
packageName = currentContent.substring(0, index).toCharArray();
}
// char[] packageName = "at.bestsolution.e4.handlers".toCharArray();
// char[] typeName = "*".toCharArray();
TypeNameRequestor req = new TypeNameRequestor() {
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
// Accept search results from the JDT SearchEngine
String cName = new String(simpleTypeName);
String pName = new String(packageName);
// String label = cName + " - " + pName; //$NON-NLS-1$
String content = pName.length() == 0 ? cName : pName + "." + cName; //$NON-NLS-1$
// System.err.println("Found: " + label + " => " + pName + " => " + path);
IResource resource = filter.project.getWorkspace().getRoot().findMember(path);
if( resource != null ) {
IProject project = resource.getProject();
IFile f = project.getFile("/META-INF/MANIFEST.MF");
if( f != null && f.exists() ) {
BufferedReader r = null;
try {
InputStream s = f.getContents();
r = new BufferedReader(new InputStreamReader(s));
String line;
while( (line = r.readLine()) != null ) {
if( line.startsWith("Bundle-SymbolicName:") ) {
int start = line.indexOf(':');
int end = line.indexOf(';');
if( end == -1 ) {
end = line.length();
}
ContributionData data = new ContributionData(line.substring(start+1,end).trim(), content, "Java", null);
handler.result(data);
break;
}
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if( r != null ) {
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//Image image = (Flags.isInterface(modifiers)) ? PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_INTERFACE) : PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS);
//addProposalToCollection(c, startOffset, length, label, content, image);
}
};
try {
searchEngine.searchAllTypeNames(
packageName,
SearchPattern.R_PATTERN_MATCH,
typeName,
SearchPattern.R_PREFIX_MATCH,
IJavaSearchConstants.CLASS,
scope,
req,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/de/thiemonagel/vegdroid/EntryActivity.java b/src/de/thiemonagel/vegdroid/EntryActivity.java
index 98e7ede..01eac01 100644
--- a/src/de/thiemonagel/vegdroid/EntryActivity.java
+++ b/src/de/thiemonagel/vegdroid/EntryActivity.java
@@ -1,113 +1,114 @@
package de.thiemonagel.vegdroid;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
public class EntryActivity extends Activity {
private Venue mVenue;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: // no idea what this is for
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.menu_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
Intent i = getIntent();
int VenueId = i.getIntExtra( "VenueId", -1 );
mVenue = Global.getInstance(this).venues.get(VenueId);
if ( mVenue == null ) {
// TODO: implement error message
+ return;
}
{
TextView tv = (TextView) findViewById(R.id.name);
tv.setText( mVenue.name );
}{
RatingBar rb = (RatingBar) findViewById(R.id.ratingBar2);
rb.setRating( mVenue.rating );
}{
// TextView tv = (TextView) findViewById(R.id.veg_level_description);
// tv.setText( mVenue.get("veg_level_description") );
}{
Button but = (Button) findViewById(R.id.phone);
if ( mVenue.phone.equals("") )
but.setVisibility( View.GONE );
else
but.setText( "Dial " + mVenue.phone );
}{
Button but = (Button) findViewById(R.id.website);
if ( mVenue.website.equals("") )
but.setVisibility( View.GONE );
else
//but.setText( "Visit " + fData.get("website") );
but.setText( "Visit web site" );
}{
TextView tv = (TextView) findViewById(R.id.address);
String addressBlock = mVenue.locHtml();
if ( addressBlock.equals("") )
tv.setVisibility( View.GONE );
else
tv.setText( Html.fromHtml(addressBlock) );
}{
TextView tv = (TextView) findViewById(R.id.long_description);
tv.setMovementMethod( LinkMovementMethod.getInstance() );
if ( mVenue.longDescription.equals("") )
tv.setVisibility( View.GONE );
else
tv.setText( Html.fromHtml( mVenue.longDescription ) );
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_entry, menu);
return true;
}
public void clickMap( View view ) {
// the name of the venue is not included in the query string because
// it seems to cause problems when Google isn't aware of the specific venue
String uri = "geo:0,0?q=" + mVenue.locString();
Intent intent = new Intent( Intent.ACTION_VIEW );
intent.setData( Uri.parse(uri) );
startActivity(intent);
}
public void clickPhone( View view ) {
String uri = "tel:" + mVenue.phone;
Intent intent = new Intent( Intent.ACTION_DIAL );
intent.setData( Uri.parse(uri) );
startActivity(intent);
}
public void clickWebsite( View view ) {
Intent intent = new Intent( Intent.ACTION_VIEW );
intent.setData( Uri.parse(mVenue.website) );
startActivity(intent);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
Intent i = getIntent();
int VenueId = i.getIntExtra( "VenueId", -1 );
mVenue = Global.getInstance(this).venues.get(VenueId);
if ( mVenue == null ) {
// TODO: implement error message
}
{
TextView tv = (TextView) findViewById(R.id.name);
tv.setText( mVenue.name );
}{
RatingBar rb = (RatingBar) findViewById(R.id.ratingBar2);
rb.setRating( mVenue.rating );
}{
// TextView tv = (TextView) findViewById(R.id.veg_level_description);
// tv.setText( mVenue.get("veg_level_description") );
}{
Button but = (Button) findViewById(R.id.phone);
if ( mVenue.phone.equals("") )
but.setVisibility( View.GONE );
else
but.setText( "Dial " + mVenue.phone );
}{
Button but = (Button) findViewById(R.id.website);
if ( mVenue.website.equals("") )
but.setVisibility( View.GONE );
else
//but.setText( "Visit " + fData.get("website") );
but.setText( "Visit web site" );
}{
TextView tv = (TextView) findViewById(R.id.address);
String addressBlock = mVenue.locHtml();
if ( addressBlock.equals("") )
tv.setVisibility( View.GONE );
else
tv.setText( Html.fromHtml(addressBlock) );
}{
TextView tv = (TextView) findViewById(R.id.long_description);
tv.setMovementMethod( LinkMovementMethod.getInstance() );
if ( mVenue.longDescription.equals("") )
tv.setVisibility( View.GONE );
else
tv.setText( Html.fromHtml( mVenue.longDescription ) );
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
Intent i = getIntent();
int VenueId = i.getIntExtra( "VenueId", -1 );
mVenue = Global.getInstance(this).venues.get(VenueId);
if ( mVenue == null ) {
// TODO: implement error message
return;
}
{
TextView tv = (TextView) findViewById(R.id.name);
tv.setText( mVenue.name );
}{
RatingBar rb = (RatingBar) findViewById(R.id.ratingBar2);
rb.setRating( mVenue.rating );
}{
// TextView tv = (TextView) findViewById(R.id.veg_level_description);
// tv.setText( mVenue.get("veg_level_description") );
}{
Button but = (Button) findViewById(R.id.phone);
if ( mVenue.phone.equals("") )
but.setVisibility( View.GONE );
else
but.setText( "Dial " + mVenue.phone );
}{
Button but = (Button) findViewById(R.id.website);
if ( mVenue.website.equals("") )
but.setVisibility( View.GONE );
else
//but.setText( "Visit " + fData.get("website") );
but.setText( "Visit web site" );
}{
TextView tv = (TextView) findViewById(R.id.address);
String addressBlock = mVenue.locHtml();
if ( addressBlock.equals("") )
tv.setVisibility( View.GONE );
else
tv.setText( Html.fromHtml(addressBlock) );
}{
TextView tv = (TextView) findViewById(R.id.long_description);
tv.setMovementMethod( LinkMovementMethod.getInstance() );
if ( mVenue.longDescription.equals("") )
tv.setVisibility( View.GONE );
else
tv.setText( Html.fromHtml( mVenue.longDescription ) );
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.