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/maven-lombok-plugin/src/main/java/lombok/maven/DelombokMojo.java b/maven-lombok-plugin/src/main/java/lombok/maven/DelombokMojo.java
index b1730ce2..974870ea 100644
--- a/maven-lombok-plugin/src/main/java/lombok/maven/DelombokMojo.java
+++ b/maven-lombok-plugin/src/main/java/lombok/maven/DelombokMojo.java
@@ -1,102 +1,102 @@
package lombok.maven;
import java.io.File;
import java.io.IOException;
import java.nio.charset.UnsupportedCharsetException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import lombok.delombok.Delombok;
/**
* Delombok java source with lombok annotations.
*
* @goal delombok
* @phase generate-sources
* @threadSafe
* @author <a href="mailto:[email protected]">Anthony Whitford</a>
* @see <a href="http://projectlombok.org/features/delombok.html">Delombok</a>
*/
public class DelombokMojo extends AbstractMojo {
/**
* Specifies whether the delombok generation should be skipped.
* @parameter expression="${lombok.delombok.skip}" default-value="false"
* @required
*/
private boolean skip;
/**
* Encoding.
* @parameter expression="${lombok.encoding}" default-value="${project.build.sourceEncoding}"
* @required
*/
private String encoding;
/**
* Location of the lombok annotated source files.
* @parameter expression="${lombok.sourceDirectory}" default-value="${project.build.directory}/../src/main/lombok"
* @required
*/
private File sourceDirectory;
/**
* Location of the generated source files.
* @parameter expression="${lombok.outputDirectory}" default-value="${project.build.directory}/generated-sources/delombok"
* @required
*/
private File outputDirectory;
/**
* Verbose flag.
* @parameter expression="${lombok.verbose}" default-value="false"
* @required
*/
private boolean verbose;
/**
* The Maven project to act upon.
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
@Override
public void execute() throws MojoExecutionException {
final Log logger = getLog();
assert null != logger;
if (this.skip) {
logger.warn("Skipping delombok.");
- } else if (!this.sourceDirectory.exists()) {
- logger.warn("Skipping delombok; no source to process.");
- } else {
+ } else if (this.sourceDirectory.exists()) {
final Delombok delombok = new Delombok();
delombok.setVerbose(this.verbose);
try {
delombok.setCharset(this.encoding);
} catch (final UnsupportedCharsetException e) {
logger.error("The encoding parameter is invalid; Please check!", e);
throw new MojoExecutionException("Unknown charset: " + this.encoding, e);
}
try {
delombok.setOutput(this.outputDirectory);
delombok.delombok(this.sourceDirectory);
logger.info("Delombok complete.");
// adding generated sources to Maven project
project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
} catch (final IOException e) {
logger.error("Unable to delombok!", e);
throw new MojoExecutionException("I/O problem during delombok", e);
}
+ } else {
+ logger.warn("Skipping delombok; no source to process.");
}
}
}
| false | true | public void execute() throws MojoExecutionException {
final Log logger = getLog();
assert null != logger;
if (this.skip) {
logger.warn("Skipping delombok.");
} else if (!this.sourceDirectory.exists()) {
logger.warn("Skipping delombok; no source to process.");
} else {
final Delombok delombok = new Delombok();
delombok.setVerbose(this.verbose);
try {
delombok.setCharset(this.encoding);
} catch (final UnsupportedCharsetException e) {
logger.error("The encoding parameter is invalid; Please check!", e);
throw new MojoExecutionException("Unknown charset: " + this.encoding, e);
}
try {
delombok.setOutput(this.outputDirectory);
delombok.delombok(this.sourceDirectory);
logger.info("Delombok complete.");
// adding generated sources to Maven project
project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
} catch (final IOException e) {
logger.error("Unable to delombok!", e);
throw new MojoExecutionException("I/O problem during delombok", e);
}
}
}
| public void execute() throws MojoExecutionException {
final Log logger = getLog();
assert null != logger;
if (this.skip) {
logger.warn("Skipping delombok.");
} else if (this.sourceDirectory.exists()) {
final Delombok delombok = new Delombok();
delombok.setVerbose(this.verbose);
try {
delombok.setCharset(this.encoding);
} catch (final UnsupportedCharsetException e) {
logger.error("The encoding parameter is invalid; Please check!", e);
throw new MojoExecutionException("Unknown charset: " + this.encoding, e);
}
try {
delombok.setOutput(this.outputDirectory);
delombok.delombok(this.sourceDirectory);
logger.info("Delombok complete.");
// adding generated sources to Maven project
project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
} catch (final IOException e) {
logger.error("Unable to delombok!", e);
throw new MojoExecutionException("I/O problem during delombok", e);
}
} else {
logger.warn("Skipping delombok; no source to process.");
}
}
|
diff --git a/src/com/android/settings/Rootbox.java b/src/com/android/settings/Rootbox.java
index 46909c492..915debb87 100644
--- a/src/com/android/settings/Rootbox.java
+++ b/src/com/android/settings/Rootbox.java
@@ -1,369 +1,365 @@
/*
* Copyright (C) 2012 RootBox Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.IWindowManager;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
public class Rootbox extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener {
private static final String TAG = "Rootbox";
private static final String KEY_LOCK_CLOCK = "lock_clock";
private static final String KEY_HARDWARE_KEYS = "hardware_keys";
private static final String KEY_LOCKSCREEN_BUTTONS = "lockscreen_buttons";
private static final String KEY_EXPANDED_DESKTOP = "power_menu_expanded_desktop";
private static final String KEY_HEADSET_CONNECT_PLAYER = "headset_connect_player";
private static final String KEY_VOLUME_ADJUST_SOUNDS = "volume_adjust_sounds";
private static final String KEY_SEE_TRHOUGH = "see_through";
private static final String KEY_MMS_BREATH = "mms_breath";
private static final String KEY_MISSED_CALL_BREATH = "missed_call_breath";
private static final String KEY_NOTIFICATION_BEHAVIOUR = "notifications_behaviour";
private static final String KEY_STATUS_BAR_ICON_OPACITY = "status_bar_icon_opacity";
private static final String KEY_SWAP_VOLUME_BUTTONS = "swap_volume_buttons";
private static final String PREF_KILL_APP_LONGPRESS_BACK = "kill_app_longpress_back";
private static final String PREF_FULLSCREEN_KEYBOARD = "fullscreen_keyboard";
private static final String KEYBOARD_ROTATION_TOGGLE = "keyboard_rotation_toggle";
private static final String KEYBOARD_ROTATION_TIMEOUT = "keyboard_rotation_timeout";
private static final String PREF_LOW_BATTERY_WARNING_POLICY = "pref_low_battery_warning_policy";
private static final String PREF_NOTIFICATION_SHOW_WIFI_SSID = "notification_show_wifi_ssid";
private static final String VOLUME_KEY_CURSOR_CONTROL = "volume_key_cursor_control";
private static final String RB_HARDWARE_KEYS = "rb_hardware_keys";
private static final String RB_GENERAL_UI = "rb_general_ui";
private static final int KEYBOARD_ROTATION_TIMEOUT_DEFAULT = 5000; // 5s
private PreferenceScreen mLockscreenButtons;
private PreferenceScreen mHardwareKeys;
private CheckBoxPreference mExpandedDesktopPref;
private CheckBoxPreference mHeadsetConnectPlayer;
private CheckBoxPreference mVolumeAdjustSounds;
private CheckBoxPreference mKillAppLongpressBack;
private CheckBoxPreference mCrtOff;
private CheckBoxPreference mCrtOn;
private CheckBoxPreference mFullscreenKeyboard;
private CheckBoxPreference mKeyboardRotationToggle;
private CheckBoxPreference mSeeThrough;
private CheckBoxPreference mMMSBreath;
private CheckBoxPreference mMissedCallBreath;
private CheckBoxPreference mShowWifiName;
private CheckBoxPreference mSwapVolumeButtons;
private ListPreference mVolumeKeyCursorControl;
private ListPreference mKeyboardRotationTimeout;
private ListPreference mLowBatteryWarning;
private ListPreference mNotificationsBeh;
private ListPreference mStatusBarIconOpacity;
private final Configuration mCurConfig = new Configuration();
private ContentResolver mCr;
private Context mContext;
private PreferenceScreen mPrefSet;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver resolver = getContentResolver();
mContext = getActivity();
mPrefSet = getPreferenceScreen();
mCr = getContentResolver();
addPreferencesFromResource(R.xml.rootbox_settings);
PreferenceScreen prefs = getPreferenceScreen();
mSeeThrough = (CheckBoxPreference) findPreference(KEY_SEE_TRHOUGH);
mSeeThrough.setChecked(Settings.System.getInt(resolver,
Settings.System.LOCKSCREEN_SEE_THROUGH, 0) == 1);
mMMSBreath = (CheckBoxPreference) findPreference(KEY_MMS_BREATH);
mMMSBreath.setChecked(Settings.System.getInt(resolver,
Settings.System.MMS_BREATH, 0) == 1);
mMissedCallBreath = (CheckBoxPreference) findPreference(KEY_MISSED_CALL_BREATH);
mMissedCallBreath.setChecked(Settings.System.getInt(resolver,
Settings.System.MISSED_CALL_BREATH, 0) == 1);
mShowWifiName = (CheckBoxPreference) findPreference(PREF_NOTIFICATION_SHOW_WIFI_SSID);
mShowWifiName.setChecked(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.NOTIFICATION_SHOW_WIFI_SSID, 0) == 1);
int CurrentBeh = Settings.Secure.getInt(mCr, Settings.Secure.NOTIFICATIONS_BEHAVIOUR, 0);
mNotificationsBeh = (ListPreference) findPreference(KEY_NOTIFICATION_BEHAVIOUR);
mNotificationsBeh.setValue(String.valueOf(CurrentBeh));
mNotificationsBeh.setSummary(mNotificationsBeh.getEntry());
mNotificationsBeh.setOnPreferenceChangeListener(this);
int iconOpacity = Settings.System.getInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.STATUS_BAR_NOTIF_ICON_OPACITY, 140);
mStatusBarIconOpacity = (ListPreference) findPreference(KEY_STATUS_BAR_ICON_OPACITY);
mStatusBarIconOpacity.setValue(String.valueOf(iconOpacity));
mStatusBarIconOpacity.setOnPreferenceChangeListener(this);
mLockscreenButtons = (PreferenceScreen) findPreference(KEY_LOCKSCREEN_BUTTONS);
mHardwareKeys = (PreferenceScreen) findPreference(KEY_HARDWARE_KEYS);
mFullscreenKeyboard = (CheckBoxPreference) findPreference(PREF_FULLSCREEN_KEYBOARD);
mFullscreenKeyboard.setChecked(Settings.System.getInt(resolver,
Settings.System.FULLSCREEN_KEYBOARD, 0) == 1);
mKeyboardRotationToggle = (CheckBoxPreference) findPreference(KEYBOARD_ROTATION_TOGGLE);
mKeyboardRotationToggle.setChecked(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.KEYBOARD_ROTATION_TIMEOUT, 0) > 0);
mKeyboardRotationTimeout = (ListPreference) findPreference(KEYBOARD_ROTATION_TIMEOUT);
mKeyboardRotationTimeout.setOnPreferenceChangeListener(this);
updateRotationTimeout(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.KEYBOARD_ROTATION_TIMEOUT, KEYBOARD_ROTATION_TIMEOUT_DEFAULT));
mLowBatteryWarning = (ListPreference) findPreference(PREF_LOW_BATTERY_WARNING_POLICY);
int lowBatteryWarning = Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.POWER_UI_LOW_BATTERY_WARNING_POLICY, 3);
mLowBatteryWarning.setValue(String.valueOf(lowBatteryWarning));
mLowBatteryWarning.setSummary(mLowBatteryWarning.getEntry());
mLowBatteryWarning.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL);
if(mVolumeKeyCursorControl != null) {
mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0)));
mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
}
mHeadsetConnectPlayer = (CheckBoxPreference) findPreference(KEY_HEADSET_CONNECT_PLAYER);
mHeadsetConnectPlayer.setChecked(Settings.System.getInt(resolver,
Settings.System.HEADSET_CONNECT_PLAYER, 0) != 0);
mVolumeAdjustSounds = (CheckBoxPreference) findPreference(KEY_VOLUME_ADJUST_SOUNDS);
mVolumeAdjustSounds.setPersistent(false);
mVolumeAdjustSounds.setChecked(Settings.System.getInt(resolver,
Settings.System.VOLUME_ADJUST_SOUNDS_ENABLED, 1) != 0);
mSwapVolumeButtons = (CheckBoxPreference) findPreference(KEY_SWAP_VOLUME_BUTTONS);
mSwapVolumeButtons.setChecked(Settings.System.getInt(resolver,
Settings.System.SWAP_VOLUME_KEYS, 0) == 1);
mKillAppLongpressBack = (CheckBoxPreference) findPreference(PREF_KILL_APP_LONGPRESS_BACK);
updateKillAppLongpressBackOptions();
boolean hasNavBarByDefault = getResources().getBoolean(
com.android.internal.R.bool.config_showNavigationBar);
mExpandedDesktopPref = (CheckBoxPreference) findPreference(KEY_EXPANDED_DESKTOP);
boolean showExpandedDesktopPref =
getResources().getBoolean(R.bool.config_show_expandedDesktop);
if (!showExpandedDesktopPref) {
if (mExpandedDesktopPref != null) {
getPreferenceScreen().removePreference(mExpandedDesktopPref);
}
} else {
mExpandedDesktopPref.setChecked((Settings.System.getInt(getContentResolver(),
Settings.System.POWER_MENU_EXPANDED_DESKTOP_ENABLED, 0) == 1));
}
// Do not display lock clock preference if its not installed
removePreferenceIfPackageNotInstalled(findPreference(KEY_LOCK_CLOCK));
// Only show the hardware keys config on a device that does not have a navbar
- IWindowManager windowManager = IWindowManager.Stub.asInterface(
- ServiceManager.getService(Context.WINDOW_SERVICE));
- try {
- if (windowManager.hasNavigationBar()) {
+ boolean hasHardwareButtons = mContext.getResources().getBoolean(
+ R.bool.has_hardware_buttons);
+ if (!hasHardwareButtons) {
getPreferenceScreen().removePreference(findPreference(RB_HARDWARE_KEYS));
PreferenceCategory generalCategory = (PreferenceCategory) findPreference(RB_GENERAL_UI);
generalCategory.removePreference(mKillAppLongpressBack);
- }
- } catch (RemoteException e) {
- // Do nothing
}
}
public void updateRotationTimeout(int timeout) {
if (timeout == 0)
timeout = KEYBOARD_ROTATION_TIMEOUT_DEFAULT;
mKeyboardRotationTimeout.setValue(Integer.toString(timeout));
mKeyboardRotationTimeout.setSummary(getString(R.string.keyboard_rotation_timeout_summary, mKeyboardRotationTimeout.getEntry()));
}
@Override
public void onResume() {
super.onResume();
}
private void writeKillAppLongpressBackOptions() {
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.KILL_APP_LONGPRESS_BACK, mKillAppLongpressBack.isChecked() ? 1 : 0);
}
private void updateKillAppLongpressBackOptions() {
mKillAppLongpressBack.setChecked(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.KILL_APP_LONGPRESS_BACK, 0) != 0);
}
@Override
public void onPause() {
super.onPause();
}
public void mKeyboardRotationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.keyboard_rotation_dialog);
builder.setCancelable(false);
builder.setPositiveButton(getResources().getString(com.android.internal.R.string.ok), null);
AlertDialog alert = builder.create();
alert.show();
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
boolean value;
if (preference == mExpandedDesktopPref) {
value = mExpandedDesktopPref.isChecked();
Settings.System.putInt(getContentResolver(),
Settings.System.POWER_MENU_EXPANDED_DESKTOP_ENABLED,
value ? 1 : 0);
} else if (preference == mHeadsetConnectPlayer) {
Settings.System.putInt(getContentResolver(), Settings.System.HEADSET_CONNECT_PLAYER,
mHeadsetConnectPlayer.isChecked() ? 1 : 0);
} else if (preference == mVolumeAdjustSounds) {
Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ADJUST_SOUNDS_ENABLED,
mVolumeAdjustSounds.isChecked() ? 1 : 0);
} else if (preference == mSwapVolumeButtons) {
Settings.System.putInt(getActivity().getContentResolver(), Settings.System.SWAP_VOLUME_KEYS,
mSwapVolumeButtons.isChecked() ? 1 : 0);
} else if (preference == mKillAppLongpressBack) {
writeKillAppLongpressBackOptions();
} else if (preference == mFullscreenKeyboard) {
Settings.System.putInt(getActivity().getContentResolver(), Settings.System.FULLSCREEN_KEYBOARD,
mFullscreenKeyboard.isChecked() ? 1 : 0);
} else if (preference == mMMSBreath) {
Settings.System.putInt(mContext.getContentResolver(), Settings.System.MMS_BREATH,
mMMSBreath.isChecked() ? 1 : 0);
} else if (preference == mMissedCallBreath) {
Settings.System.putInt(mContext.getContentResolver(), Settings.System.MISSED_CALL_BREATH,
mMissedCallBreath.isChecked() ? 1 : 0);
} else if (preference == mSeeThrough) {
Settings.System.putInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_SEE_THROUGH,
mSeeThrough.isChecked() ? 1 : 0);
} else if (preference == mShowWifiName) {
Settings.System.putInt(getActivity().getContentResolver(), Settings.System.NOTIFICATION_SHOW_WIFI_SSID,
mShowWifiName.isChecked() ? 1 : 0);
} else if (preference == mKeyboardRotationToggle) {
boolean isAutoRotate = (Settings.System.getInt(getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
if (isAutoRotate && mKeyboardRotationToggle.isChecked())
mKeyboardRotationDialog();
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.KEYBOARD_ROTATION_TIMEOUT,
mKeyboardRotationToggle.isChecked() ? KEYBOARD_ROTATION_TIMEOUT_DEFAULT : 0);
updateRotationTimeout(KEYBOARD_ROTATION_TIMEOUT_DEFAULT);
} else {
// If not handled, let preferences handle it.
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
return true;
}
public boolean onPreferenceChange(Preference preference, Object Value) {
final String key = preference.getKey();
if (preference == mLowBatteryWarning) {
int lowBatteryWarning = Integer.valueOf((String) Value);
int index = mLowBatteryWarning.findIndexOfValue((String) Value);
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.POWER_UI_LOW_BATTERY_WARNING_POLICY, lowBatteryWarning);
mLowBatteryWarning.setSummary(mLowBatteryWarning.getEntries()[index]);
return true;
} else if (preference == mVolumeKeyCursorControl) {
String volumeKeyCursorControl = (String) Value;
int val = Integer.parseInt(volumeKeyCursorControl);
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.VOLUME_KEY_CURSOR_CONTROL, val);
int index = mVolumeKeyCursorControl.findIndexOfValue(volumeKeyCursorControl);
mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntries()[index]);
return true;
} else if (preference == mNotificationsBeh) {
String val = (String) Value;
Settings.Secure.putInt(mCr, Settings.Secure.NOTIFICATIONS_BEHAVIOUR,
Integer.valueOf(val));
int index = mNotificationsBeh.findIndexOfValue(val);
mNotificationsBeh.setSummary(mNotificationsBeh.getEntries()[index]);
return true;
} else if (preference == mStatusBarIconOpacity) {
int iconOpacity = Integer.valueOf((String) Value);
Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.STATUS_BAR_NOTIF_ICON_OPACITY, iconOpacity);
return true;
} else if (preference == mKeyboardRotationTimeout) {
int timeout = Integer.parseInt((String) Value);
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.KEYBOARD_ROTATION_TIMEOUT, timeout);
updateRotationTimeout(timeout);
return true;
}
return false;
}
private boolean removePreferenceIfPackageNotInstalled(Preference preference) {
String intentUri = ((PreferenceScreen) preference).getIntent().toUri(1);
Pattern pattern = Pattern.compile("component=([^/]+)/");
Matcher matcher = pattern.matcher(intentUri);
String packageName = matcher.find() ? matcher.group(1) : null;
if (packageName != null) {
try {
getPackageManager().getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
Log.e(TAG, "package " + packageName + " not installed, hiding preference.");
getPreferenceScreen().removePreference(preference);
return true;
}
}
return false;
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver resolver = getContentResolver();
mContext = getActivity();
mPrefSet = getPreferenceScreen();
mCr = getContentResolver();
addPreferencesFromResource(R.xml.rootbox_settings);
PreferenceScreen prefs = getPreferenceScreen();
mSeeThrough = (CheckBoxPreference) findPreference(KEY_SEE_TRHOUGH);
mSeeThrough.setChecked(Settings.System.getInt(resolver,
Settings.System.LOCKSCREEN_SEE_THROUGH, 0) == 1);
mMMSBreath = (CheckBoxPreference) findPreference(KEY_MMS_BREATH);
mMMSBreath.setChecked(Settings.System.getInt(resolver,
Settings.System.MMS_BREATH, 0) == 1);
mMissedCallBreath = (CheckBoxPreference) findPreference(KEY_MISSED_CALL_BREATH);
mMissedCallBreath.setChecked(Settings.System.getInt(resolver,
Settings.System.MISSED_CALL_BREATH, 0) == 1);
mShowWifiName = (CheckBoxPreference) findPreference(PREF_NOTIFICATION_SHOW_WIFI_SSID);
mShowWifiName.setChecked(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.NOTIFICATION_SHOW_WIFI_SSID, 0) == 1);
int CurrentBeh = Settings.Secure.getInt(mCr, Settings.Secure.NOTIFICATIONS_BEHAVIOUR, 0);
mNotificationsBeh = (ListPreference) findPreference(KEY_NOTIFICATION_BEHAVIOUR);
mNotificationsBeh.setValue(String.valueOf(CurrentBeh));
mNotificationsBeh.setSummary(mNotificationsBeh.getEntry());
mNotificationsBeh.setOnPreferenceChangeListener(this);
int iconOpacity = Settings.System.getInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.STATUS_BAR_NOTIF_ICON_OPACITY, 140);
mStatusBarIconOpacity = (ListPreference) findPreference(KEY_STATUS_BAR_ICON_OPACITY);
mStatusBarIconOpacity.setValue(String.valueOf(iconOpacity));
mStatusBarIconOpacity.setOnPreferenceChangeListener(this);
mLockscreenButtons = (PreferenceScreen) findPreference(KEY_LOCKSCREEN_BUTTONS);
mHardwareKeys = (PreferenceScreen) findPreference(KEY_HARDWARE_KEYS);
mFullscreenKeyboard = (CheckBoxPreference) findPreference(PREF_FULLSCREEN_KEYBOARD);
mFullscreenKeyboard.setChecked(Settings.System.getInt(resolver,
Settings.System.FULLSCREEN_KEYBOARD, 0) == 1);
mKeyboardRotationToggle = (CheckBoxPreference) findPreference(KEYBOARD_ROTATION_TOGGLE);
mKeyboardRotationToggle.setChecked(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.KEYBOARD_ROTATION_TIMEOUT, 0) > 0);
mKeyboardRotationTimeout = (ListPreference) findPreference(KEYBOARD_ROTATION_TIMEOUT);
mKeyboardRotationTimeout.setOnPreferenceChangeListener(this);
updateRotationTimeout(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.KEYBOARD_ROTATION_TIMEOUT, KEYBOARD_ROTATION_TIMEOUT_DEFAULT));
mLowBatteryWarning = (ListPreference) findPreference(PREF_LOW_BATTERY_WARNING_POLICY);
int lowBatteryWarning = Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.POWER_UI_LOW_BATTERY_WARNING_POLICY, 3);
mLowBatteryWarning.setValue(String.valueOf(lowBatteryWarning));
mLowBatteryWarning.setSummary(mLowBatteryWarning.getEntry());
mLowBatteryWarning.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL);
if(mVolumeKeyCursorControl != null) {
mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0)));
mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
}
mHeadsetConnectPlayer = (CheckBoxPreference) findPreference(KEY_HEADSET_CONNECT_PLAYER);
mHeadsetConnectPlayer.setChecked(Settings.System.getInt(resolver,
Settings.System.HEADSET_CONNECT_PLAYER, 0) != 0);
mVolumeAdjustSounds = (CheckBoxPreference) findPreference(KEY_VOLUME_ADJUST_SOUNDS);
mVolumeAdjustSounds.setPersistent(false);
mVolumeAdjustSounds.setChecked(Settings.System.getInt(resolver,
Settings.System.VOLUME_ADJUST_SOUNDS_ENABLED, 1) != 0);
mSwapVolumeButtons = (CheckBoxPreference) findPreference(KEY_SWAP_VOLUME_BUTTONS);
mSwapVolumeButtons.setChecked(Settings.System.getInt(resolver,
Settings.System.SWAP_VOLUME_KEYS, 0) == 1);
mKillAppLongpressBack = (CheckBoxPreference) findPreference(PREF_KILL_APP_LONGPRESS_BACK);
updateKillAppLongpressBackOptions();
boolean hasNavBarByDefault = getResources().getBoolean(
com.android.internal.R.bool.config_showNavigationBar);
mExpandedDesktopPref = (CheckBoxPreference) findPreference(KEY_EXPANDED_DESKTOP);
boolean showExpandedDesktopPref =
getResources().getBoolean(R.bool.config_show_expandedDesktop);
if (!showExpandedDesktopPref) {
if (mExpandedDesktopPref != null) {
getPreferenceScreen().removePreference(mExpandedDesktopPref);
}
} else {
mExpandedDesktopPref.setChecked((Settings.System.getInt(getContentResolver(),
Settings.System.POWER_MENU_EXPANDED_DESKTOP_ENABLED, 0) == 1));
}
// Do not display lock clock preference if its not installed
removePreferenceIfPackageNotInstalled(findPreference(KEY_LOCK_CLOCK));
// Only show the hardware keys config on a device that does not have a navbar
IWindowManager windowManager = IWindowManager.Stub.asInterface(
ServiceManager.getService(Context.WINDOW_SERVICE));
try {
if (windowManager.hasNavigationBar()) {
getPreferenceScreen().removePreference(findPreference(RB_HARDWARE_KEYS));
PreferenceCategory generalCategory = (PreferenceCategory) findPreference(RB_GENERAL_UI);
generalCategory.removePreference(mKillAppLongpressBack);
}
} catch (RemoteException e) {
// Do nothing
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver resolver = getContentResolver();
mContext = getActivity();
mPrefSet = getPreferenceScreen();
mCr = getContentResolver();
addPreferencesFromResource(R.xml.rootbox_settings);
PreferenceScreen prefs = getPreferenceScreen();
mSeeThrough = (CheckBoxPreference) findPreference(KEY_SEE_TRHOUGH);
mSeeThrough.setChecked(Settings.System.getInt(resolver,
Settings.System.LOCKSCREEN_SEE_THROUGH, 0) == 1);
mMMSBreath = (CheckBoxPreference) findPreference(KEY_MMS_BREATH);
mMMSBreath.setChecked(Settings.System.getInt(resolver,
Settings.System.MMS_BREATH, 0) == 1);
mMissedCallBreath = (CheckBoxPreference) findPreference(KEY_MISSED_CALL_BREATH);
mMissedCallBreath.setChecked(Settings.System.getInt(resolver,
Settings.System.MISSED_CALL_BREATH, 0) == 1);
mShowWifiName = (CheckBoxPreference) findPreference(PREF_NOTIFICATION_SHOW_WIFI_SSID);
mShowWifiName.setChecked(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.NOTIFICATION_SHOW_WIFI_SSID, 0) == 1);
int CurrentBeh = Settings.Secure.getInt(mCr, Settings.Secure.NOTIFICATIONS_BEHAVIOUR, 0);
mNotificationsBeh = (ListPreference) findPreference(KEY_NOTIFICATION_BEHAVIOUR);
mNotificationsBeh.setValue(String.valueOf(CurrentBeh));
mNotificationsBeh.setSummary(mNotificationsBeh.getEntry());
mNotificationsBeh.setOnPreferenceChangeListener(this);
int iconOpacity = Settings.System.getInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.STATUS_BAR_NOTIF_ICON_OPACITY, 140);
mStatusBarIconOpacity = (ListPreference) findPreference(KEY_STATUS_BAR_ICON_OPACITY);
mStatusBarIconOpacity.setValue(String.valueOf(iconOpacity));
mStatusBarIconOpacity.setOnPreferenceChangeListener(this);
mLockscreenButtons = (PreferenceScreen) findPreference(KEY_LOCKSCREEN_BUTTONS);
mHardwareKeys = (PreferenceScreen) findPreference(KEY_HARDWARE_KEYS);
mFullscreenKeyboard = (CheckBoxPreference) findPreference(PREF_FULLSCREEN_KEYBOARD);
mFullscreenKeyboard.setChecked(Settings.System.getInt(resolver,
Settings.System.FULLSCREEN_KEYBOARD, 0) == 1);
mKeyboardRotationToggle = (CheckBoxPreference) findPreference(KEYBOARD_ROTATION_TOGGLE);
mKeyboardRotationToggle.setChecked(Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.KEYBOARD_ROTATION_TIMEOUT, 0) > 0);
mKeyboardRotationTimeout = (ListPreference) findPreference(KEYBOARD_ROTATION_TIMEOUT);
mKeyboardRotationTimeout.setOnPreferenceChangeListener(this);
updateRotationTimeout(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.KEYBOARD_ROTATION_TIMEOUT, KEYBOARD_ROTATION_TIMEOUT_DEFAULT));
mLowBatteryWarning = (ListPreference) findPreference(PREF_LOW_BATTERY_WARNING_POLICY);
int lowBatteryWarning = Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.POWER_UI_LOW_BATTERY_WARNING_POLICY, 3);
mLowBatteryWarning.setValue(String.valueOf(lowBatteryWarning));
mLowBatteryWarning.setSummary(mLowBatteryWarning.getEntry());
mLowBatteryWarning.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL);
if(mVolumeKeyCursorControl != null) {
mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0)));
mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
}
mHeadsetConnectPlayer = (CheckBoxPreference) findPreference(KEY_HEADSET_CONNECT_PLAYER);
mHeadsetConnectPlayer.setChecked(Settings.System.getInt(resolver,
Settings.System.HEADSET_CONNECT_PLAYER, 0) != 0);
mVolumeAdjustSounds = (CheckBoxPreference) findPreference(KEY_VOLUME_ADJUST_SOUNDS);
mVolumeAdjustSounds.setPersistent(false);
mVolumeAdjustSounds.setChecked(Settings.System.getInt(resolver,
Settings.System.VOLUME_ADJUST_SOUNDS_ENABLED, 1) != 0);
mSwapVolumeButtons = (CheckBoxPreference) findPreference(KEY_SWAP_VOLUME_BUTTONS);
mSwapVolumeButtons.setChecked(Settings.System.getInt(resolver,
Settings.System.SWAP_VOLUME_KEYS, 0) == 1);
mKillAppLongpressBack = (CheckBoxPreference) findPreference(PREF_KILL_APP_LONGPRESS_BACK);
updateKillAppLongpressBackOptions();
boolean hasNavBarByDefault = getResources().getBoolean(
com.android.internal.R.bool.config_showNavigationBar);
mExpandedDesktopPref = (CheckBoxPreference) findPreference(KEY_EXPANDED_DESKTOP);
boolean showExpandedDesktopPref =
getResources().getBoolean(R.bool.config_show_expandedDesktop);
if (!showExpandedDesktopPref) {
if (mExpandedDesktopPref != null) {
getPreferenceScreen().removePreference(mExpandedDesktopPref);
}
} else {
mExpandedDesktopPref.setChecked((Settings.System.getInt(getContentResolver(),
Settings.System.POWER_MENU_EXPANDED_DESKTOP_ENABLED, 0) == 1));
}
// Do not display lock clock preference if its not installed
removePreferenceIfPackageNotInstalled(findPreference(KEY_LOCK_CLOCK));
// Only show the hardware keys config on a device that does not have a navbar
boolean hasHardwareButtons = mContext.getResources().getBoolean(
R.bool.has_hardware_buttons);
if (!hasHardwareButtons) {
getPreferenceScreen().removePreference(findPreference(RB_HARDWARE_KEYS));
PreferenceCategory generalCategory = (PreferenceCategory) findPreference(RB_GENERAL_UI);
generalCategory.removePreference(mKillAppLongpressBack);
}
}
|
diff --git a/src/test/java/org/mailoverlord/server/controllers/ControllerTest.java b/src/test/java/org/mailoverlord/server/controllers/ControllerTest.java
index 60cf191..37f0b30 100644
--- a/src/test/java/org/mailoverlord/server/controllers/ControllerTest.java
+++ b/src/test/java/org/mailoverlord/server/controllers/ControllerTest.java
@@ -1,55 +1,55 @@
package org.mailoverlord.server.controllers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mailoverlord.server.config.EmbeddedDataSourceConfig;
import org.mailoverlord.server.config.JpaConfig;
import org.mailoverlord.server.config.TestMailSessionConfig;
import org.mailoverlord.server.config.WebConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Index Controller Test
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={WebConfig.class, EmbeddedDataSourceConfig.class, JpaConfig.class, TestMailSessionConfig.class})
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
//this.mockMvc = MockMvcBuilders.standaloneSetup(new IndexController()).build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testIndex() throws Exception {
mockMvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void testTable() throws Exception {
- mockMvc.perform(get("/messages").accept(MediaType.APPLICATION_JSON))
+ mockMvc.perform(get("/messages/list").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
}
| true | true | public void testTable() throws Exception {
mockMvc.perform(get("/messages").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
| public void testTable() throws Exception {
mockMvc.perform(get("/messages/list").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
|
diff --git a/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/StateInitExpression.java b/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/StateInitExpression.java
index e09c6b6d59..6d819e131f 100644
--- a/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/StateInitExpression.java
+++ b/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/StateInitExpression.java
@@ -1,132 +1,132 @@
/*******************************************************************************
*
* Copyright (C) 2008 Fujitsu Services Ltd.
*
* Author: Nick Battle
*
* This file is part of VDMJ.
*
* VDMJ 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.
*
* VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
package org.overturetool.vdmj.expressions;
import org.overturetool.vdmj.definitions.StateDefinition;
import org.overturetool.vdmj.patterns.IdentifierPattern;
import org.overturetool.vdmj.patterns.Pattern;
import org.overturetool.vdmj.runtime.Context;
import org.overturetool.vdmj.runtime.ValueException;
import org.overturetool.vdmj.typechecker.Environment;
import org.overturetool.vdmj.typechecker.NameScope;
import org.overturetool.vdmj.types.BooleanType;
import org.overturetool.vdmj.types.RecordType;
import org.overturetool.vdmj.types.Type;
import org.overturetool.vdmj.types.TypeList;
import org.overturetool.vdmj.values.BooleanValue;
import org.overturetool.vdmj.values.FunctionValue;
import org.overturetool.vdmj.values.RecordValue;
import org.overturetool.vdmj.values.Value;
public class StateInitExpression extends Expression
{
private static final long serialVersionUID = 1L;
public final StateDefinition state;
public StateInitExpression(StateDefinition state)
{
super(state.location);
this.state = state;
location.executable(false);
}
@Override
public Value eval(Context ctxt)
{
breakpoint.check(location, ctxt);
try
{
FunctionValue invariant = state.invfunc;
// Note, the function just checks whether the argument passed would
// violate the state invariant (if any). It doesn't initialize the
// state itself. This is done in State.initialize().
if (invariant != null)
{
IdentifierPattern argp = (IdentifierPattern)state.initPattern;
RecordValue rv = (RecordValue)ctxt.lookup(argp.name);
return invariant.eval(location, rv, ctxt);
}
return new BooleanValue(true);
}
catch (ValueException e)
{
return abort(e);
}
}
@Override
public String toString()
{
return "init " + state.initPattern + " == " + state.initExpression;
}
@Override
public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope)
{
Pattern pattern = state.initPattern;
Expression exp = state.initExpression;
boolean canBeExecuted = false;
if (pattern instanceof IdentifierPattern &&
exp instanceof EqualsExpression)
{
EqualsExpression ee = (EqualsExpression)exp;
+ ee.left.typeCheck(env, null, scope);
if (ee.left instanceof VariableExpression)
{
- ee.left.typeCheck(env, null, scope);
Type rhs = ee.right.typeCheck(env, null, scope);
if (rhs.isRecord())
{
RecordType rt = rhs.getRecord();
canBeExecuted = rt.name.equals(state.name);
}
}
}
else
{
exp.typeCheck(env, null, scope);
}
if (!canBeExecuted)
{
warning(5010, "State init expression cannot be executed");
detail("Expected", "p == p = mk_Record(...)");
}
state.canBeExecuted = canBeExecuted;
return new BooleanType(location);
}
@Override
public String kind()
{
return "state init";
}
}
| false | true | public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope)
{
Pattern pattern = state.initPattern;
Expression exp = state.initExpression;
boolean canBeExecuted = false;
if (pattern instanceof IdentifierPattern &&
exp instanceof EqualsExpression)
{
EqualsExpression ee = (EqualsExpression)exp;
if (ee.left instanceof VariableExpression)
{
ee.left.typeCheck(env, null, scope);
Type rhs = ee.right.typeCheck(env, null, scope);
if (rhs.isRecord())
{
RecordType rt = rhs.getRecord();
canBeExecuted = rt.name.equals(state.name);
}
}
}
else
{
exp.typeCheck(env, null, scope);
}
if (!canBeExecuted)
{
warning(5010, "State init expression cannot be executed");
detail("Expected", "p == p = mk_Record(...)");
}
state.canBeExecuted = canBeExecuted;
return new BooleanType(location);
}
| public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope)
{
Pattern pattern = state.initPattern;
Expression exp = state.initExpression;
boolean canBeExecuted = false;
if (pattern instanceof IdentifierPattern &&
exp instanceof EqualsExpression)
{
EqualsExpression ee = (EqualsExpression)exp;
ee.left.typeCheck(env, null, scope);
if (ee.left instanceof VariableExpression)
{
Type rhs = ee.right.typeCheck(env, null, scope);
if (rhs.isRecord())
{
RecordType rt = rhs.getRecord();
canBeExecuted = rt.name.equals(state.name);
}
}
}
else
{
exp.typeCheck(env, null, scope);
}
if (!canBeExecuted)
{
warning(5010, "State init expression cannot be executed");
detail("Expected", "p == p = mk_Record(...)");
}
state.canBeExecuted = canBeExecuted;
return new BooleanType(location);
}
|
diff --git a/client/src/org/compiere/pos/PosOrderModel.java b/client/src/org/compiere/pos/PosOrderModel.java
index ff82f74..bb24627 100644
--- a/client/src/org/compiere/pos/PosOrderModel.java
+++ b/client/src/org/compiere/pos/PosOrderModel.java
@@ -1,539 +1,540 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License 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. *
*****************************************************************************/
package org.compiere.pos;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Properties;
import org.compiere.model.MBPartner;
import org.compiere.model.MOrder;
import org.compiere.model.MOrderLine;
import org.compiere.model.MOrderTax;
import org.compiere.model.MPOS;
import org.compiere.model.MPayment;
import org.compiere.model.MPaymentProcessor;
import org.compiere.model.MProduct;
import org.compiere.model.MStorage;
import org.compiere.process.DocAction;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.ValueNamePair;
import ar.com.ergio.model.MLAROrderPerception;
/**
* Wrapper for standard order
* @author Paul Bowden - Adaxa Pty Ltd
*
* @contributor Emiliano Pereyra - http://www.ergio.com.ar
*/
public class PosOrderModel extends MOrder {
private static final long serialVersionUID = 5253837037827124425L;
private MPOS m_pos;
public PosOrderModel(Properties ctx, int C_Order_ID, String trxName, MPOS pos) {
super(ctx, C_Order_ID, trxName);
set_TrxName(trxName);
m_pos = pos;
}
/**
* Get/create Order
*
* @return order or null
*/
public static PosOrderModel createOrder(MPOS pos, MBPartner partner, String trxName) {
PosOrderModel order = new PosOrderModel(Env.getCtx(), 0, trxName, pos);
order.setAD_Org_ID(pos.getAD_Org_ID());
order.setIsSOTrx(true);
order.setC_POS_ID(pos.getC_POS_ID());
if (pos.getC_DocType_ID() != 0)
order.setC_DocTypeTarget_ID(pos.getC_DocType_ID());
else
order.setC_DocTypeTarget_ID(MOrder.DocSubTypeSO_POS);
if (partner == null || partner.get_ID() == 0)
partner = pos.getBPartner();
if (partner == null || partner.get_ID() == 0) {
throw new AdempierePOSException("No BPartner for order");
}
order.setBPartner(partner);
//
order.setM_PriceList_ID(pos.getM_PriceList_ID());
order.setM_Warehouse_ID(pos.getM_Warehouse_ID());
order.setSalesRep_ID(pos.getSalesRep_ID());
if (!order.save())
{
order = null;
throw new AdempierePOSException("Save order failed");
}
return order;
} // createOrder
/**
* @author Community Development OpenXpertya
* *Based on Modified Original Code, Revised and Optimized:
* *Copyright ConSerTi
*/
public void setBPartner(MBPartner partner)
{
if (getDocStatus().equals("DR"))
{
if (partner == null || partner.get_ID() == 0) {
throw new AdempierePOSException("no BPartner");
}
else
{
log.info("BPartner - " + partner);
super.setBPartner(partner);
/* TODO - (emmie) Review I think that this code is OLD, and no longer needed it
MOrderLine[] lineas = getLines();
for (int i = 0; i < lineas.length; i++)
{
lineas[i].setC_BPartner_ID(partner.getC_BPartner_ID());
lineas[i].setTax();
lineas[i].save();
}
saveEx();
*/
}
}
}
/**
* Create new Line
*
* @return line or null
*/
public MOrderLine createLine(MProduct product, BigDecimal qtyOrdered,
BigDecimal priceActual, int WindowNo) {
String stockMsg = checkStockAvailable(product, qtyOrdered.intValue(), WindowNo);
if (stockMsg != null) {
throw new AdempierePOSException(stockMsg);
}
- if (!getDocStatus().equals("DR") )
- return null;
+ if (!(getDocStatus().equals("DR") || getDocStatus().equals("IP"))) {
+ return null;
+ }
//add new line or increase qty
// catch Exceptions at order.getLines()
int numLines = 0;
MOrderLine[] lines = null;
try
{
lines = getLines(null,"Line");
numLines = lines.length;
for (int i = 0; i < numLines; i++)
{
if (lines[i].getM_Product_ID() == product.getM_Product_ID())
{
//increase qty
BigDecimal current = lines[i].getQtyEntered();
BigDecimal toadd = qtyOrdered;
BigDecimal total = current.add(toadd);
lines[i].setQty(total);
lines[i].setPrice(); // sets List/limit
if ( priceActual.compareTo(Env.ZERO) > 0 )
lines[i].setPrice(priceActual);
lines[i].save();
return lines[i];
}
}
}
catch (Exception e)
{
log.severe("Order lines cannot be created - " + e.getMessage());
}
//create new line
MOrderLine line = new MOrderLine(this);
line.setProduct(product);
line.setQty(qtyOrdered);
line.setPrice(); // sets List/limit
if ( priceActual.compareTo(Env.ZERO) > 0 )
line.setPrice(priceActual);
line.save();
return line;
} // createLine
/**
* Delete order from database
*
* @author Comunidad de Desarrollo OpenXpertya
* Basado en Codigo Original Modificado, Revisado y Optimizado de:
* Copyright (c) ConSerTi
*/
public boolean deleteOrder () {
if (getDocStatus().equals("DR") || getDocStatus().equals("IP"))
{
MOrderLine[] lines = getLines();
if (lines != null)
{
int numLines = lines.length;
if (numLines > 0)
for (int i = numLines - 1; i >= 0; i--)
{
if (lines[i] != null)
deleteLine(lines[i].getC_OrderLine_ID());
}
}
MOrderTax[] taxs = getTaxes(true);
if (taxs != null)
{
int numTax = taxs.length;
if (numTax > 0)
for (int i = taxs.length - 1; i >= 0; i--)
{
if (taxs[i] != null)
taxs[i].delete(true);
taxs[i].save();
taxs[i] = null;
}
}
getLines(true, null); // requery order
setDocStatus("VO"); //delete(true); red1 -- should not delete but void the order
setDocAction("--"); // emmie
setProcessed(true); //red1 -- to avoid been in history during query
save();
return true;
}
return false;
} // deleteOrder
/**
* to erase the lines from order
* @return true if deleted
*/
public void deleteLine (int C_OrderLine_ID) {
if ( C_OrderLine_ID != -1 )
{
for ( MOrderLine line : getLines(true, "M_Product_ID") )
{
if ( line.getC_OrderLine_ID() == C_OrderLine_ID )
{
line.delete(true);
line.save();
}
}
}
} // deleteLine
/**
* Process Order
* @author Comunidad de Desarrollo OpenXpertya
* *Basado en Codigo Original Modificado, Revisado y Optimizado de:
* *Copyright (c) ConSerTi
*/
public boolean processOrder()
{
//Returning orderCompleted to check for order completeness
boolean orderCompleted = false;
// check if order completed OK
if (getDocStatus().equals("DR") || getDocStatus().equals("IP") )
{
setDocAction(DocAction.ACTION_Complete);
try
{
if (processIt(DocAction.ACTION_Complete) )
{
save();
}
else
{
log.info( "Process Order FAILED");
}
}
catch (Exception e)
{
log.severe("Order can not be completed - " + e.getMessage());
}
finally
{ // When order failed convert it back to draft so it can be processed
if( getDocStatus().equals("IN") )
{
setDocStatus("DR");
}
else if( getDocStatus().equals("CO") )
{
orderCompleted = true;
log.info( "SubCheckout - processOrder OK");
}
else
{
log.info( "SubCheckout - processOrder - unrecognized DocStatus");
}
} // try-finally
}
return orderCompleted;
} // processOrder
public BigDecimal getTaxAmt() {
BigDecimal taxAmt = Env.ZERO;
for (MOrderTax tax : getTaxes(true))
{
taxAmt = taxAmt.add(tax.getTaxAmt());
}
taxAmt = taxAmt.add(getPerceptionAmt());// TODO - Think about perceptions as "other tax"
return taxAmt;
}
public BigDecimal getSubtotal() {
return getGrandTotal().subtract(getTaxAmt());
}
@Override
public BigDecimal getGrandTotal()
{
return super.getGrandTotal().add(getPerceptionAmt());
}
public BigDecimal getPaidAmt()
{
String sql = "SELECT sum(PayAmt) FROM C_Payment WHERE C_Order_ID = ? AND DocStatus IN ('CO','CL')";
BigDecimal received = DB.getSQLValueBD(get_TrxName(), sql, getC_Order_ID());
if ( received == null )
received = Env.ZERO;
sql = "SELECT sum(Amount) FROM C_CashLine WHERE C_Invoice_ID = ? ";
BigDecimal cashline = DB.getSQLValueBD(get_TrxName(), sql, getC_Invoice_ID());
if ( cashline != null )
received = received.add(cashline);
return received;
}
private BigDecimal getPerceptionAmt()
{
MLAROrderPerception perception = MLAROrderPerception.get(this, get_TrxName());
return perception.getTaxAmt();
}
public boolean payCash(BigDecimal amt) {
MPayment payment = createPayment(MPayment.TENDERTYPE_Cash);
payment.setC_CashBook_ID(m_pos.getC_CashBook_ID());
payment.setAmount(getC_Currency_ID(), amt);
payment.setC_BankAccount_ID(m_pos.getC_BankAccount_ID());
setPaymentRule(MOrder.PAYMENTRULE_Cash);
payment.save();
payment.setDocAction(MPayment.DOCACTION_Complete);
payment.setDocStatus(MPayment.DOCSTATUS_Drafted);
if ( payment.processIt(MPayment.DOCACTION_Complete) )
{
payment.save();
return true;
}
else return false;
} // payCash
public boolean payCheck(BigDecimal amt, String accountNo, String routingNo, String checkNo)
{
MPayment payment = createPayment(MPayment.TENDERTYPE_Check);
payment.setAmount(getC_Currency_ID(), amt);
payment.setC_BankAccount_ID(m_pos.getC_BankAccount_ID());
payment.setAccountNo(accountNo);
payment.setRoutingNo(routingNo);
payment.setCheckNo(checkNo);
setPaymentRule(MOrder.PAYMENTRULE_Check);
payment.saveEx();
payment.setDocAction(MPayment.DOCACTION_Complete);
payment.setDocStatus(MPayment.DOCSTATUS_Drafted);
if ( payment.processIt(MPayment.DOCACTION_Complete) )
{
payment.saveEx();
return true;
}
else return false;
} // payCheck
public boolean payCreditCard(BigDecimal amt, String accountName, int month, int year,
String cardNo, String cvc, String cardtype)
{
MPayment payment = createPayment(MPayment.TENDERTYPE_CreditCard);
payment.setAmount(getC_Currency_ID(), amt);
payment.setC_BankAccount_ID(m_pos.getC_BankAccount_ID());
payment.setCreditCard(MPayment.TRXTYPE_Sales, cardtype,
cardNo, cvc, month, year);
setPaymentRule(MOrder.PAYMENTRULE_CreditCard);
payment.saveEx();
payment.setDocAction(MPayment.DOCACTION_Complete);
payment.setDocStatus(MPayment.DOCSTATUS_Drafted);
if ( payment.processIt(MPayment.DOCACTION_Complete) )
{
payment.saveEx();
return true;
}
else return false;
} // payCheck
public boolean payAccount(final BigDecimal amt, int C_PaymentTerm_ID)
{
MPayment payment = createPayment(MPayment.TENDERTYPE_Account);
payment.setAmount(getC_Currency_ID(), amt);
payment.setC_BankAccount_ID(m_pos.getC_BankAccount_ID());
payment.setPayAmt(amt);
setC_PaymentTerm_ID(C_PaymentTerm_ID);
setPaymentRule(MOrder.PAYMENTRULE_OnCredit);
return payment.save();
}
private MPayment createPayment(String tenderType)
{
MPayment payment = new MPayment(getCtx(), 0, get_TrxName());
payment.setAD_Org_ID(m_pos.getAD_Org_ID());
payment.setTenderType(tenderType);
payment.setC_Order_ID(getC_Order_ID());
payment.setIsReceipt(true);
payment.setC_BPartner_ID(getC_BPartner_ID());
return payment;
}
public void reload() {
load( get_TrxName());
getLines(true, "");
}
/**
* Duplicated from MPayment
* Get Accepted Credit Cards for amount
* @param amt trx amount
* @return credit cards
*/
public ValueNamePair[] getCreditCards (BigDecimal amt)
{
try
{
MPaymentProcessor[] m_mPaymentProcessors = MPaymentProcessor.find (getCtx (), null, null,
getAD_Client_ID (), getAD_Org_ID(), getC_Currency_ID (), amt, get_TrxName());
//
HashMap<String,ValueNamePair> map = new HashMap<String,ValueNamePair>(); // to eliminate duplicates
for (int i = 0; i < m_mPaymentProcessors.length; i++)
{
if (m_mPaymentProcessors[i].isAcceptAMEX ())
map.put (MPayment.CREDITCARDTYPE_Amex, getCreditCardPair (MPayment.CREDITCARDTYPE_Amex));
if (m_mPaymentProcessors[i].isAcceptDiners ())
map.put (MPayment.CREDITCARDTYPE_Diners, getCreditCardPair (MPayment.CREDITCARDTYPE_Diners));
if (m_mPaymentProcessors[i].isAcceptDiscover ())
map.put (MPayment.CREDITCARDTYPE_Discover, getCreditCardPair (MPayment.CREDITCARDTYPE_Discover));
if (m_mPaymentProcessors[i].isAcceptMC ())
map.put (MPayment.CREDITCARDTYPE_MasterCard, getCreditCardPair (MPayment.CREDITCARDTYPE_MasterCard));
if (m_mPaymentProcessors[i].isAcceptCorporate ())
map.put (MPayment.CREDITCARDTYPE_PurchaseCard, getCreditCardPair (MPayment.CREDITCARDTYPE_PurchaseCard));
if (m_mPaymentProcessors[i].isAcceptVisa ())
map.put (MPayment.CREDITCARDTYPE_Visa, getCreditCardPair (MPayment.CREDITCARDTYPE_Visa));
} // for all payment processors
//
ValueNamePair[] retValue = new ValueNamePair[map.size ()];
map.values ().toArray (retValue);
log.fine("getCreditCards - #" + retValue.length + " - Processors=" + m_mPaymentProcessors.length);
return retValue;
}
catch (Exception ex)
{
ex.printStackTrace();
return null;
}
} // getCreditCards
/**
*
* Duplicated from MPayment
* Get Type and name pair
* @param CreditCardType credit card Type
* @return pair
*/
private ValueNamePair getCreditCardPair (String CreditCardType)
{
return new ValueNamePair (CreditCardType, getCreditCardName(CreditCardType));
} // getCreditCardPair
/**
*
* Duplicated from MPayment
* Get Name of Credit Card
* @param CreditCardType credit card type
* @return Name
*/
public String getCreditCardName(String CreditCardType)
{
if (CreditCardType == null)
return "--";
else if (MPayment.CREDITCARDTYPE_MasterCard.equals(CreditCardType))
return "MasterCard";
else if (MPayment.CREDITCARDTYPE_Visa.equals(CreditCardType))
return "Visa";
else if (MPayment.CREDITCARDTYPE_Amex.equals(CreditCardType))
return "Amex";
else if (MPayment.CREDITCARDTYPE_ATM.equals(CreditCardType))
return "ATM";
else if (MPayment.CREDITCARDTYPE_Diners.equals(CreditCardType))
return "Diners";
else if (MPayment.CREDITCARDTYPE_Discover.equals(CreditCardType))
return "Discover";
else if (MPayment.CREDITCARDTYPE_PurchaseCard.equals(CreditCardType))
return "PurchaseCard";
return "?" + CreditCardType + "?";
} // getCreditCardName
/**
* Performs stock validation according to product depending of its
* attributes set instance for it.
*
* @param product
* @param attributes
* @param count
* @return null or error stock message
*/
String checkStockAvailable(final MProduct product, int count, int windowNo)
{
boolean isSaleWithoutStock = m_pos.get_ValueAsBoolean("IsSaleWithoutStock");
if (product.isStocked() && !isSaleWithoutStock) {
// TODO - Review this id lookups (m_locator_id and m_attributesetinstance_id)
int m_Locator_ID = Env.getContextAsInt(m_pos.getCtx(), windowNo, "M_Locator_ID");
int m_AttributeSetInstance_ID = Env.getContextAsInt(m_pos.getCtx(), windowNo, "M_AttributeSetInstance_ID");
String msg = String.format("Product=%s AttrSetInstance=%d Count=%d WindowNo=%d",
product, m_AttributeSetInstance_ID, count, windowNo);
log.info(msg);
BigDecimal available = MStorage.getQtyAvailable(m_pos.getM_Warehouse_ID(), m_Locator_ID, product.get_ID(),
m_AttributeSetInstance_ID, get_TrxName());
if (available == null) {
available = Env.ZERO;
}
if (available.signum() == 0) {
return Msg.translate(p_ctx, "NoQtyAvailable") + " 0";
}
else if (available.compareTo(BigDecimal.valueOf(count)) < 0) {
return Msg.translate(p_ctx, "InsufficientQtyAvailable") + " " +available.toString();
}
}
return null;
} // checkStockAvailable
} // PosOrderModel.class
| true | true | public MOrderLine createLine(MProduct product, BigDecimal qtyOrdered,
BigDecimal priceActual, int WindowNo) {
String stockMsg = checkStockAvailable(product, qtyOrdered.intValue(), WindowNo);
if (stockMsg != null) {
throw new AdempierePOSException(stockMsg);
}
if (!getDocStatus().equals("DR") )
return null;
//add new line or increase qty
// catch Exceptions at order.getLines()
int numLines = 0;
MOrderLine[] lines = null;
try
{
lines = getLines(null,"Line");
numLines = lines.length;
for (int i = 0; i < numLines; i++)
{
if (lines[i].getM_Product_ID() == product.getM_Product_ID())
{
//increase qty
BigDecimal current = lines[i].getQtyEntered();
BigDecimal toadd = qtyOrdered;
BigDecimal total = current.add(toadd);
lines[i].setQty(total);
lines[i].setPrice(); // sets List/limit
if ( priceActual.compareTo(Env.ZERO) > 0 )
lines[i].setPrice(priceActual);
lines[i].save();
return lines[i];
}
}
}
catch (Exception e)
{
log.severe("Order lines cannot be created - " + e.getMessage());
}
//create new line
MOrderLine line = new MOrderLine(this);
line.setProduct(product);
line.setQty(qtyOrdered);
line.setPrice(); // sets List/limit
if ( priceActual.compareTo(Env.ZERO) > 0 )
line.setPrice(priceActual);
line.save();
return line;
} // createLine
| public MOrderLine createLine(MProduct product, BigDecimal qtyOrdered,
BigDecimal priceActual, int WindowNo) {
String stockMsg = checkStockAvailable(product, qtyOrdered.intValue(), WindowNo);
if (stockMsg != null) {
throw new AdempierePOSException(stockMsg);
}
if (!(getDocStatus().equals("DR") || getDocStatus().equals("IP"))) {
return null;
}
//add new line or increase qty
// catch Exceptions at order.getLines()
int numLines = 0;
MOrderLine[] lines = null;
try
{
lines = getLines(null,"Line");
numLines = lines.length;
for (int i = 0; i < numLines; i++)
{
if (lines[i].getM_Product_ID() == product.getM_Product_ID())
{
//increase qty
BigDecimal current = lines[i].getQtyEntered();
BigDecimal toadd = qtyOrdered;
BigDecimal total = current.add(toadd);
lines[i].setQty(total);
lines[i].setPrice(); // sets List/limit
if ( priceActual.compareTo(Env.ZERO) > 0 )
lines[i].setPrice(priceActual);
lines[i].save();
return lines[i];
}
}
}
catch (Exception e)
{
log.severe("Order lines cannot be created - " + e.getMessage());
}
//create new line
MOrderLine line = new MOrderLine(this);
line.setProduct(product);
line.setQty(qtyOrdered);
line.setPrice(); // sets List/limit
if ( priceActual.compareTo(Env.ZERO) > 0 )
line.setPrice(priceActual);
line.save();
return line;
} // createLine
|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/ProjectRightsPanel.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/ProjectRightsPanel.java
index 11f5f2b2b..e4db77ae3 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/ProjectRightsPanel.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/ProjectRightsPanel.java
@@ -1,496 +1,488 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.admin;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.ui.AccountGroupSuggestOracle;
import com.google.gerrit.client.ui.FancyFlexTable;
import com.google.gerrit.client.ui.SmallHeading;
import com.google.gerrit.common.data.ApprovalType;
import com.google.gerrit.common.data.GerritConfig;
import com.google.gerrit.common.data.ProjectDetail;
import com.google.gerrit.reviewdb.AccountGroup;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.ApprovalCategoryValue;
import com.google.gerrit.reviewdb.Project;
import com.google.gerrit.reviewdb.RefRight;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwtexpui.globalkey.client.NpTextBox;
import com.google.gwtexpui.safehtml.client.SafeHtml;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
import com.google.gwtjsonrpc.client.VoidResult;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class ProjectRightsPanel extends Composite {
private Project.NameKey projectName;
private RightsTable rights;
private Button delRight;
private Button addRight;
private ListBox catBox;
private ListBox rangeMinBox;
private ListBox rangeMaxBox;
private NpTextBox nameTxtBox;
private SuggestBox nameTxt;
private NpTextBox referenceTxt;
public ProjectRightsPanel(final Project.NameKey toShow) {
projectName = toShow;
final FlowPanel body = new FlowPanel();
initRights(body);
initWidget(body);
}
@Override
protected void onLoad() {
enableForm(false);
super.onLoad();
Util.PROJECT_SVC.projectDetail(projectName,
new GerritCallback<ProjectDetail>() {
public void onSuccess(final ProjectDetail result) {
enableForm(true);
display(result);
}
});
}
private void enableForm(final boolean on) {
delRight.setEnabled(on);
final boolean canAdd = on && catBox.getItemCount() > 0;
addRight.setEnabled(canAdd);
nameTxtBox.setEnabled(canAdd);
referenceTxt.setEnabled(canAdd);
catBox.setEnabled(canAdd);
rangeMinBox.setEnabled(canAdd);
rangeMaxBox.setEnabled(canAdd);
}
private void initRights(final Panel body) {
final FlowPanel addPanel = new FlowPanel();
addPanel.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel());
final Grid addGrid = new Grid(5, 2);
catBox = new ListBox();
rangeMinBox = new ListBox();
rangeMaxBox = new ListBox();
catBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(final ChangeEvent event) {
updateCategorySelection();
}
});
for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes()
.getApprovalTypes()) {
final ApprovalCategory c = at.getCategory();
catBox.addItem(c.getName(), c.getId().get());
}
for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes()
.getActionTypes()) {
final ApprovalCategory c = at.getCategory();
if (Gerrit.getConfig().getWildProject().equals(projectName)
&& ApprovalCategory.OWN.equals(c.getId())) {
// Giving out control of the WILD_PROJECT to other groups beyond
// Administrators is dangerous. Having control over WILD_PROJECT
// is about the same as having Administrator access as users are
// able to affect grants in all projects on the system.
//
continue;
}
catBox.addItem(c.getName(), c.getId().get());
}
addGrid.setText(0, 0, Util.C.columnApprovalCategory() + ":");
addGrid.setWidget(0, 1, catBox);
nameTxtBox = new NpTextBox();
nameTxt = new SuggestBox(new AccountGroupSuggestOracle(), nameTxtBox);
nameTxtBox.setVisibleLength(50);
nameTxtBox.setText(Util.C.defaultAccountGroupName());
nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint());
nameTxtBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
if (Util.C.defaultAccountGroupName().equals(nameTxtBox.getText())) {
nameTxtBox.setText("");
nameTxtBox.removeStyleName(Gerrit.RESOURCES.css()
.inputFieldTypeHint());
}
}
});
nameTxtBox.addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
if ("".equals(nameTxtBox.getText())) {
nameTxtBox.setText(Util.C.defaultAccountGroupName());
nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint());
}
}
});
- nameTxtBox.addKeyPressHandler(new KeyPressHandler() {
- @Override
- public void onKeyPress(KeyPressEvent event) {
- if (event.getCharCode() == KeyCodes.KEY_ENTER) {
- doAddNewRight();
- }
- }
- });
addGrid.setText(1, 0, Util.C.columnGroupName() + ":");
addGrid.setWidget(1, 1, nameTxt);
referenceTxt = new NpTextBox();
referenceTxt.setVisibleLength(50);
referenceTxt.setText("");
referenceTxt.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
doAddNewRight();
}
}
});
addGrid.setText(2, 0, Util.C.columnRefName() + ":");
addGrid.setWidget(2, 1, referenceTxt);
addGrid.setText(3, 0, Util.C.columnRightRange() + ":");
addGrid.setWidget(3, 1, rangeMinBox);
addGrid.setText(4, 0, "");
addGrid.setWidget(4, 1, rangeMaxBox);
addRight = new Button(Util.C.buttonAddProjectRight());
addRight.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doAddNewRight();
}
});
addPanel.add(addGrid);
addPanel.add(addRight);
rights = new RightsTable();
delRight = new Button(Util.C.buttonDeleteGroupMembers());
delRight.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
rights.deleteChecked();
}
});
body.add(new SmallHeading(Util.C.headingAccessRights()));
body.add(rights);
body.add(delRight);
body.add(addPanel);
if (catBox.getItemCount() > 0) {
catBox.setSelectedIndex(0);
updateCategorySelection();
}
}
void display(final ProjectDetail result) {
rights.display(result.groups, result.rights);
}
private void doAddNewRight() {
int idx = catBox.getSelectedIndex();
final ApprovalType at;
ApprovalCategoryValue min, max;
if (idx < 0) {
return;
}
at =
Gerrit.getConfig().getApprovalTypes().getApprovalType(
new ApprovalCategory.Id(catBox.getValue(idx)));
if (at == null) {
return;
}
idx = rangeMinBox.getSelectedIndex();
if (idx < 0) {
return;
}
min = at.getValue(Short.parseShort(rangeMinBox.getValue(idx)));
if (min == null) {
return;
}
idx = rangeMaxBox.getSelectedIndex();
if (idx < 0) {
return;
}
max = at.getValue(Short.parseShort(rangeMaxBox.getValue(idx)));
if (max == null) {
return;
}
final String groupName = nameTxt.getText();
if ("".equals(groupName)
|| Util.C.defaultAccountGroupName().equals(groupName)) {
return;
}
final String refPattern = referenceTxt.getText();
if (min.getValue() > max.getValue()) {
// If the user selects it backwards in the web UI, help them out
// by reversing the order to what we would expect.
//
final ApprovalCategoryValue newMin = max;
final ApprovalCategoryValue newMax = min;
min = newMin;
max = newMax;
}
addRight.setEnabled(false);
Util.PROJECT_SVC.addRight(projectName, at.getCategory().getId(), groupName,
refPattern, min.getValue(), max.getValue(),
new GerritCallback<ProjectDetail>() {
public void onSuccess(final ProjectDetail result) {
addRight.setEnabled(true);
nameTxt.setText("");
referenceTxt.setText("");
display(result);
}
@Override
public void onFailure(final Throwable caught) {
addRight.setEnabled(true);
super.onFailure(caught);
}
});
}
private void updateCategorySelection() {
final int idx = catBox.getSelectedIndex();
final ApprovalType at;
if (idx >= 0) {
at =
Gerrit.getConfig().getApprovalTypes().getApprovalType(
new ApprovalCategory.Id(catBox.getValue(idx)));
} else {
at = null;
}
if (at == null || at.getValues().isEmpty()) {
rangeMinBox.setEnabled(false);
rangeMaxBox.setEnabled(false);
referenceTxt.setEnabled(false);
addRight.setEnabled(false);
return;
}
// TODO Support per-branch READ access.
if (ApprovalCategory.READ.equals(at.getCategory().getId())) {
referenceTxt.setText("");
referenceTxt.setEnabled(false);
} else {
referenceTxt.setEnabled(true);
}
int curIndex = 0, minIndex = -1, maxIndex = -1;
rangeMinBox.clear();
rangeMaxBox.clear();
for (final ApprovalCategoryValue v : at.getValues()) {
final String vStr = String.valueOf(v.getValue());
String nStr = vStr + ": " + v.getName();
if (v.getValue() > 0) {
nStr = "+" + nStr;
}
rangeMinBox.addItem(nStr, vStr);
rangeMaxBox.addItem(nStr, vStr);
if (v.getValue() < 0) {
minIndex = curIndex;
}
if (maxIndex < 0 && v.getValue() > 0) {
maxIndex = curIndex;
}
curIndex++;
}
if (ApprovalCategory.READ.equals(at.getCategory().getId())) {
// Special case; for READ the most logical range is just
// +1 READ, so assume that as the default for both.
minIndex = maxIndex;
}
rangeMinBox.setSelectedIndex(minIndex >= 0 ? minIndex : 0);
rangeMaxBox.setSelectedIndex(maxIndex >= 0 ? maxIndex : curIndex - 1);
addRight.setEnabled(true);
}
private class RightsTable extends FancyFlexTable<RefRight> {
RightsTable() {
table.setWidth("");
table.setText(0, 2, Util.C.columnApprovalCategory());
table.setText(0, 3, Util.C.columnGroupName());
table.setText(0, 4, Util.C.columnRefName());
table.setText(0, 5, Util.C.columnRightRange());
final FlexCellFormatter fmt = table.getFlexCellFormatter();
fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().iconHeader());
fmt.addStyleName(0, 2, Gerrit.RESOURCES.css().dataHeader());
fmt.addStyleName(0, 3, Gerrit.RESOURCES.css().dataHeader());
fmt.addStyleName(0, 4, Gerrit.RESOURCES.css().dataHeader());
fmt.addStyleName(0, 5, Gerrit.RESOURCES.css().dataHeader());
}
void deleteChecked() {
final HashSet<RefRight.Key> refRightIds = new HashSet<RefRight.Key>();
for (int row = 1; row < table.getRowCount(); row++) {
RefRight r = getRowItem(row);
if (r != null && table.getWidget(row, 1) instanceof CheckBox
&& ((CheckBox) table.getWidget(row, 1)).getValue()) {
refRightIds.add(r.getKey());
}
}
GerritCallback<VoidResult> updateTable =
new GerritCallback<VoidResult>() {
@Override
public void onSuccess(final VoidResult result) {
for (int row = 1; row < table.getRowCount();) {
RefRight r = getRowItem(row);
if (r != null && refRightIds.contains(r.getKey())) {
table.removeRow(row);
} else {
row++;
}
}
}
};
if (!refRightIds.isEmpty()) {
Util.PROJECT_SVC.deleteRight(projectName, refRightIds, updateTable);
}
}
void display(final Map<AccountGroup.Id, AccountGroup> groups,
final List<RefRight> refRights) {
while (1 < table.getRowCount())
table.removeRow(table.getRowCount() - 1);
for (final RefRight r : refRights) {
final int row = table.getRowCount();
table.insertRow(row);
applyDataRowStyle(row);
populate(row, groups, r);
}
}
void populate(final int row,
final Map<AccountGroup.Id, AccountGroup> groups, final RefRight r) {
final GerritConfig config = Gerrit.getConfig();
final ApprovalType ar =
config.getApprovalTypes().getApprovalType(r.getApprovalCategoryId());
final AccountGroup group = groups.get(r.getAccountGroupId());
if (!projectName.equals(Gerrit.getConfig().getWildProject())
&& Gerrit.getConfig().getWildProject().equals(r.getProjectNameKey())) {
table.setText(row, 1, "");
} else {
table.setWidget(row, 1, new CheckBox());
}
if (ar != null) {
table.setText(row, 2, ar.getCategory().getName());
} else {
table.setText(row, 2, r.getApprovalCategoryId().get());
}
if (group != null) {
table.setText(row, 3, group.getName());
} else {
table.setText(row, 3, Util.M.deletedGroup(r.getAccountGroupId().get()));
}
table.setText(row, 4, r.getRefPattern());
{
final SafeHtmlBuilder m = new SafeHtmlBuilder();
final ApprovalCategoryValue min, max;
min = ar != null ? ar.getValue(r.getMinValue()) : null;
max = ar != null ? ar.getValue(r.getMaxValue()) : null;
formatValue(m, r.getMinValue(), min);
if (r.getMinValue() != r.getMaxValue()) {
m.br();
formatValue(m, r.getMaxValue(), max);
}
SafeHtml.set(table, row, 5, m);
}
final FlexCellFormatter fmt = table.getFlexCellFormatter();
fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell());
fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell());
fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell());
fmt.addStyleName(row, 4, Gerrit.RESOURCES.css().dataCell());
fmt.addStyleName(row, 5, Gerrit.RESOURCES.css().dataCell());
fmt.addStyleName(row, 5, Gerrit.RESOURCES.css()
.projectAdminApprovalCategoryRangeLine());
setRowItem(row, r);
}
private void formatValue(final SafeHtmlBuilder m, final short v,
final ApprovalCategoryValue e) {
m.openSpan();
m
.setStyleName(Gerrit.RESOURCES.css()
.projectAdminApprovalCategoryValue());
if (v == 0) {
m.append(' ');
} else if (v > 0) {
m.append('+');
}
m.append(v);
m.closeSpan();
if (e != null) {
m.append(": ");
m.append(e.getName());
}
}
}
}
| true | true | private void initRights(final Panel body) {
final FlowPanel addPanel = new FlowPanel();
addPanel.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel());
final Grid addGrid = new Grid(5, 2);
catBox = new ListBox();
rangeMinBox = new ListBox();
rangeMaxBox = new ListBox();
catBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(final ChangeEvent event) {
updateCategorySelection();
}
});
for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes()
.getApprovalTypes()) {
final ApprovalCategory c = at.getCategory();
catBox.addItem(c.getName(), c.getId().get());
}
for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes()
.getActionTypes()) {
final ApprovalCategory c = at.getCategory();
if (Gerrit.getConfig().getWildProject().equals(projectName)
&& ApprovalCategory.OWN.equals(c.getId())) {
// Giving out control of the WILD_PROJECT to other groups beyond
// Administrators is dangerous. Having control over WILD_PROJECT
// is about the same as having Administrator access as users are
// able to affect grants in all projects on the system.
//
continue;
}
catBox.addItem(c.getName(), c.getId().get());
}
addGrid.setText(0, 0, Util.C.columnApprovalCategory() + ":");
addGrid.setWidget(0, 1, catBox);
nameTxtBox = new NpTextBox();
nameTxt = new SuggestBox(new AccountGroupSuggestOracle(), nameTxtBox);
nameTxtBox.setVisibleLength(50);
nameTxtBox.setText(Util.C.defaultAccountGroupName());
nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint());
nameTxtBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
if (Util.C.defaultAccountGroupName().equals(nameTxtBox.getText())) {
nameTxtBox.setText("");
nameTxtBox.removeStyleName(Gerrit.RESOURCES.css()
.inputFieldTypeHint());
}
}
});
nameTxtBox.addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
if ("".equals(nameTxtBox.getText())) {
nameTxtBox.setText(Util.C.defaultAccountGroupName());
nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint());
}
}
});
nameTxtBox.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
doAddNewRight();
}
}
});
addGrid.setText(1, 0, Util.C.columnGroupName() + ":");
addGrid.setWidget(1, 1, nameTxt);
referenceTxt = new NpTextBox();
referenceTxt.setVisibleLength(50);
referenceTxt.setText("");
referenceTxt.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
doAddNewRight();
}
}
});
addGrid.setText(2, 0, Util.C.columnRefName() + ":");
addGrid.setWidget(2, 1, referenceTxt);
addGrid.setText(3, 0, Util.C.columnRightRange() + ":");
addGrid.setWidget(3, 1, rangeMinBox);
addGrid.setText(4, 0, "");
addGrid.setWidget(4, 1, rangeMaxBox);
addRight = new Button(Util.C.buttonAddProjectRight());
addRight.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doAddNewRight();
}
});
addPanel.add(addGrid);
addPanel.add(addRight);
rights = new RightsTable();
delRight = new Button(Util.C.buttonDeleteGroupMembers());
delRight.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
rights.deleteChecked();
}
});
body.add(new SmallHeading(Util.C.headingAccessRights()));
body.add(rights);
body.add(delRight);
body.add(addPanel);
if (catBox.getItemCount() > 0) {
catBox.setSelectedIndex(0);
updateCategorySelection();
}
}
| private void initRights(final Panel body) {
final FlowPanel addPanel = new FlowPanel();
addPanel.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel());
final Grid addGrid = new Grid(5, 2);
catBox = new ListBox();
rangeMinBox = new ListBox();
rangeMaxBox = new ListBox();
catBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(final ChangeEvent event) {
updateCategorySelection();
}
});
for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes()
.getApprovalTypes()) {
final ApprovalCategory c = at.getCategory();
catBox.addItem(c.getName(), c.getId().get());
}
for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes()
.getActionTypes()) {
final ApprovalCategory c = at.getCategory();
if (Gerrit.getConfig().getWildProject().equals(projectName)
&& ApprovalCategory.OWN.equals(c.getId())) {
// Giving out control of the WILD_PROJECT to other groups beyond
// Administrators is dangerous. Having control over WILD_PROJECT
// is about the same as having Administrator access as users are
// able to affect grants in all projects on the system.
//
continue;
}
catBox.addItem(c.getName(), c.getId().get());
}
addGrid.setText(0, 0, Util.C.columnApprovalCategory() + ":");
addGrid.setWidget(0, 1, catBox);
nameTxtBox = new NpTextBox();
nameTxt = new SuggestBox(new AccountGroupSuggestOracle(), nameTxtBox);
nameTxtBox.setVisibleLength(50);
nameTxtBox.setText(Util.C.defaultAccountGroupName());
nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint());
nameTxtBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
if (Util.C.defaultAccountGroupName().equals(nameTxtBox.getText())) {
nameTxtBox.setText("");
nameTxtBox.removeStyleName(Gerrit.RESOURCES.css()
.inputFieldTypeHint());
}
}
});
nameTxtBox.addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
if ("".equals(nameTxtBox.getText())) {
nameTxtBox.setText(Util.C.defaultAccountGroupName());
nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint());
}
}
});
addGrid.setText(1, 0, Util.C.columnGroupName() + ":");
addGrid.setWidget(1, 1, nameTxt);
referenceTxt = new NpTextBox();
referenceTxt.setVisibleLength(50);
referenceTxt.setText("");
referenceTxt.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
doAddNewRight();
}
}
});
addGrid.setText(2, 0, Util.C.columnRefName() + ":");
addGrid.setWidget(2, 1, referenceTxt);
addGrid.setText(3, 0, Util.C.columnRightRange() + ":");
addGrid.setWidget(3, 1, rangeMinBox);
addGrid.setText(4, 0, "");
addGrid.setWidget(4, 1, rangeMaxBox);
addRight = new Button(Util.C.buttonAddProjectRight());
addRight.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doAddNewRight();
}
});
addPanel.add(addGrid);
addPanel.add(addRight);
rights = new RightsTable();
delRight = new Button(Util.C.buttonDeleteGroupMembers());
delRight.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
rights.deleteChecked();
}
});
body.add(new SmallHeading(Util.C.headingAccessRights()));
body.add(rights);
body.add(delRight);
body.add(addPanel);
if (catBox.getItemCount() > 0) {
catBox.setSelectedIndex(0);
updateCategorySelection();
}
}
|
diff --git a/src/edu/cwru/sepia/agent/ResourceCollectionAgent.java b/src/edu/cwru/sepia/agent/ResourceCollectionAgent.java
index 26aff59..45b5b76 100644
--- a/src/edu/cwru/sepia/agent/ResourceCollectionAgent.java
+++ b/src/edu/cwru/sepia/agent/ResourceCollectionAgent.java
@@ -1,349 +1,356 @@
package edu.cwru.sepia.agent;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.prefs.Preferences;
import edu.cwru.sepia.action.Action;
import edu.cwru.sepia.action.ActionFeedback;
import edu.cwru.sepia.action.ActionResult;
import edu.cwru.sepia.action.ActionType;
import edu.cwru.sepia.agent.action.BaseAction;
import edu.cwru.sepia.agent.action.CollectAction;
import edu.cwru.sepia.agent.action.CollectGoldAction;
import edu.cwru.sepia.agent.action.CollectWoodAction;
import edu.cwru.sepia.environment.model.history.BirthLog;
import edu.cwru.sepia.environment.model.history.History.HistoryView;
import edu.cwru.sepia.environment.model.history.ResourceNodeExhaustionLog;
import edu.cwru.sepia.environment.model.state.ResourceNode;
import edu.cwru.sepia.environment.model.state.ResourceNode.ResourceView;
import edu.cwru.sepia.environment.model.state.ResourceType;
import edu.cwru.sepia.environment.model.state.State.StateView;
import edu.cwru.sepia.experiment.Configuration;
import edu.cwru.sepia.experiment.ConfigurationValues;
/*
* This agent uses an instance of the SRS class to do online planning for
* resource collection.
*/
public class ResourceCollectionAgent extends Agent {
private static final long serialVersionUID = 1596635469778909387L;
private SRS planner;
private List<BaseAction> plan = null;
// this number controls how often the agent will replan
private int replanTime = 200;
private Condition goal;
/* Keeps track of actions in progress
* The first key is the list the action came from
* The second key is the total duration so far of that action
*/
private List<Pair<BaseAction,Integer>> inProgress;
// stores the townhall's id
private Integer townhall = null;
private boolean busyTownhall = false;
// stores the peasants that are available for work
private List<Integer> freePeasants;
public ResourceCollectionAgent(int playernum) {
super(playernum);
// this will be used by the convertId's method
inProgress = new ArrayList<Pair<BaseAction, Integer>>();
freePeasants = new LinkedList<Integer>();
}
@Override
public Map<Integer, Action> initialStep(StateView newstate,
HistoryView statehistory) {
System.out.println("In initial step");
// Extract the Goal conditions from the xml
goal = new Condition();
//goal.gold=ConfigurationValues.MODEL_REQUIRED_GOLD.getIntValue(configuration);
//goal.wood=Preferences.userRoot().node("edu").node("cwru").node("sepia").node("environment").node("model").getInt("RequiredWood", 0);
goal.gold = 50000;
goal.wood = 50000;
// find out the townhall and add all of the peasants to the free list
List<Integer> unitIds = newstate.getUnitIds(this.playernum);
for(Integer id : unitIds)
{
String unitName = newstate.getUnit(id).getTemplateView().getName();
if(unitName.equals("TownHall"))
{
townhall = id;
}
else if(unitName.equals("Peasant"))
{
freePeasants.add(id);
}
}
// add the resources to the Collect Actions
int[] spaces = new int[2];
spaces[0] = newstate.getUnit(townhall).getXPosition();
spaces[1] = newstate.getUnit(townhall).getYPosition();
CollectGoldAction goldAction = new CollectGoldAction();
CollectWoodAction woodAction = new CollectWoodAction();
List<Integer> resourceIds = newstate.getAllResourceIds();
for(Integer id : resourceIds)
{
ResourceView resource = newstate.getResourceNode(id);
if(resource.getType() == ResourceNode.Type.GOLD_MINE)
{
goldAction.addResource(id, Math.max(Math.abs(resource.getXPosition()-spaces[0]), Math.abs(resource.getYPosition()-spaces[1])));
}
else
{
woodAction.addResource(id, Math.max(Math.abs(resource.getXPosition()-spaces[0]), Math.abs(resource.getYPosition()-spaces[1])));
}
}
// get initial plan
plan = SRS.getPlan(newstate, goal, this.playernum);
System.out.println("# of actions in plan: " + plan.size());
// increment the number of steps;
Map<Integer, Action> executableActions = convertPlan2Actions(newstate, new HashMap<Integer, Action>());
System.out.println("executableActions: " + executableActions);
return executableActions;
}
@Override
public Map<Integer, Action> middleStep(StateView newstate,
HistoryView statehistory) {
System.out.println("In middleStep");
System.out.println("# of actions in plan: " + plan.size());
System.out.println("\n");
if(newstate.getTurnNumber() % replanTime == 0)
{
plan = SRS.getPlan(newstate, goal, this.playernum);
}
Map<Integer, ActionResult> commandLog = statehistory.getCommandFeedback(playernum, newstate.getTurnNumber()-1);
System.out.println("commandLog: " + commandLog);
// remove nodes that no longer have any resources
List<ResourceNodeExhaustionLog> depletedNodes = statehistory.getResourceNodeExhaustionLogs(newstate.getTurnNumber()-1);
updateResources(depletedNodes);
// update the duration counts
// also if any compoundgather moves have completed add
// appropriate compound deposit actions
Map<Integer, Action> executableActions = updateDurations(commandLog);
// see if any new peasants were created
// if they were then add their id's to the free peasant list
List<BirthLog> births = statehistory.getBirthLogs(newstate.getTurnNumber()-1);
if(!births.isEmpty())
System.out.println("births: " + births);
System.out.println("");
System.out.println("");
addNewPeasants(births);
executableActions = convertPlan2Actions(newstate, executableActions);
//System.out.println("executableActions: " + executableActions);
return executableActions;
}
@Override
public void terminalStep(StateView newstate, HistoryView statehistory) {
// TODO Auto-generated method stub
}
@Override
public void savePlayerData(OutputStream os) {
// TODO Auto-generated method stub
}
@Override
public void loadPlayerData(InputStream is) {
// TODO Auto-generated method stub
}
/*
* This method takes the plan from the SRS and converts it to
* SEPIA's actions
*/
private Map<Integer, Action> convertPlan2Actions(StateView state, Map<Integer, Action> actionMap)
{
System.out.println("In convertPlan2Actions");
while(!plan.isEmpty())
{
System.out.println("Action " + plan.get(0).getClass().getName());
//System.out.println("\tPreconditions Met: " + preSat(plan.get(0), state));
if(preSat(plan.get(0), state))
{
System.out.println("\tPreconditions Met: True");
System.out.println("\tUnit Type: " + plan.get(0).getUnitType());
if(plan.get(0).getUnitType().equals("Peasant"))
{
// grab the id of the peasant this will be assigned to
Integer id = getAvailPeasant();
// remove this action from the plan
BaseAction action = plan.remove(0);
// set the unitID in the action
action.setUnitId(id);
// add the action to the actions to be executed this turn
actionMap.put(id, action.getAction(playernum, state));
// add the action to the list of actions in progress
inProgress.add(new Pair<BaseAction, Integer>(action, 0));
System.out.println("actionMap: " + actionMap);
}
else
{
BaseAction action = plan.remove(0);
action.setUnitId(townhall);
actionMap.put(townhall, action.getAction(playernum, state));
inProgress.add(new Pair<BaseAction, Integer>(action, 0));
busyTownhall = true;
System.out.println("actionMap: " + actionMap);
}
}
else // as soon as a single bad action is reached then quit trying to make a plan
{
break;
}
}
return actionMap;
}
private boolean preSat(BaseAction action, StateView state)
{
Condition pre = action.getPreConditions();
boolean result = true;
result = result && (state.getResourceAmount(playernum, ResourceType.GOLD) >= pre.gold); // is there enough gold?
result = result && (state.getResourceAmount(playernum, ResourceType.WOOD) >= pre.wood); // is there enough wood?
result = result && (freePeasants.size() >= pre.peasant); // are there enough peasants?
// might have to subtract the number of peasants currently created
result = result && (state.getSupplyCap(playernum) >= pre.supply); // are there enough farms?
if(pre.townhall == 1)
result = result && !busyTownhall;
return result;
}
private Integer getAvailPeasant()
{
if(!freePeasants.isEmpty())
return freePeasants.remove(0);
return null;
}
/*
* This method will either update the duration counter for actions in progress
* It will also remove an action from inProgress and free up its resources if
* the action is incomplete
*/
private Map<Integer, Action> updateDurations(Map<Integer, ActionResult> log)
{
Map<Integer, Action> actionMap = new HashMap<Integer, Action>();
int index = -1;
List<Pair<BaseAction, Integer>> newInProgress = new ArrayList<Pair<BaseAction, Integer>>();
for(Pair<BaseAction, Integer> pairing : inProgress)
{
index++;
int unitid = pairing.first.getUnitId();
ActionFeedback result = log.get(unitid).getFeedback();
// if still in progress
if(result.compareTo(ActionFeedback.INCOMPLETE) == 0)
{
pairing.second++;
newInProgress.add(pairing);
}
// finished last turn
else if(result.compareTo(ActionFeedback.COMPLETED) == 0)
{
// update the duration for that resourceID
pairing.second++;
// don't want to remove collection actions because they need to be continued
// with a COMPOUND_DEPOSIT move
if(log.get(unitid).getAction().getType().compareTo(ActionType.COMPOUNDGATHER) == 0)
{
actionMap.put(unitid, Action.createCompoundDeposit(unitid, townhall));
newInProgress.add(pairing);
continue;
}
try {
pairing.first.updateDuration(pairing.second);
} catch (Exception e) {
e.printStackTrace();
}
// remove the object from the inProgress list
Pair<BaseAction, Integer> completed = inProgress.get(index);
if(unitid != townhall)
freePeasants.add(unitid);
else
busyTownhall = false;
}
// error or something else
else
{
// retry the action
// should probably make this replan
- /*Action oldAction = log.get(unitid).getAction();
- ActionType oldType = oldAction.getType();
- switch(oldType)
+ // deposits must suceed or a peasant becomes useless
+ // because the peasant will be unable to pickup any more resources without first depositing
+ if(log.get(unitid).getAction().getType().compareTo(ActionType.COMPOUNDDEPOSIT) == 0)
{
- case COMPOUNDGATHER:
- actionMap.put(unitid, Action.createCompoundGather(unitid, ))
- }*/
- actionMap.put(unitid, log.get(unitid).getAction());
- newInProgress.add(pairing);
+ actionMap.put(unitid, log.get(unitid).getAction());
+ newInProgress.add(pairing);
+ }
+ // any other action can simply be dropped and will be readded with the new plan
+ else
+ {
+ Pair<BaseAction, Integer> completed = inProgress.get(index);
+ if(unitid != townhall)
+ freePeasants.add(unitid);
+ else
+ busyTownhall = false;
+ }
}
}
inProgress = newInProgress;
return actionMap;
}
private void addNewPeasants(List<BirthLog> births)
{
for(BirthLog log : births)
{
freePeasants.add(log.getNewUnitID());
}
}
/*
* This method removes depleted trees and gold mines from the duration
* tracking map inside of the wood and gold action classes
*/
private void updateResources(List<ResourceNodeExhaustionLog> log)
{
CollectAction wood = new CollectWoodAction();
CollectAction gold = new CollectGoldAction();
for(ResourceNodeExhaustionLog nodeLog : log)
{
if(nodeLog.getResourceNodeType() == ResourceNode.Type.GOLD_MINE)
{
gold.deleteResource(nodeLog.getExhaustedNodeID());
}
else
{
wood.deleteResource(nodeLog.getExhaustedNodeID());
}
}
}
}
| false | true | private Map<Integer, Action> updateDurations(Map<Integer, ActionResult> log)
{
Map<Integer, Action> actionMap = new HashMap<Integer, Action>();
int index = -1;
List<Pair<BaseAction, Integer>> newInProgress = new ArrayList<Pair<BaseAction, Integer>>();
for(Pair<BaseAction, Integer> pairing : inProgress)
{
index++;
int unitid = pairing.first.getUnitId();
ActionFeedback result = log.get(unitid).getFeedback();
// if still in progress
if(result.compareTo(ActionFeedback.INCOMPLETE) == 0)
{
pairing.second++;
newInProgress.add(pairing);
}
// finished last turn
else if(result.compareTo(ActionFeedback.COMPLETED) == 0)
{
// update the duration for that resourceID
pairing.second++;
// don't want to remove collection actions because they need to be continued
// with a COMPOUND_DEPOSIT move
if(log.get(unitid).getAction().getType().compareTo(ActionType.COMPOUNDGATHER) == 0)
{
actionMap.put(unitid, Action.createCompoundDeposit(unitid, townhall));
newInProgress.add(pairing);
continue;
}
try {
pairing.first.updateDuration(pairing.second);
} catch (Exception e) {
e.printStackTrace();
}
// remove the object from the inProgress list
Pair<BaseAction, Integer> completed = inProgress.get(index);
if(unitid != townhall)
freePeasants.add(unitid);
else
busyTownhall = false;
}
// error or something else
else
{
// retry the action
// should probably make this replan
/*Action oldAction = log.get(unitid).getAction();
ActionType oldType = oldAction.getType();
switch(oldType)
{
case COMPOUNDGATHER:
actionMap.put(unitid, Action.createCompoundGather(unitid, ))
}*/
actionMap.put(unitid, log.get(unitid).getAction());
newInProgress.add(pairing);
}
}
inProgress = newInProgress;
return actionMap;
}
| private Map<Integer, Action> updateDurations(Map<Integer, ActionResult> log)
{
Map<Integer, Action> actionMap = new HashMap<Integer, Action>();
int index = -1;
List<Pair<BaseAction, Integer>> newInProgress = new ArrayList<Pair<BaseAction, Integer>>();
for(Pair<BaseAction, Integer> pairing : inProgress)
{
index++;
int unitid = pairing.first.getUnitId();
ActionFeedback result = log.get(unitid).getFeedback();
// if still in progress
if(result.compareTo(ActionFeedback.INCOMPLETE) == 0)
{
pairing.second++;
newInProgress.add(pairing);
}
// finished last turn
else if(result.compareTo(ActionFeedback.COMPLETED) == 0)
{
// update the duration for that resourceID
pairing.second++;
// don't want to remove collection actions because they need to be continued
// with a COMPOUND_DEPOSIT move
if(log.get(unitid).getAction().getType().compareTo(ActionType.COMPOUNDGATHER) == 0)
{
actionMap.put(unitid, Action.createCompoundDeposit(unitid, townhall));
newInProgress.add(pairing);
continue;
}
try {
pairing.first.updateDuration(pairing.second);
} catch (Exception e) {
e.printStackTrace();
}
// remove the object from the inProgress list
Pair<BaseAction, Integer> completed = inProgress.get(index);
if(unitid != townhall)
freePeasants.add(unitid);
else
busyTownhall = false;
}
// error or something else
else
{
// retry the action
// should probably make this replan
// deposits must suceed or a peasant becomes useless
// because the peasant will be unable to pickup any more resources without first depositing
if(log.get(unitid).getAction().getType().compareTo(ActionType.COMPOUNDDEPOSIT) == 0)
{
actionMap.put(unitid, log.get(unitid).getAction());
newInProgress.add(pairing);
}
// any other action can simply be dropped and will be readded with the new plan
else
{
Pair<BaseAction, Integer> completed = inProgress.get(index);
if(unitid != townhall)
freePeasants.add(unitid);
else
busyTownhall = false;
}
}
}
inProgress = newInProgress;
return actionMap;
}
|
diff --git a/tooling/jbi-maven-plugin/src/main/java/org/apache/servicemix/maven/plugin/jbi/GenerateServiceAssemblyDescriptorMojo.java b/tooling/jbi-maven-plugin/src/main/java/org/apache/servicemix/maven/plugin/jbi/GenerateServiceAssemblyDescriptorMojo.java
index 83f21e60f..3373ecb6a 100644
--- a/tooling/jbi-maven-plugin/src/main/java/org/apache/servicemix/maven/plugin/jbi/GenerateServiceAssemblyDescriptorMojo.java
+++ b/tooling/jbi-maven-plugin/src/main/java/org/apache/servicemix/maven/plugin/jbi/GenerateServiceAssemblyDescriptorMojo.java
@@ -1,267 +1,269 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicemix.maven.plugin.jbi;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.codehaus.plexus.util.FileUtils;
/**
* A Mojo used to build the jbi.xml file for a service unit.
*
* @author <a href="[email protected]">Philip Dodds</a>
* @version $Id: GenerateComponentDescriptorMojo 314956 2005-10-12 16:27:15Z
* brett $
* @goal generate-jbi-service-assembly-descriptor
* @phase generate-resources
* @requiresDependencyResolution runtime
* @description generates the jbi.xml deployment descriptor for a service unit
*/
public class GenerateServiceAssemblyDescriptorMojo extends AbstractJbiMojo {
public static final String UTF_8 = "UTF-8";
/**
* Whether the jbi.xml should be generated or not.
*
* @parameter
*/
private Boolean generateJbiDescriptor = Boolean.TRUE;
/**
* The component name.
*
* @parameter expression="${project.artifactId}"
*/
private String name;
/**
* The component description.
*
* @parameter expression="${project.name}"
*/
private String description;
/**
* Character encoding for the auto-generated application.xml file.
*
* @parameter
*/
private String encoding = UTF_8;
/**
* Directory where the application.xml file will be auto-generated.
*
* @parameter expression="${project.build.directory}/classes/META-INF"
*/
private String generatedDescriptorLocation;
/**
* @component
*/
private MavenProjectBuilder pb;
/**
* @parameter default-value="${localRepository}"
*/
private ArtifactRepository localRepo;
/**
* @parameter default-value="${project.remoteArtifactRepositories}"
*/
private List remoteRepos;
public void execute() throws MojoExecutionException, MojoFailureException {
getLog()
.debug(
" ======= GenerateServiceAssemlbyDescriptorMojo settings =======");
getLog().debug("workDirectory[" + workDirectory + "]");
getLog().debug("generateJbiDescriptor[" + generateJbiDescriptor + "]");
getLog().debug("name[" + name + "]");
getLog().debug("description[" + description + "]");
getLog().debug("encoding[" + encoding + "]");
getLog().debug(
"generatedDescriptorLocation[" + generatedDescriptorLocation
+ "]");
if (!generateJbiDescriptor.booleanValue()) {
getLog().debug("Generation of jbi.xml is disabled");
return;
}
// Generate jbi descriptor and copy it to the build directory
getLog().info("Generating jbi.xml");
try {
generateJbiDescriptor();
} catch (JbiPluginException e) {
throw new MojoExecutionException("Failed to generate jbi.xml", e);
}
try {
FileUtils.copyFileToDirectory(new File(generatedDescriptorLocation,
JBI_DESCRIPTOR), new File(getWorkDirectory(), META_INF));
} catch (IOException e) {
throw new MojoExecutionException(
"Unable to copy jbi.xml to final destination", e);
}
}
/**
* Generates the deployment descriptor if necessary.
*
* @throws MojoExecutionException
*/
protected void generateJbiDescriptor() throws JbiPluginException,
MojoExecutionException {
File outputDir = new File(generatedDescriptorLocation);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
File descriptor = new File(outputDir, JBI_DESCRIPTOR);
List serviceUnits = new ArrayList();
Set artifacts = project.getArtifacts();
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
// TODO: utilise appropriate methods from project builder
ScopeArtifactFilter filter = new ScopeArtifactFilter(
Artifact.SCOPE_RUNTIME);
if (!artifact.isOptional() && filter.include(artifact)
&& (artifact.getDependencyTrail().size() == 2)) {
MavenProject project = null;
try {
project = pb.buildFromRepository(artifact, remoteRepos,
localRepo);
} catch (ProjectBuildingException e) {
getLog().warn(
"Unable to determine packaging for dependency : "
+ artifact.getArtifactId()
+ " assuming jar");
}
if ((project != null)
&& (project.getPackaging().equals("jbi-service-unit"))) {
DependencyInformation info = new DependencyInformation();
info.setName(artifact.getArtifactId());
- info.setFilename(artifact.getFile().getName());
+ String name = artifact.getFile().getName();
+ name = name.substring(0, name.lastIndexOf('.')) + ".zip";
+ info.setFilename(name);
info.setComponent(getComponentName(project, artifacts,
artifact));
info.setDescription(project.getDescription());
serviceUnits.add(info);
}
}
}
List orderedServiceUnits = reorderServiceUnits(serviceUnits);
JbiServiceAssemblyDescriptorWriter writer = new JbiServiceAssemblyDescriptorWriter(
encoding);
writer.write(descriptor, name, description, orderedServiceUnits);
}
/**
* Re-orders the service units to match order in the dependencies section of the pom
*
* @param serviceUnits
*/
private List reorderServiceUnits(List serviceUnits) {
Iterator dependencies = project.getModel().getDependencies().iterator();
List orderedServiceUnits = new ArrayList();
while(dependencies.hasNext()) {
Dependency dependency = (Dependency) dependencies.next();
for (Iterator it = serviceUnits.iterator(); it.hasNext();) {
DependencyInformation serviceUnitInfo = (DependencyInformation) it
.next();
if (dependency.getArtifactId().equals(serviceUnitInfo.getName())) {
orderedServiceUnits.add(serviceUnitInfo);
}
}
}
return orderedServiceUnits;
}
private String getComponentName(MavenProject project, Set artifacts,
Artifact suArtifact) throws MojoExecutionException {
getLog().info(
"Determining component name for service unit "
+ project.getArtifactId());
if (project.getProperties().getProperty("componentName") != null) {
return project.getProperties().getProperty("componentName");
}
String currentArtifact = suArtifact.getGroupId() + ":"
+ suArtifact.getArtifactId() + ":" + suArtifact.getType() + ":"
+ suArtifact.getVersion();
// Find artifacts directly under this project
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
if ((artifact.getDependencyTrail().size() == 3)) {
String parent = getDependencyParent(artifact
.getDependencyTrail());
if (parent.equals(currentArtifact)) {
MavenProject artifactProject = null;
try {
artifactProject = pb.buildFromRepository(artifact,
remoteRepos, localRepo);
} catch (ProjectBuildingException e) {
getLog().warn(
"Unable to determine packaging for dependency : "
+ artifact.getArtifactId()
+ " assuming jar");
}
getLog().info("Project "+artifactProject+" packaged "+artifactProject.getPackaging());
if ((artifactProject != null)
&& (artifactProject.getPackaging()
.equals("jbi-component"))) {
return artifact.getArtifactId();
}
}
}
}
throw new MojoExecutionException(
"The service unit "
+ project.getArtifactId()
+ " does not have a dependency which is packaged as a jbi-component or a project property 'componentName'");
}
private String getDependencyParent(List dependencyTrail) {
return (String) dependencyTrail.get(dependencyTrail.size() - 2);
}
}
| true | true | protected void generateJbiDescriptor() throws JbiPluginException,
MojoExecutionException {
File outputDir = new File(generatedDescriptorLocation);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
File descriptor = new File(outputDir, JBI_DESCRIPTOR);
List serviceUnits = new ArrayList();
Set artifacts = project.getArtifacts();
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
// TODO: utilise appropriate methods from project builder
ScopeArtifactFilter filter = new ScopeArtifactFilter(
Artifact.SCOPE_RUNTIME);
if (!artifact.isOptional() && filter.include(artifact)
&& (artifact.getDependencyTrail().size() == 2)) {
MavenProject project = null;
try {
project = pb.buildFromRepository(artifact, remoteRepos,
localRepo);
} catch (ProjectBuildingException e) {
getLog().warn(
"Unable to determine packaging for dependency : "
+ artifact.getArtifactId()
+ " assuming jar");
}
if ((project != null)
&& (project.getPackaging().equals("jbi-service-unit"))) {
DependencyInformation info = new DependencyInformation();
info.setName(artifact.getArtifactId());
info.setFilename(artifact.getFile().getName());
info.setComponent(getComponentName(project, artifacts,
artifact));
info.setDescription(project.getDescription());
serviceUnits.add(info);
}
}
}
List orderedServiceUnits = reorderServiceUnits(serviceUnits);
JbiServiceAssemblyDescriptorWriter writer = new JbiServiceAssemblyDescriptorWriter(
encoding);
writer.write(descriptor, name, description, orderedServiceUnits);
}
| protected void generateJbiDescriptor() throws JbiPluginException,
MojoExecutionException {
File outputDir = new File(generatedDescriptorLocation);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
File descriptor = new File(outputDir, JBI_DESCRIPTOR);
List serviceUnits = new ArrayList();
Set artifacts = project.getArtifacts();
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
// TODO: utilise appropriate methods from project builder
ScopeArtifactFilter filter = new ScopeArtifactFilter(
Artifact.SCOPE_RUNTIME);
if (!artifact.isOptional() && filter.include(artifact)
&& (artifact.getDependencyTrail().size() == 2)) {
MavenProject project = null;
try {
project = pb.buildFromRepository(artifact, remoteRepos,
localRepo);
} catch (ProjectBuildingException e) {
getLog().warn(
"Unable to determine packaging for dependency : "
+ artifact.getArtifactId()
+ " assuming jar");
}
if ((project != null)
&& (project.getPackaging().equals("jbi-service-unit"))) {
DependencyInformation info = new DependencyInformation();
info.setName(artifact.getArtifactId());
String name = artifact.getFile().getName();
name = name.substring(0, name.lastIndexOf('.')) + ".zip";
info.setFilename(name);
info.setComponent(getComponentName(project, artifacts,
artifact));
info.setDescription(project.getDescription());
serviceUnits.add(info);
}
}
}
List orderedServiceUnits = reorderServiceUnits(serviceUnits);
JbiServiceAssemblyDescriptorWriter writer = new JbiServiceAssemblyDescriptorWriter(
encoding);
writer.write(descriptor, name, description, orderedServiceUnits);
}
|
diff --git a/src/org/odk/collect/android/tasks/InstanceUploaderTask.java b/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
index 38a0a5d..405e904 100644
--- a/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
+++ b/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
@@ -1,482 +1,482 @@
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.tasks;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.protocol.HttpContext;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.utilities.WebUtils;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Background task for uploading completed forms.
*
* @author Carl Hartung ([email protected])
*/
public class InstanceUploaderTask extends AsyncTask<Long, Integer, HashMap<String, String>> {
private static String t = "InstanceUploaderTask";
private InstanceUploaderListener mStateListener;
private static final int CONNECTION_TIMEOUT = 30000;
private static final String fail = "FAILED: ";
private URI mAuthRequestingServer;
HashMap<String, String> mResults;
// TODO: This method is like 350 lines long, down from 400.
// still. ridiculous. make it smaller.
@Override
protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
Map<URI, URI> uriRemap = new HashMap<URI, URI>();
Cursor c =
Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
next_submission: while (c.moveToNext()) {
if (isCancelled()) {
return mResults;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
urlString = urlString + submissionUrl;
}
ContentValues cv = new ContentValues();
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (URISyntaxException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
} else {
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 401) {
// we need authentication, so stop and return what we've
// done so far.
mAuthRequestingServer = u;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
if (locations != null && locations.length == 1) {
try {
URL url = new URL(locations[0].getValue());
URI uNew = url.toURI();
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
} catch (Exception e) {
e.printStackTrace();
- mResults.put(id, fail + e.getMessage());
+ mResults.put(id, fail + urlString + " " + e.getMessage());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} else {
// may be a server that does not handle
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= 200 && statusCode <= 299) {
mResults.put(id, fail + "network login? ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mResults.put(id, fail + "client protocol exeption?");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic excpetion. great");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
File instanceFile = new File(instance);
if (!instanceFile.exists()) {
mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
while (j < files.size() || first) {
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(instanceFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + instanceFile.getName());
byteCount += instanceFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if (byteCount + files.get(j + 1).length() > 10000000L) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != 201 && responseCode != 202) {
if (responseCode == 200) {
mResults.put(id, fail + "Network login failure? again?");
} else {
- mResults.put(id, fail + responseCode + " returned "
- + response.getStatusLine().getReasonPhrase());
+ mResults.put(id, fail + urlString + " returned " + responseCode + " " +
+ response.getStatusLine().getReasonPhrase());
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue next_submission;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic exception... " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue next_submission;
}
}
// if it got here, it must have worked
mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
}
if (c != null) {
c.close();
}
} // end while
return mResults;
}
@Override
protected void onPostExecute(HashMap<String, String> value) {
synchronized (this) {
if (mStateListener != null) {
if (mAuthRequestingServer != null) {
mStateListener.authRequest(mAuthRequestingServer, mResults);
} else {
mStateListener.uploadingComplete(value);
}
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0].intValue(), values[1].intValue());
}
}
}
public void setUploaderListener(InstanceUploaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
| false | true | protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
Map<URI, URI> uriRemap = new HashMap<URI, URI>();
Cursor c =
Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
next_submission: while (c.moveToNext()) {
if (isCancelled()) {
return mResults;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
urlString = urlString + submissionUrl;
}
ContentValues cv = new ContentValues();
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (URISyntaxException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
} else {
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 401) {
// we need authentication, so stop and return what we've
// done so far.
mAuthRequestingServer = u;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
if (locations != null && locations.length == 1) {
try {
URL url = new URL(locations[0].getValue());
URI uNew = url.toURI();
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + e.getMessage());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} else {
// may be a server that does not handle
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= 200 && statusCode <= 299) {
mResults.put(id, fail + "network login? ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mResults.put(id, fail + "client protocol exeption?");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic excpetion. great");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
File instanceFile = new File(instance);
if (!instanceFile.exists()) {
mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
while (j < files.size() || first) {
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(instanceFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + instanceFile.getName());
byteCount += instanceFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if (byteCount + files.get(j + 1).length() > 10000000L) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != 201 && responseCode != 202) {
if (responseCode == 200) {
mResults.put(id, fail + "Network login failure? again?");
} else {
mResults.put(id, fail + responseCode + " returned "
+ response.getStatusLine().getReasonPhrase());
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue next_submission;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic exception... " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue next_submission;
}
}
// if it got here, it must have worked
mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
}
if (c != null) {
c.close();
}
} // end while
return mResults;
}
| protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
Map<URI, URI> uriRemap = new HashMap<URI, URI>();
Cursor c =
Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
next_submission: while (c.moveToNext()) {
if (isCancelled()) {
return mResults;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
urlString = urlString + submissionUrl;
}
ContentValues cv = new ContentValues();
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (URISyntaxException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
} else {
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 401) {
// we need authentication, so stop and return what we've
// done so far.
mAuthRequestingServer = u;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
if (locations != null && locations.length == 1) {
try {
URL url = new URL(locations[0].getValue());
URI uNew = url.toURI();
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + urlString + " " + e.getMessage());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} else {
// may be a server that does not handle
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= 200 && statusCode <= 299) {
mResults.put(id, fail + "network login? ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mResults.put(id, fail + "client protocol exeption?");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic excpetion. great");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
File instanceFile = new File(instance);
if (!instanceFile.exists()) {
mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
while (j < files.size() || first) {
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(instanceFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + instanceFile.getName());
byteCount += instanceFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if (byteCount + files.get(j + 1).length() > 10000000L) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != 201 && responseCode != 202) {
if (responseCode == 200) {
mResults.put(id, fail + "Network login failure? again?");
} else {
mResults.put(id, fail + urlString + " returned " + responseCode + " " +
response.getStatusLine().getReasonPhrase());
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue next_submission;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic exception... " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue next_submission;
}
}
// if it got here, it must have worked
mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
}
if (c != null) {
c.close();
}
} // end while
return mResults;
}
|
diff --git a/srcj/com/sun/electric/tool/user/Clipboard.java b/srcj/com/sun/electric/tool/user/Clipboard.java
index 734d66d82..9903020a6 100755
--- a/srcj/com/sun/electric/tool/user/Clipboard.java
+++ b/srcj/com/sun/electric/tool/user/Clipboard.java
@@ -1,1348 +1,1348 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Clipboard.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 2 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.tool.user;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.geometry.Geometric;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.DisplayedText;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.user.ui.ClickZoomWireListener;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.ui.WindowFrame;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
/**
* Class for managing the circuitry clipboard (for copy and paste).
*/
public class Clipboard
{
/** The only Clipboard object. */ private static Clipboard theClipboard = new Clipboard();
/** The Clipboard Library. */ private static Library clipLib = null;
/** The Clipboard Cell. */ private static Cell clipCell;
/** the last node that was duplicated */ private static NodeInst lastDup = null;
/** the amount that the last node moved */ private static double lastDupX = 10, lastDupY = 10;
/**
* There is only one instance of this object (just one clipboard).
*/
private Clipboard() {}
/**
* Returns a printable version of this Clipboard.
* @return a printable version of this Clipboard.
*/
public String toString() { return "Clipboard"; }
// this is really only for debugging
public static void editClipboard()
{
EditWindow wnd = EditWindow.getCurrent();
wnd.setCell(clipCell, VarContext.globalContext);
}
/**
* Method to copy the selected objects to the clipboard.
*/
public static void copy()
{
// see what is highlighted
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<Geometric> highlightedGeoms = highlighter.getHighlightedEObjs(true, true);
List<DisplayedText> highlightedText = highlighter.getHighlightedText(true);
if (highlightedGeoms.size() == 0 && highlightedText.size() == 0)
{
System.out.println("First select objects to copy");
return;
}
// special case: if one text object is selected, copy its text to the system clipboard
copySelectedText(highlightedText);
// copy to Electric clipboard cell
new CopyObjects(wnd.getCell(), highlightedGeoms, highlightedText, User.getAlignmentToGrid());
}
/**
* Method to copy the selected objects to the clipboard and then delete them.
*/
public static void cut()
{
// see what is highlighted
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<Geometric> highlightedGeoms = highlighter.getHighlightedEObjs(true, true);
List<DisplayedText> highlightedText = highlighter.getHighlightedText(true);
if (highlightedGeoms.size() == 0 && highlightedText.size() == 0)
{
System.out.println("First select objects to cut");
return;
}
highlighter.clear();
highlighter.finished();
// special case: if one text object is selected, copy its text to the system clipboard
copySelectedText(highlightedText);
// cut from Electric, copy to clipboard cell
new CutObjects(wnd.getCell(), highlightedGeoms, highlightedText, User.getAlignmentToGrid(), User.isReconstructArcsToDeletedCells());
}
/**
* Method to paste the clipboard back into the current cell.
*/
public static void paste()
{
// get objects to paste
int nTotal = 0, aTotal = 0, vTotal = 0;
if (clipCell != null)
{
nTotal = clipCell.getNumNodes();
aTotal = clipCell.getNumArcs();
vTotal = clipCell.getNumVariables();
if (clipCell.getVar(User.FRAME_LAST_CHANGED_BY) != null) vTotal--; // discount this variable since it should not be copied.
}
int total = nTotal + aTotal + vTotal;
if (total == 0)
{
System.out.println("Nothing in the clipboard to paste");
return;
}
// find out where the paste is going
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
Cell parent = wnd.getCell();
// special case of pasting on top of selected objects
List<Geometric> geoms = highlighter.getHighlightedEObjs(true, true);
if (geoms.size() > 0)
{
// can only paste a single object onto selection
if (nTotal == 2 && aTotal == 1)
{
ArcInst ai = clipCell.getArcs().next();
NodeInst niHead = ai.getHeadPortInst().getNodeInst();
NodeInst niTail = ai.getTailPortInst().getNodeInst();
Iterator<NodeInst> nIt = clipCell.getNodes();
NodeInst ni1 = nIt.next();
NodeInst ni2 = nIt.next();
if ((ni1 == niHead && ni2 == niTail) ||
(ni1 == niTail && ni2 == niHead)) nTotal = 0;
total = nTotal + aTotal;
}
if (total > 1)
{
System.out.println("Can only paste a single object on top of selected objects");
return;
}
for(Geometric geom : geoms)
{
if (geom instanceof NodeInst && nTotal == 1)
{
NodeInst ni = (NodeInst)geom;
new PasteNodeToNode(ni, clipCell.getNodes().next());
} else if (geom instanceof ArcInst && aTotal == 1)
{
ArcInst ai = (ArcInst)geom;
new PasteArcToArc(ai, clipCell.getArcs().next());
}
}
return;
}
// make list of things to paste
List<Geometric> geomList = new ArrayList<Geometric>();
for(Iterator<NodeInst> it = clipCell.getNodes(); it.hasNext(); )
geomList.add(it.next());
for(Iterator<ArcInst> it = clipCell.getArcs(); it.hasNext(); )
geomList.add(it.next());
List<DisplayedText> textList = new ArrayList<DisplayedText>();
for (Iterator<Variable> it = clipCell.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (!var.isDisplay()) continue;
textList.add(new DisplayedText(clipCell, var.getKey()));
}
if (geomList.size() == 0 && textList.size() == 0) return;
if (User.isMoveAfterDuplicate())
{
EventListener currentListener = WindowFrame.getListener();
WindowFrame.setListener(new PasteListener(wnd, geomList, textList, currentListener));
} else
{
new PasteObjects(parent, geomList, textList, lastDupX, lastDupY,
User.getAlignmentToGrid(), User.isDupCopiesExports(), User.isArcsAutoIncremented());
}
}
/**
* Method to duplicate the selected objects.
*/
public static void duplicate()
{
// see what is highlighted
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<Geometric> geomList = highlighter.getHighlightedEObjs(true, true);
List<DisplayedText> textList = new ArrayList<DisplayedText>();
for (Iterator<Variable> it = clipCell.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (!var.isDisplay()) continue;
textList.add(new DisplayedText(clipCell, var.getKey()));
}
if (geomList.size() == 0 && textList.size() == 0)
{
System.out.println("First select objects to duplicate");
return;
}
// do duplication
if (User.isMoveAfterDuplicate())
{
EventListener currentListener = WindowFrame.getListener();
WindowFrame.setListener(new PasteListener(wnd, geomList, textList, currentListener));
} else
{
new DuplicateObjects(wnd.getCell(), geomList, textList, User.getAlignmentToGrid());
}
}
/**
* Method to track movement of the object that was just duplicated.
* By following subsequent changes to that node, future duplications know where to place their copies.
* @param ni the NodeInst that has just moved.
* @param lastX the previous center X of the NodeInst.
* @param lastY the previous center Y of the NodeInst.
*/
public static void nodeMoved(NodeInst ni, double lastX, double lastY)
{
if (ni != lastDup) return;
lastDupX += ni.getAnchorCenterX() - lastX;
lastDupY += ni.getAnchorCenterY() - lastY;
}
/**
* Helper method to copy any selected text to the system-wide clipboard.
*/
private static void copySelectedText(List<DisplayedText> highlightedText)
{
// must be one text selected
if (highlightedText.size() != 1) return;
// get the text
DisplayedText dt = highlightedText.get(0);
ElectricObject eObj = dt.getElectricObject();
Variable.Key varKey = dt.getVariableKey();
Variable var = eObj.getVar(varKey);
if (var == null) return;
String selected = var.describe(-1);
if (selected == null) return;
// put the text in the clipboard
java.awt.datatransfer.Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = new StringSelection(selected);
cb.setContents(transferable, null);
}
/****************************** CHANGE JOBS ******************************/
private static class CopyObjects extends Job
{
private Cell cell;
private List<Geometric> highlightedGeoms;
private List<DisplayedText> highlightedText;
private double alignment;
protected CopyObjects(Cell cell, List<Geometric> highlightedGeoms, List<DisplayedText> highlightedText, double alignment)
{
super("Copy", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.highlightedGeoms = highlightedGeoms;
this.highlightedText = highlightedText;
this.alignment = alignment;
startJob();
}
public boolean doIt() throws JobException
{
// remove contents of clipboard
clear();
// copy objects to clipboard
copyListToCell(clipCell, highlightedGeoms, highlightedText, null, null,
new Point2D.Double(0,0), User.isDupCopiesExports(), User.isArcsAutoIncremented(), alignment);
return true;
}
}
private static class CutObjects extends Job
{
private Cell cell;
private List<Geometric> geomList;
private List<DisplayedText> textList;
private double alignment;
private boolean reconstructArcs;
protected CutObjects(Cell cell, List<Geometric> geomList, List<DisplayedText> textList, double alignment, boolean reconstructArcs)
{
super("Cut", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.geomList = geomList;
this.textList = textList;
this.alignment = alignment;
this.reconstructArcs = reconstructArcs;
startJob();
}
public boolean doIt() throws JobException
{
// remove contents of clipboard
clear();
// make sure deletion is allowed
if (CircuitChangeJobs.cantEdit(cell, null, true) != 0) return false;
List<Highlight2> deleteList = new ArrayList<Highlight2>();
for(Geometric geom : geomList)
{
if (geom instanceof NodeInst)
{
int errorCode = CircuitChangeJobs.cantEdit(cell, (NodeInst)geom, true);
if (errorCode < 0) return false;
if (errorCode > 0) continue;
}
}
// copy objects to clipboard
copyListToCell(clipCell, geomList, textList, null, null,
new Point2D.Double(0, 0), User.isDupCopiesExports(), User.isArcsAutoIncremented(), alignment);
// and delete the original objects
CircuitChangeJobs.eraseObjectsInList(cell, geomList, reconstructArcs);
// kill variables on cells
for(DisplayedText dt : textList)
{
ElectricObject owner = dt.getElectricObject();
if (!(owner instanceof Cell)) continue;
owner.delVar(dt.getVariableKey());
}
return true;
}
}
private static class DuplicateObjects extends Job
{
private Cell cell;
private List<Geometric> geomList, newGeomList;
private List<DisplayedText> textList, newTextList;
private double alignment;
private NodeInst lastCreatedNode;
protected DuplicateObjects(Cell cell, List<Geometric> geomList, List<DisplayedText> textList, double alignment)
{
super("Duplicate", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.geomList = geomList;
this.textList = textList;
this.alignment = alignment;
startJob();
}
public boolean doIt() throws JobException
{
// copy objects to clipboard
newGeomList = new ArrayList<Geometric>();
newTextList = new ArrayList<DisplayedText>();
lastCreatedNode = copyListToCell(cell, geomList, textList, newGeomList, newTextList,
new Point2D.Double(lastDupX, lastDupY), User.isDupCopiesExports(), User.isArcsAutoIncremented(), alignment);
fieldVariableChanged("newGeomList");
fieldVariableChanged("newTextList");
fieldVariableChanged("lastCreatedNode");
return true;
}
public void terminateOK()
{
// remember the last node created
lastDup = lastCreatedNode;
// highlight the copy
showCopiedObjects(newGeomList, newTextList);
}
}
private static class PasteArcToArc extends Job
{
private ArcInst src, dst, newArc;
protected PasteArcToArc(ArcInst dst, ArcInst src)
{
super("Paste Arc to Arc", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.src = src;
this.dst = dst;
startJob();
}
public boolean doIt() throws JobException
{
// make sure pasting is allowed
if (CircuitChangeJobs.cantEdit(dst.getParent(), null, true) != 0) return false;
newArc = pasteArcToArc(dst, src);
if (newArc == null) System.out.println("Nothing was pasted"); else
fieldVariableChanged("newArc");
return true;
}
public void terminateOK()
{
if (newArc != null)
{
EditWindow wnd = EditWindow.getCurrent();
if (wnd != null)
{
Highlighter highlighter = wnd.getHighlighter();
if (highlighter != null)
{
highlighter.clear();
highlighter.addElectricObject(newArc, newArc.getParent());
highlighter.finished();
}
}
};
}
}
private static class PasteNodeToNode extends Job
{
private NodeInst src, dst, newNode;
protected PasteNodeToNode(NodeInst dst, NodeInst src)
{
super("Paste Node to Node", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.src = src;
this.dst = dst;
startJob();
}
public boolean doIt() throws JobException
{
// make sure pasting is allowed
if (CircuitChangeJobs.cantEdit(dst.getParent(), null, true) != 0) return false;
newNode = pasteNodeToNode(dst, src);
if (newNode == null) System.out.println("Nothing was pasted"); else
fieldVariableChanged("newNode");
return true;
}
public void terminateOK()
{
if (newNode != null)
{
EditWindow wnd = EditWindow.getCurrent();
if (wnd != null)
{
Highlighter highlighter = wnd.getHighlighter();
if (highlighter != null)
{
highlighter.clear();
highlighter.addElectricObject(newNode, newNode.getParent());
highlighter.finished();
}
}
}
}
}
private static class PasteObjects extends Job
{
private Cell cell;
private List<Geometric> geomList, newGeomList;
private List<DisplayedText> textList, newTextList;
private double dX, dY, alignment;
private boolean copyExports, uniqueArcs;
private NodeInst lastCreatedNode;
protected PasteObjects(Cell cell, List<Geometric> geomList, List<DisplayedText> textList,
double dX, double dY, double alignment, boolean copyExports, boolean uniqueArcs)
{
super("Paste", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.geomList = geomList;
this.textList = textList;
this.dX = dX;
this.dY = dY;
this.alignment = alignment;
this.copyExports = copyExports;
this.uniqueArcs = uniqueArcs;
startJob();
}
public boolean doIt() throws JobException
{
// make sure pasting is allowed
if (CircuitChangeJobs.cantEdit(cell, null, true) != 0) return false;
// paste them into the current cell
newGeomList = new ArrayList<Geometric>();
newTextList = new ArrayList<DisplayedText>();
lastCreatedNode = copyListToCell(cell, geomList, textList, newGeomList, newTextList,
new Point2D.Double(dX, dY), copyExports, uniqueArcs, alignment);
fieldVariableChanged("newGeomList");
fieldVariableChanged("newTextList");
fieldVariableChanged("lastCreatedNode");
return true;
}
public void terminateOK()
{
// remember the last node created
lastDup = lastCreatedNode;
// highlight the copy
showCopiedObjects(newGeomList, newTextList);
}
}
/****************************** CHANGE JOB SUPPORT ******************************/
/**
* Method to clear the clipboard.
*/
private static void init()
{
if (clipLib == null)
{
clipLib = Library.newInstance("Clipboard!!", null);
clipLib.setHidden();
}
if (clipCell == null)
{
clipCell = Cell.newInstance(clipLib, "Clipboard!!");
}
}
/**
* Method to clear the contents of the clipboard.
*/
public static void clear()
{
init();
// delete all arcs in the clipboard
List<ArcInst> arcsToDelete = new ArrayList<ArcInst>();
for(Iterator<ArcInst> it = clipCell.getArcs(); it.hasNext(); )
arcsToDelete.add(it.next());
for(ArcInst ai : arcsToDelete)
{
ai.kill();
}
// delete all exports in the clipboard
List<Export> exportsToDelete = new ArrayList<Export>();
for(Iterator<Export> it = clipCell.getExports(); it.hasNext(); )
exportsToDelete.add(it.next());
for(Export pp : exportsToDelete)
{
pp.kill();
}
// delete all nodes in the clipboard
List<NodeInst> nodesToDelete = new ArrayList<NodeInst>();
for(Iterator<NodeInst> it = clipCell.getNodes(); it.hasNext(); )
nodesToDelete.add(it.next());
for(NodeInst ni : nodesToDelete)
{
ni.kill();
}
// Delete all variables
List<Variable> varsToDelete = new ArrayList<Variable>();
for(Iterator<Variable> it = clipCell.getVariables(); it.hasNext(); )
{
Variable var = it.next();
clipCell.delVar(var.getKey());
//varsToDelete.add(var);
}
}
/**
* Method to copy the list of Geometrics to a new Cell.
* @param wnd the EditWindow in which this is happening (if null, do not highlight copied Geometrics).
* @param list the list of Geometrics to copy.
* @param fromCell the source cell of the Geometrics.
* @param toCell the destination cell of the Geometrics.
* @param delta an offset for all of the copied Geometrics.
* @param copyExports true to copy exports.
* @param uniqueArcs true to generate unique arc names.
* @return the last NodeInst that was created.
*/
public static NodeInst copyListToCell(Cell toCell, List<Geometric> geomList, List<DisplayedText> textList,
List<Geometric> newGeomList, List<DisplayedText> newTextList, Point2D delta, boolean copyExports, boolean uniqueArcs, double alignment)
{
// make a list of all objects to be copied (includes end points of arcs)
List<NodeInst> theNodes = new ArrayList<NodeInst>();
List<ArcInst> theArcs = new ArrayList<ArcInst>();
for (Geometric geom : geomList)
{
if (geom instanceof NodeInst)
{
if (!theNodes.contains(geom)) theNodes.add((NodeInst)geom);
}
if (geom instanceof ArcInst)
{
ArcInst ai = (ArcInst)geom;
theArcs.add(ai);
NodeInst head = ai.getHeadPortInst().getNodeInst();
NodeInst tail = ai.getTailPortInst().getNodeInst();
if (!theNodes.contains(head)) theNodes.add(head);
if (!theNodes.contains(tail)) theNodes.add(tail);
}
}
if (theNodes.size() == 0 && textList.size() == 0) return null;
// check for recursion
for(NodeInst ni : theNodes)
{
if (!ni.isCellInstance()) continue;
Cell niCell = (Cell)ni.getProto();
if (Cell.isInstantiationRecursive(niCell, toCell))
{
System.out.println("Cannot: that would be recursive (" +
toCell + " is beneath " + ni.getProto() + ")");
return null;
}
}
DBMath.gridAlign(delta, alignment);
double dX = delta.getX();
double dY = delta.getY();
// sort the nodes by name
Collections.sort(theNodes);
// create the new nodes
NodeInst lastCreatedNode = null;
HashMap<NodeInst,NodeInst> newNodes = new HashMap<NodeInst,NodeInst>();
List<PortInst> portInstsToExport = new ArrayList<PortInst>();
HashMap<PortInst,Export> originalExports = new HashMap<PortInst,Export>();
for(NodeInst ni : theNodes)
{
if (ni.getProto() == Generic.tech.cellCenterNode && toCell.alreadyCellCenter()) continue;
double width = ni.getXSize();
double height = ni.getYSize();
String name = null;
if (ni.isUsernamed())
name = ElectricObject.uniqueObjectName(ni.getName(), toCell, NodeInst.class);
double px = ni.getAnchorCenterX()+dX;
double py = ni.getAnchorCenterY()+dY;
px = DBMath.toNearest(px, User.getAlignmentToGrid());
py = DBMath.toNearest(py, User.getAlignmentToGrid());
NodeInst newNi = NodeInst.newInstance(ni.getProto(),
- new Point2D.Double(px, py),
+ new Point2D.Double(ni.getAnchorCenterX()+dX, ni.getAnchorCenterY()+dY),
width, height, toCell, ni.getOrient(), name, ni.getTechSpecific());
if (newNi == null)
{
System.out.println("Cannot create node");
return lastCreatedNode;
}
newNi.copyStateBits(ni);
newNi.copyTextDescriptorFrom(ni, NodeInst.NODE_PROTO);
newNi.copyTextDescriptorFrom(ni, NodeInst.NODE_NAME);
newNi.copyVarsFrom(ni);
newNodes.put(ni, newNi);
if (newGeomList != null) newGeomList.add(newNi);
lastCreatedNode = newNi;
// copy the ports, too
if (copyExports)
{
for(Iterator<Export> eit = ni.getExports(); eit.hasNext(); )
{
Export pp = eit.next();
PortInst pi = ExportChanges.getNewPortFromReferenceExport(newNi, pp);
portInstsToExport.add(pi);
originalExports.put(pi, pp);
}
}
}
if (copyExports)
ExportChanges.reExportPorts(toCell, portInstsToExport, true, true, false, originalExports);
HashMap<ArcInst,ArcInst> newArcs = new HashMap<ArcInst,ArcInst>();
if (theArcs.size() > 0)
{
// sort the arcs by name
Collections.sort(theArcs);
// for associating old names with new names
HashMap<String,String> newArcNames = new HashMap<String,String>();
// create the new arcs
for(ArcInst ai : theArcs)
{
PortInst oldHeadPi = ai.getHeadPortInst();
NodeInst headNi = newNodes.get(oldHeadPi.getNodeInst());
PortInst headPi = headNi.findPortInstFromProto(oldHeadPi.getPortProto());
PortInst oldTailPi = ai.getTailPortInst();
NodeInst tailNi = newNodes.get(oldTailPi.getNodeInst());
PortInst tailPi = tailNi.findPortInstFromProto(oldTailPi.getPortProto());
String name = null;
if (ai.isUsernamed())
{
name = ai.getName();
if (uniqueArcs)
{
String newName = newArcNames.get(name);
if (newName == null)
{
newName = ElectricObject.uniqueObjectName(name, toCell, ArcInst.class);
newArcNames.put(name, newName);
}
name = newName;
}
}
ArcInst newAr = ArcInst.newInstance(ai.getProto(), ai.getWidth(),
headPi, tailPi, new Point2D.Double(ai.getHeadLocation().getX() + dX, ai.getHeadLocation().getY() + dY),
new Point2D.Double(ai.getTailLocation().getX() + dX, ai.getTailLocation().getY() + dY), name, ai.getAngle());
if (newAr == null)
{
System.out.println("Cannot create arc");
return lastCreatedNode;
}
newAr.copyPropertiesFrom(ai);
newArcs.put(ai, newAr);
if (newGeomList != null) newGeomList.add(newAr);
}
}
// copy variables on cells
for(DisplayedText dt : textList)
{
ElectricObject eObj = dt.getElectricObject();
if (!(eObj instanceof Cell)) continue;
Variable.Key varKey = dt.getVariableKey();
Variable var = eObj.getVar(varKey);
double xP = var.getTextDescriptor().getXOff();
double yP = var.getTextDescriptor().getYOff();
Variable newv = toCell.newVar(varKey, var.getObject(), var.getTextDescriptor().withOff(xP+dX, yP+dY));
if (newTextList != null) newTextList.add(new DisplayedText(toCell, varKey));
}
return lastCreatedNode;
}
private static void showCopiedObjects(List<Geometric> newGeomList, List<DisplayedText> newTextList)
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd != null)
{
Cell cell = wnd.getCell();
Highlighter highlighter = wnd.getHighlighter();
highlighter.clear();
for(Geometric geom : newGeomList)
{
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
// special case for displayable text on invisible pins
if (ni.isInvisiblePinWithText())
{
Poly [] polys = ni.getAllText(false, wnd);
if (polys == null) continue;
for(int i=0; i<polys.length; i++)
{
Poly poly = polys[i];
if (poly == null) continue;
Highlight2 h = highlighter.addText(ni, cell, poly.getDisplayedText().getVariableKey());
}
continue;
}
}
highlighter.addElectricObject(geom, cell);
}
for(DisplayedText dt : newTextList)
{
highlighter.addText(dt.getElectricObject(), cell, dt.getVariableKey());
}
highlighter.finished();
}
}
/**
* Method to "paste" node "srcnode" onto node "destnode", making them the same.
* Returns the address of the destination node (null on error).
*/
private static NodeInst pasteNodeToNode(NodeInst destNode, NodeInst srcNode)
{
destNode = CircuitChangeJobs.replaceNodeInst(destNode, srcNode.getProto(), true, false);
if (destNode == null) return null;
destNode.clearExpanded();
if (srcNode.isExpanded()) destNode.setExpanded();
if (!destNode.isCellInstance() && !srcNode.isCellInstance()) {
if (srcNode.getProto().getTechnology() == destNode.getProto().getTechnology()) {
Technology tech = srcNode.getProto().getTechnology();
tech.setPrimitiveFunction(destNode, srcNode.getFunction());
}
}
// make the sizes the same if they are primitives
if (!destNode.isCellInstance())
{
double dX = srcNode.getXSize() - destNode.getXSize();
double dY = srcNode.getYSize() - destNode.getYSize();
if (dX != 0 || dY != 0)
{
destNode.resize(dX, dY);
}
}
// remove variables that are not on the pasted object
boolean checkAgain = true;
while (checkAgain)
{
checkAgain = false;
for(Iterator<Variable> it = destNode.getVariables(); it.hasNext(); )
{
Variable destVar = it.next();
Variable.Key key = destVar.getKey();
Variable srcVar = srcNode.getVar(key);
if (srcVar != null) continue;
destNode.delVar(key);
checkAgain = true;
break;
}
}
// make sure all variables are on the node
destNode.copyVarsFrom(srcNode);
// copy any special user bits
destNode.copyStateBits(srcNode);
destNode.clearExpanded();
if (srcNode.isExpanded()) destNode.setExpanded();
destNode.clearLocked();
return(destNode);
}
/**
* Method to paste one arc onto another.
* @param destArc the destination arc that will be replaced.
* @param srcArc the source arc that will replace it.
* @return the replaced arc (null on error).
*/
private static ArcInst pasteArcToArc(ArcInst destArc, ArcInst srcArc)
{
// make sure they have the same type
if (destArc.getProto() != srcArc.getProto())
{
destArc = destArc.replace(srcArc.getProto());
if (destArc == null) return null;
}
// make the widths the same
double dw = srcArc.getWidth() - destArc.getWidth();
if (dw != 0)
destArc.modify(dw, 0, 0, 0, 0);
// remove variables that are not on the pasted object
boolean checkAgain = true;
while (checkAgain)
{
checkAgain = false;
for(Iterator<Variable> it = destArc.getVariables(); it.hasNext(); )
{
Variable destVar = it.next();
Variable.Key key = destVar.getKey();
Variable srcVar = srcArc.getVar(key);
if (srcVar != null) continue;
destArc.delVar(key);
checkAgain = true;
break;
}
}
// make sure all variables are on the arc
for(Iterator<Variable> it = srcArc.getVariables(); it.hasNext(); )
{
Variable srcVar = it.next();
Variable.Key key = srcVar.getKey();
Variable destVar = destArc.newVar(key, srcVar.getObject(), srcVar.getTextDescriptor());
}
// make sure the constraints and other userbits are the same
destArc.copyPropertiesFrom(srcArc);
return destArc;
}
/****************************** PASTE LISTENER ******************************/
/**
* Class to handle the interactive drag after a paste.
*/
private static class PasteListener
implements MouseMotionListener, MouseListener, MouseWheelListener, KeyListener
{
private EditWindow wnd;
private List<Geometric> geomList;
private List<DisplayedText> textList;
private EventListener currentListener;
private Rectangle2D pasteBounds;
private double translateX;
private double translateY;
private Point2D lastMouseDB; // last point where mouse was (in db units)
private JPopupMenu popup;
/** paste anchor types */
/**
* Create a new paste listener
* @param wnd Controlling window
* @param pasteList list of objects to paste
* @param currentListener listener to restore when done
*/
private PasteListener(EditWindow wnd, List<Geometric> geomList, List<DisplayedText> textList, EventListener currentListener)
{
this.wnd = wnd;
this.geomList = geomList;
this.textList = textList;
this.currentListener = currentListener;
this.pasteBounds = getPasteBounds(geomList, textList, wnd);
translateX = translateY = 0;
initPopup();
// get starting point from current mouse location
Point2D mouse = ClickZoomWireListener.theOne.getLastMouse();
Point2D mouseDB = wnd.screenToDatabase((int)mouse.getX(), (int)mouse.getY());
Point2D delta = getDelta(mouseDB, false);
wnd.getHighlighter().pushHighlight();
showList(delta);
}
/**
* Gets grid-aligned delta translation for nodes based on mouse location
* @param mouseDB the location of the mouse
* @param orthogonal if the translation is orthogonal only
* @return a grid-aligned delta
*/
private Point2D getDelta(Point2D mouseDB, boolean orthogonal)
{
// mouseDB == null if you press arrow keys before placing the new copy
if (mouseDB == null) return null;
double alignment = User.getAlignmentToGrid();
DBMath.gridAlign(mouseDB, alignment);
// this is the point on the clipboard cell that will be pasted at the mouse location
Point2D refPastePoint = new Point2D.Double(pasteBounds.getCenterX() + translateX,
pasteBounds.getCenterY() + translateY);
double deltaX = mouseDB.getX() - refPastePoint.getX();
double deltaY = mouseDB.getY() - refPastePoint.getY();
// if orthogonal is true, convert to orthogonal
if (orthogonal) {
// only use delta in direction that has larger delta
if (Math.abs(deltaX) > Math.abs(deltaY)) deltaY = 0;
else deltaX = 0;
}
// this is now a delta, not a point
refPastePoint.setLocation(deltaX, deltaY);
DBMath.gridAlign(refPastePoint, alignment);
return refPastePoint;
}
/**
* Show the objects to paste with the anchor point at 'mouseDB'
* @param delta the translation for the highlights
*/
private void showList(Point2D delta)
{
// if delta==null, problems to get mouseDB pointer
if (delta == null) return;
// find offset of highlights
double oX = delta.getX();
double oY = delta.getY();
Cell cell = wnd.getCell();
Highlighter highlighter = wnd.getHighlighter();
highlighter.clear();
// for(DisplayedText dt : textList)
// {
// ElectricObject eObj = dt.getElectricObject();
// Variable var = eObj.getVar(dt.getVariableKey());
// Poly poly = clipCell.computeTextPoly(wnd, var, null);
// showPoints(poly.getPoints(), oX, oY, cell, highlighter);
// }
for(Geometric geom : geomList)
{
if (geom instanceof ArcInst)
{
ArcInst ai = (ArcInst)geom;
Poly poly = ai.makePoly(ai.getWidth() - ai.getProto().getWidthOffset(), Poly.Type.CLOSED);
Point2D [] points = poly.getPoints();
showPoints(points, oX, oY, cell, highlighter);
continue;
}
NodeInst ni = (NodeInst)geom;
if (ni.isInvisiblePinWithText())
{
// find text on the invisible pin
boolean found = false;
for(Iterator<Variable> vIt = ni.getVariables(); vIt.hasNext(); )
{
Variable var = vIt.next();
if (var.isDisplay())
{
Point2D [] points = Highlighter.describeHighlightText(wnd, geom, var.getKey());
showPoints(points, oX, oY, cell, highlighter);
found = true;
break;
}
}
if (found) continue;
}
SizeOffset so = ni.getSizeOffset();
AffineTransform trans = ni.rotateOutAboutTrueCenter();
double nodeLowX = ni.getTrueCenterX() - ni.getXSize()/2 + so.getLowXOffset();
double nodeHighX = ni.getTrueCenterX() + ni.getXSize()/2 - so.getHighXOffset();
double nodeLowY = ni.getTrueCenterY() - ni.getYSize()/2 + so.getLowYOffset();
double nodeHighY = ni.getTrueCenterY() + ni.getYSize()/2 - so.getHighYOffset();
double nodeX = (nodeLowX + nodeHighX) / 2;
double nodeY = (nodeLowY + nodeHighY) / 2;
Poly poly = new Poly(nodeX, nodeY, nodeHighX-nodeLowX, nodeHighY-nodeLowY);
poly.transform(trans);
showPoints(poly.getPoints(), oX, oY, cell, highlighter);
}
// show delta from original
Rectangle2D bounds = wnd.getDisplayedBounds();
highlighter.addMessage(cell, "("+(int)oX+","+(int)oY+")",
new Point2D.Double(bounds.getCenterX(),bounds.getCenterY()));
// also draw arrow if user has moved highlights off the screen
double halfWidth = 0.5*pasteBounds.getWidth();
double halfHeight = 0.5*pasteBounds.getHeight();
if (Math.abs(translateX) > halfWidth || Math.abs(translateY) > halfHeight)
{
Rectangle2D transBounds = new Rectangle2D.Double(pasteBounds.getX()+oX, pasteBounds.getY()+oY,
pasteBounds.getWidth(), pasteBounds.getHeight());
Poly p = new Poly(transBounds);
Point2D endPoint = p.closestPoint(lastMouseDB);
// draw arrow
highlighter.addLine(lastMouseDB, endPoint, cell);
int angle = GenMath.figureAngle(lastMouseDB, endPoint);
angle += 1800;
int angleOfArrow = 300; // 30 degrees
int backAngle1 = angle - angleOfArrow;
int backAngle2 = angle + angleOfArrow;
Point2D p1 = new Point2D.Double(endPoint.getX() + DBMath.cos(backAngle1), endPoint.getY() + DBMath.sin(backAngle1));
Point2D p2 = new Point2D.Double(endPoint.getX() + DBMath.cos(backAngle2), endPoint.getY() + DBMath.sin(backAngle2));
highlighter.addLine(endPoint, p1, cell);
highlighter.addLine(endPoint, p2, cell);
}
highlighter.finished();
}
private void showPoints(Point2D [] points, double oX, double oY, Cell cell, Highlighter highlighter)
{
for(int i=0; i<points.length; i++)
{
int lastI = i - 1;
if (lastI < 0) lastI = points.length - 1;
double fX = points[lastI].getX();
double fY = points[lastI].getY();
double tX = points[i].getX();
double tY = points[i].getY();
highlighter.addLine(new Point2D.Double(fX+oX, fY+oY), new Point2D.Double(tX+oX, tY+oY), cell);
}
}
public void mousePressed(MouseEvent e)
{
if (e.isMetaDown()) {
// right click
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
public void mouseDragged(MouseEvent evt)
{
mouseMoved(evt);
}
public void mouseReleased(MouseEvent evt)
{
if (evt.isMetaDown()) {
// right click
return;
}
boolean ctrl = (evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
Point2D mouseDB = wnd.screenToDatabase((int)evt.getX(), (int)evt.getY());
Point2D delta = getDelta(mouseDB, ctrl);
showList(delta);
WindowFrame.setListener(currentListener);
wnd.getHighlighter().popHighlight();
Cell cell = WindowFrame.needCurCell();
if (cell != null)
new PasteObjects(cell, geomList, textList, delta.getX(), delta.getY(),
User.getAlignmentToGrid(), User.isDupCopiesExports(), User.isArcsAutoIncremented());
}
public void mouseMoved(MouseEvent evt)
{
boolean ctrl = (evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
Point2D mouseDB = wnd.screenToDatabase((int)evt.getX(), (int)evt.getY());
Point2D delta = getDelta(mouseDB, ctrl);
lastMouseDB = mouseDB;
showList(delta);
wnd.repaint();
}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
public void mouseWheelMoved(MouseWheelEvent e) {}
public void keyPressed(KeyEvent evt) {
boolean ctrl = (evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
int chr = evt.getKeyCode();
if (chr == KeyEvent.VK_ESCAPE) {
// abort on ESC
abort();
}
else if (chr == KeyEvent.VK_UP) {
moveObjectsUp();
}
else if (chr == KeyEvent.VK_DOWN) {
moveObjectsDown();
}
else if (chr == KeyEvent.VK_LEFT) {
moveObjectsLeft();
}
else if (chr == KeyEvent.VK_RIGHT) {
moveObjectsRight();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
private void abort() {
wnd.getHighlighter().clear();
wnd.getHighlighter().finished();
WindowFrame.setListener(currentListener);
wnd.repaint();
}
private void initPopup() {
popup = new JPopupMenu();
JMenuItem m;
m = new JMenuItem("Move objects left");
m.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
m.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { moveObjectsLeft(); }
});
popup.add(m);
m = new JMenuItem("Move objects right");
m.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
m.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { moveObjectsRight(); }
});
popup.add(m);
m = new JMenuItem("Move objects up");
m.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
m.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { moveObjectsUp(); }
});
popup.add(m);
m = new JMenuItem("Move objects down");
m.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
m.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { moveObjectsDown(); }
});
popup.add(m);
m = new JMenuItem("Abort");
m.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
m.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { abort(); }
});
popup.add(m);
}
private void moveObjectsLeft() {
translateX += 0.5*pasteBounds.getWidth();
Point2D delta = getDelta(lastMouseDB, false);
showList(delta);
}
private void moveObjectsRight() {
translateX -= 0.5*pasteBounds.getWidth();
Point2D delta = getDelta(lastMouseDB, false);
showList(delta);
}
private void moveObjectsUp() {
translateY -= 0.5*pasteBounds.getHeight();
Point2D delta = getDelta(lastMouseDB, false);
showList(delta);
}
private void moveObjectsDown() {
translateY += 0.5*pasteBounds.getHeight();
Point2D delta = getDelta(lastMouseDB, false);
showList(delta);
}
/**
* Gets a boundary representing the paste bounds of the list of objects.
* The corners and center point of the bounds can be used as anchors
* when pasting the objects interactively. This is all done in database units.
* Note: you will likely want to grid align any points before using them.
* @param pasteList a list of Geometrics to paste
* @return a Rectangle2D that is the paste bounds.
*/
private static Rectangle2D getPasteBounds(List<Geometric> geomList, List<DisplayedText> textList, EditWindow wnd) {
Point2D llcorner = null;
Point2D urcorner = null;
// figure out lower-left corner and upper-rigth corner of this collection of objects
for(DisplayedText dt : textList)
{
ElectricObject eObj = dt.getElectricObject();
Poly poly = clipCell.computeTextPoly(wnd, dt.getVariableKey());
Rectangle2D bounds = poly.getBounds2D();
if (llcorner == null) {
llcorner = new Point2D.Double(bounds.getMinX(), bounds.getMinY());
urcorner = new Point2D.Double(bounds.getMaxX(), bounds.getMaxY());
continue;
}
if (bounds.getMinX() < llcorner.getX()) llcorner.setLocation(bounds.getMinX(), llcorner.getY());
if (bounds.getMinY() < llcorner.getY()) llcorner.setLocation(llcorner.getX(), bounds.getMinY());
if (bounds.getMaxX() > urcorner.getX()) urcorner.setLocation(bounds.getMaxX(), urcorner.getY());
if (bounds.getMaxY() > urcorner.getY()) urcorner.setLocation(urcorner.getX(), bounds.getMaxY());
}
for(Geometric geom : geomList)
{
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
Point2D pt = ni.getAnchorCenter();
if (llcorner == null) {
llcorner = new Point2D.Double(pt.getX(), pt.getY());
urcorner = new Point2D.Double(pt.getX(), pt.getY());
continue;
}
if (pt.getX() < llcorner.getX()) llcorner.setLocation(pt.getX(), llcorner.getY());
if (pt.getY() < llcorner.getY()) llcorner.setLocation(llcorner.getX(), pt.getY());
if (pt.getX() > urcorner.getX()) urcorner.setLocation(pt.getX(), urcorner.getY());
if (pt.getY() > urcorner.getY()) urcorner.setLocation(urcorner.getX(), pt.getY());
} else
{
ArcInst ai = (ArcInst)geom;
double wid = ai.getWidth() - ai.getProto().getWidthOffset();
Poly poly = ai.makePoly(wid, Poly.Type.FILLED);
Rectangle2D bounds = poly.getBounds2D();
if (llcorner == null) {
llcorner = new Point2D.Double(bounds.getMinX(), bounds.getMinY());
urcorner = new Point2D.Double(bounds.getMaxX(), bounds.getMaxY());
continue;
}
if (bounds.getMinX() < llcorner.getX()) llcorner.setLocation(bounds.getMinX(), llcorner.getY());
if (bounds.getMinY() < llcorner.getY()) llcorner.setLocation(llcorner.getX(), bounds.getMinY());
if (bounds.getMaxX() > urcorner.getX()) urcorner.setLocation(bounds.getMaxX(), urcorner.getY());
if (bounds.getMaxY() > urcorner.getY()) urcorner.setLocation(urcorner.getX(), bounds.getMaxY());
}
}
// figure bounds
double width = urcorner.getX() - llcorner.getX();
double height = urcorner.getY() - llcorner.getY();
Rectangle2D bounds = new Rectangle2D.Double(llcorner.getX(), llcorner.getY(), width, height);
return bounds;
}
}
}
| true | true | public static NodeInst copyListToCell(Cell toCell, List<Geometric> geomList, List<DisplayedText> textList,
List<Geometric> newGeomList, List<DisplayedText> newTextList, Point2D delta, boolean copyExports, boolean uniqueArcs, double alignment)
{
// make a list of all objects to be copied (includes end points of arcs)
List<NodeInst> theNodes = new ArrayList<NodeInst>();
List<ArcInst> theArcs = new ArrayList<ArcInst>();
for (Geometric geom : geomList)
{
if (geom instanceof NodeInst)
{
if (!theNodes.contains(geom)) theNodes.add((NodeInst)geom);
}
if (geom instanceof ArcInst)
{
ArcInst ai = (ArcInst)geom;
theArcs.add(ai);
NodeInst head = ai.getHeadPortInst().getNodeInst();
NodeInst tail = ai.getTailPortInst().getNodeInst();
if (!theNodes.contains(head)) theNodes.add(head);
if (!theNodes.contains(tail)) theNodes.add(tail);
}
}
if (theNodes.size() == 0 && textList.size() == 0) return null;
// check for recursion
for(NodeInst ni : theNodes)
{
if (!ni.isCellInstance()) continue;
Cell niCell = (Cell)ni.getProto();
if (Cell.isInstantiationRecursive(niCell, toCell))
{
System.out.println("Cannot: that would be recursive (" +
toCell + " is beneath " + ni.getProto() + ")");
return null;
}
}
DBMath.gridAlign(delta, alignment);
double dX = delta.getX();
double dY = delta.getY();
// sort the nodes by name
Collections.sort(theNodes);
// create the new nodes
NodeInst lastCreatedNode = null;
HashMap<NodeInst,NodeInst> newNodes = new HashMap<NodeInst,NodeInst>();
List<PortInst> portInstsToExport = new ArrayList<PortInst>();
HashMap<PortInst,Export> originalExports = new HashMap<PortInst,Export>();
for(NodeInst ni : theNodes)
{
if (ni.getProto() == Generic.tech.cellCenterNode && toCell.alreadyCellCenter()) continue;
double width = ni.getXSize();
double height = ni.getYSize();
String name = null;
if (ni.isUsernamed())
name = ElectricObject.uniqueObjectName(ni.getName(), toCell, NodeInst.class);
double px = ni.getAnchorCenterX()+dX;
double py = ni.getAnchorCenterY()+dY;
px = DBMath.toNearest(px, User.getAlignmentToGrid());
py = DBMath.toNearest(py, User.getAlignmentToGrid());
NodeInst newNi = NodeInst.newInstance(ni.getProto(),
new Point2D.Double(px, py),
width, height, toCell, ni.getOrient(), name, ni.getTechSpecific());
if (newNi == null)
{
System.out.println("Cannot create node");
return lastCreatedNode;
}
newNi.copyStateBits(ni);
newNi.copyTextDescriptorFrom(ni, NodeInst.NODE_PROTO);
newNi.copyTextDescriptorFrom(ni, NodeInst.NODE_NAME);
newNi.copyVarsFrom(ni);
newNodes.put(ni, newNi);
if (newGeomList != null) newGeomList.add(newNi);
lastCreatedNode = newNi;
// copy the ports, too
if (copyExports)
{
for(Iterator<Export> eit = ni.getExports(); eit.hasNext(); )
{
Export pp = eit.next();
PortInst pi = ExportChanges.getNewPortFromReferenceExport(newNi, pp);
portInstsToExport.add(pi);
originalExports.put(pi, pp);
}
}
}
if (copyExports)
ExportChanges.reExportPorts(toCell, portInstsToExport, true, true, false, originalExports);
HashMap<ArcInst,ArcInst> newArcs = new HashMap<ArcInst,ArcInst>();
if (theArcs.size() > 0)
{
// sort the arcs by name
Collections.sort(theArcs);
// for associating old names with new names
HashMap<String,String> newArcNames = new HashMap<String,String>();
// create the new arcs
for(ArcInst ai : theArcs)
{
PortInst oldHeadPi = ai.getHeadPortInst();
NodeInst headNi = newNodes.get(oldHeadPi.getNodeInst());
PortInst headPi = headNi.findPortInstFromProto(oldHeadPi.getPortProto());
PortInst oldTailPi = ai.getTailPortInst();
NodeInst tailNi = newNodes.get(oldTailPi.getNodeInst());
PortInst tailPi = tailNi.findPortInstFromProto(oldTailPi.getPortProto());
String name = null;
if (ai.isUsernamed())
{
name = ai.getName();
if (uniqueArcs)
{
String newName = newArcNames.get(name);
if (newName == null)
{
newName = ElectricObject.uniqueObjectName(name, toCell, ArcInst.class);
newArcNames.put(name, newName);
}
name = newName;
}
}
ArcInst newAr = ArcInst.newInstance(ai.getProto(), ai.getWidth(),
headPi, tailPi, new Point2D.Double(ai.getHeadLocation().getX() + dX, ai.getHeadLocation().getY() + dY),
new Point2D.Double(ai.getTailLocation().getX() + dX, ai.getTailLocation().getY() + dY), name, ai.getAngle());
if (newAr == null)
{
System.out.println("Cannot create arc");
return lastCreatedNode;
}
newAr.copyPropertiesFrom(ai);
newArcs.put(ai, newAr);
if (newGeomList != null) newGeomList.add(newAr);
}
}
// copy variables on cells
for(DisplayedText dt : textList)
{
ElectricObject eObj = dt.getElectricObject();
if (!(eObj instanceof Cell)) continue;
Variable.Key varKey = dt.getVariableKey();
Variable var = eObj.getVar(varKey);
double xP = var.getTextDescriptor().getXOff();
double yP = var.getTextDescriptor().getYOff();
Variable newv = toCell.newVar(varKey, var.getObject(), var.getTextDescriptor().withOff(xP+dX, yP+dY));
if (newTextList != null) newTextList.add(new DisplayedText(toCell, varKey));
}
return lastCreatedNode;
}
| public static NodeInst copyListToCell(Cell toCell, List<Geometric> geomList, List<DisplayedText> textList,
List<Geometric> newGeomList, List<DisplayedText> newTextList, Point2D delta, boolean copyExports, boolean uniqueArcs, double alignment)
{
// make a list of all objects to be copied (includes end points of arcs)
List<NodeInst> theNodes = new ArrayList<NodeInst>();
List<ArcInst> theArcs = new ArrayList<ArcInst>();
for (Geometric geom : geomList)
{
if (geom instanceof NodeInst)
{
if (!theNodes.contains(geom)) theNodes.add((NodeInst)geom);
}
if (geom instanceof ArcInst)
{
ArcInst ai = (ArcInst)geom;
theArcs.add(ai);
NodeInst head = ai.getHeadPortInst().getNodeInst();
NodeInst tail = ai.getTailPortInst().getNodeInst();
if (!theNodes.contains(head)) theNodes.add(head);
if (!theNodes.contains(tail)) theNodes.add(tail);
}
}
if (theNodes.size() == 0 && textList.size() == 0) return null;
// check for recursion
for(NodeInst ni : theNodes)
{
if (!ni.isCellInstance()) continue;
Cell niCell = (Cell)ni.getProto();
if (Cell.isInstantiationRecursive(niCell, toCell))
{
System.out.println("Cannot: that would be recursive (" +
toCell + " is beneath " + ni.getProto() + ")");
return null;
}
}
DBMath.gridAlign(delta, alignment);
double dX = delta.getX();
double dY = delta.getY();
// sort the nodes by name
Collections.sort(theNodes);
// create the new nodes
NodeInst lastCreatedNode = null;
HashMap<NodeInst,NodeInst> newNodes = new HashMap<NodeInst,NodeInst>();
List<PortInst> portInstsToExport = new ArrayList<PortInst>();
HashMap<PortInst,Export> originalExports = new HashMap<PortInst,Export>();
for(NodeInst ni : theNodes)
{
if (ni.getProto() == Generic.tech.cellCenterNode && toCell.alreadyCellCenter()) continue;
double width = ni.getXSize();
double height = ni.getYSize();
String name = null;
if (ni.isUsernamed())
name = ElectricObject.uniqueObjectName(ni.getName(), toCell, NodeInst.class);
double px = ni.getAnchorCenterX()+dX;
double py = ni.getAnchorCenterY()+dY;
px = DBMath.toNearest(px, User.getAlignmentToGrid());
py = DBMath.toNearest(py, User.getAlignmentToGrid());
NodeInst newNi = NodeInst.newInstance(ni.getProto(),
new Point2D.Double(ni.getAnchorCenterX()+dX, ni.getAnchorCenterY()+dY),
width, height, toCell, ni.getOrient(), name, ni.getTechSpecific());
if (newNi == null)
{
System.out.println("Cannot create node");
return lastCreatedNode;
}
newNi.copyStateBits(ni);
newNi.copyTextDescriptorFrom(ni, NodeInst.NODE_PROTO);
newNi.copyTextDescriptorFrom(ni, NodeInst.NODE_NAME);
newNi.copyVarsFrom(ni);
newNodes.put(ni, newNi);
if (newGeomList != null) newGeomList.add(newNi);
lastCreatedNode = newNi;
// copy the ports, too
if (copyExports)
{
for(Iterator<Export> eit = ni.getExports(); eit.hasNext(); )
{
Export pp = eit.next();
PortInst pi = ExportChanges.getNewPortFromReferenceExport(newNi, pp);
portInstsToExport.add(pi);
originalExports.put(pi, pp);
}
}
}
if (copyExports)
ExportChanges.reExportPorts(toCell, portInstsToExport, true, true, false, originalExports);
HashMap<ArcInst,ArcInst> newArcs = new HashMap<ArcInst,ArcInst>();
if (theArcs.size() > 0)
{
// sort the arcs by name
Collections.sort(theArcs);
// for associating old names with new names
HashMap<String,String> newArcNames = new HashMap<String,String>();
// create the new arcs
for(ArcInst ai : theArcs)
{
PortInst oldHeadPi = ai.getHeadPortInst();
NodeInst headNi = newNodes.get(oldHeadPi.getNodeInst());
PortInst headPi = headNi.findPortInstFromProto(oldHeadPi.getPortProto());
PortInst oldTailPi = ai.getTailPortInst();
NodeInst tailNi = newNodes.get(oldTailPi.getNodeInst());
PortInst tailPi = tailNi.findPortInstFromProto(oldTailPi.getPortProto());
String name = null;
if (ai.isUsernamed())
{
name = ai.getName();
if (uniqueArcs)
{
String newName = newArcNames.get(name);
if (newName == null)
{
newName = ElectricObject.uniqueObjectName(name, toCell, ArcInst.class);
newArcNames.put(name, newName);
}
name = newName;
}
}
ArcInst newAr = ArcInst.newInstance(ai.getProto(), ai.getWidth(),
headPi, tailPi, new Point2D.Double(ai.getHeadLocation().getX() + dX, ai.getHeadLocation().getY() + dY),
new Point2D.Double(ai.getTailLocation().getX() + dX, ai.getTailLocation().getY() + dY), name, ai.getAngle());
if (newAr == null)
{
System.out.println("Cannot create arc");
return lastCreatedNode;
}
newAr.copyPropertiesFrom(ai);
newArcs.put(ai, newAr);
if (newGeomList != null) newGeomList.add(newAr);
}
}
// copy variables on cells
for(DisplayedText dt : textList)
{
ElectricObject eObj = dt.getElectricObject();
if (!(eObj instanceof Cell)) continue;
Variable.Key varKey = dt.getVariableKey();
Variable var = eObj.getVar(varKey);
double xP = var.getTextDescriptor().getXOff();
double yP = var.getTextDescriptor().getYOff();
Variable newv = toCell.newVar(varKey, var.getObject(), var.getTextDescriptor().withOff(xP+dX, yP+dY));
if (newTextList != null) newTextList.add(new DisplayedText(toCell, varKey));
}
return lastCreatedNode;
}
|
diff --git a/src/main/java/net/nexisonline/spade/SpadeWorldListener.java b/src/main/java/net/nexisonline/spade/SpadeWorldListener.java
index 6dcb195..42d82c0 100644
--- a/src/main/java/net/nexisonline/spade/SpadeWorldListener.java
+++ b/src/main/java/net/nexisonline/spade/SpadeWorldListener.java
@@ -1,184 +1,184 @@
package net.nexisonline.spade;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import net.nexisonline.spade.populators.DungeonPopulator;
import org.bukkit.World;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.WorldListener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.generator.BlockPopulator;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.reader.UnicodeReader;
public class SpadeWorldListener extends WorldListener {
private SpadePlugin spade;
private Collection<String> worlds;
private Map<String, Object> root;
private Yaml yaml;
public SpadeWorldListener(SpadePlugin plugin) {
spade = plugin;
}
@Override
public void onChunkLoad(ChunkLoadEvent e) {
for (BlockPopulator bp : e.getWorld().getPopulators()) {
if (bp instanceof DungeonPopulator) {
((DungeonPopulator) bp).onChunkLoad(e.getChunk().getX(), e.getChunk().getZ());
}
}
}
@Override
public void onWorldLoad(WorldLoadEvent e) {
}
@Override
public void onWorldSave(WorldSaveEvent e) {
saveWorlds();
}
@SuppressWarnings("unchecked")
private void load() {
DumperOptions options = new DumperOptions();
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yaml = new Yaml(options);
FileInputStream stream = null;
File file = new File(spade.getDataFolder(), "Spade.yml");
if(!file.exists())
return;
try {
stream = new FileInputStream(file);
root=(Map<String,Object>)yaml.load(new UnicodeReader(stream));
} catch (IOException e) {
root = new HashMap<String, Object>();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {}
}
}
@SuppressWarnings("unchecked")
public void loadWorlds() {
load();
Object co = null;
- if(root.containsKey("worlds")) {
+ if(root!=null && root.containsKey("worlds")) {
co = root.get("worlds");
if(co instanceof Map<?,?>) {
Map<String,Object> worldMap = (Map<String, Object>) root.get("worlds");
worlds = worldMap.keySet();
for (String worldName : this.worlds) {
Map<String,Object> currWorld = (Map<String, Object>) worldMap.get(worldName);
Map<String,Object> limits = (Map<String, Object>) currWorld.get("limits");
Long seed = (Long) ((currWorld.get("seed")==null)?((new Random()).nextLong()):currWorld.get("seed"));
spade.genLimits.put(worldName.toLowerCase(), new GenerationLimits(limits));
Map<String,Object> chunkManager = (Map<String, Object>) currWorld.get("chunk-manager");
if(chunkManager == null) {
chunkManager = new HashMap<String,Object>();
chunkManager.put("name", "stock");
}
Map<String,Object> chunkProvider = (Map<String, Object>) currWorld.get("chunk-provider");
if(chunkProvider == null) {
chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
}
spade.loadWorld(worldName, seed, (String)chunkManager.get("name"), (String)chunkProvider.get("name"), (Map<String,Object>)chunkProvider.get("config"));
}
}
} else {
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
chunkProvider.put("config", null);
world.put("chunk-provider",chunkProvider);
}
{
world.put("limits", (new GenerationLimits()).getConfig());
}
root.put(worldName, world);
}
save();
}
}
private void save() {
FileOutputStream stream = null;
File file = new File(spade.getDataFolder(), "Spade.yml");
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
try {
stream = new FileOutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
writer.append("\r\n# Spade Terrain Generator Plugin");
writer.append("\r\n# Configuration File");
writer.append("\r\n# ");
writer.append("\r\n# AUTOMATICALLY GENERATED");
writer.append("\r\n");
yaml.dump(root, writer);
return;
} catch (IOException e) {} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {}
}
return;
}
public void saveWorlds() {
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
if (w.getGenerator() instanceof SpadeChunkProvider) {
SpadeChunkProvider cp = (SpadeChunkProvider) w.getGenerator();
chunkProvider.put("name", spade.getNameForClass(cp));
chunkProvider.put("config", cp.getConfig());
} else {
chunkProvider.put("name", "stock");
}
world.put("chunk-provider",chunkProvider);
}
{
spade.genLimits.get(worldName.toLowerCase());
world.put("limits", (new GenerationLimits()).getConfig());
}
root.put(worldName, world);
}
save();
}
}
| true | true | public void loadWorlds() {
load();
Object co = null;
if(root.containsKey("worlds")) {
co = root.get("worlds");
if(co instanceof Map<?,?>) {
Map<String,Object> worldMap = (Map<String, Object>) root.get("worlds");
worlds = worldMap.keySet();
for (String worldName : this.worlds) {
Map<String,Object> currWorld = (Map<String, Object>) worldMap.get(worldName);
Map<String,Object> limits = (Map<String, Object>) currWorld.get("limits");
Long seed = (Long) ((currWorld.get("seed")==null)?((new Random()).nextLong()):currWorld.get("seed"));
spade.genLimits.put(worldName.toLowerCase(), new GenerationLimits(limits));
Map<String,Object> chunkManager = (Map<String, Object>) currWorld.get("chunk-manager");
if(chunkManager == null) {
chunkManager = new HashMap<String,Object>();
chunkManager.put("name", "stock");
}
Map<String,Object> chunkProvider = (Map<String, Object>) currWorld.get("chunk-provider");
if(chunkProvider == null) {
chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
}
spade.loadWorld(worldName, seed, (String)chunkManager.get("name"), (String)chunkProvider.get("name"), (Map<String,Object>)chunkProvider.get("config"));
}
}
} else {
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
chunkProvider.put("config", null);
world.put("chunk-provider",chunkProvider);
}
{
world.put("limits", (new GenerationLimits()).getConfig());
}
root.put(worldName, world);
}
save();
}
}
| public void loadWorlds() {
load();
Object co = null;
if(root!=null && root.containsKey("worlds")) {
co = root.get("worlds");
if(co instanceof Map<?,?>) {
Map<String,Object> worldMap = (Map<String, Object>) root.get("worlds");
worlds = worldMap.keySet();
for (String worldName : this.worlds) {
Map<String,Object> currWorld = (Map<String, Object>) worldMap.get(worldName);
Map<String,Object> limits = (Map<String, Object>) currWorld.get("limits");
Long seed = (Long) ((currWorld.get("seed")==null)?((new Random()).nextLong()):currWorld.get("seed"));
spade.genLimits.put(worldName.toLowerCase(), new GenerationLimits(limits));
Map<String,Object> chunkManager = (Map<String, Object>) currWorld.get("chunk-manager");
if(chunkManager == null) {
chunkManager = new HashMap<String,Object>();
chunkManager.put("name", "stock");
}
Map<String,Object> chunkProvider = (Map<String, Object>) currWorld.get("chunk-provider");
if(chunkProvider == null) {
chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
}
spade.loadWorld(worldName, seed, (String)chunkManager.get("name"), (String)chunkProvider.get("name"), (Map<String,Object>)chunkProvider.get("config"));
}
}
} else {
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
chunkProvider.put("config", null);
world.put("chunk-provider",chunkProvider);
}
{
world.put("limits", (new GenerationLimits()).getConfig());
}
root.put(worldName, world);
}
save();
}
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
index 1f73b3698..716d40511 100755
--- a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
@@ -1,279 +1,279 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.misc;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import javax.tools.JavaFileObject;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager;
import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl;
import com.redhat.ceylon.compiler.java.tools.CeyloncTool;
public class MiscTest extends CompilerTest {
@Test
public void testDefaultedModel() throws Exception{
compile("defaultedmodel/DefineDefaulted.ceylon");
compile("defaultedmodel/UseDefaulted.ceylon");
}
@Test
public void testHelloWorld(){
compareWithJavaSource("helloworld/helloworld");
}
@Test
public void runHelloWorld() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.helloworld.helloworld", "helloworld/helloworld.ceylon");
}
@Test
public void testCompileTwoDepdendantClasses() throws Exception{
compile("twoclasses/Two.ceylon");
compile("twoclasses/One.ceylon");
}
@Test
public void testCompileTwoClasses() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.twoclasses.main", "twoclasses/One.ceylon", "twoclasses/Two.ceylon", "twoclasses/main.ceylon");
}
@Test
public void testEqualsHashOverriding(){
compareWithJavaSource("equalshashoverriding/EqualsHashOverriding");
}
@Test
public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.metamodel"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "Boolean", "Callable", "Character", "className",
- "Exception", "flatten", "Float", "identityHash", "Integer", "internalFirst", "internalSort",
- "Keys", "language", "process", "integerRangeByIterable",
+ "Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
+ "language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
// Problem files
"LazySet"
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
private void addJavaSourceFile(String baseName, List<File> sourceFiles, File javaPkgDir) {
if (Character.isLowerCase(baseName.charAt(0))) {
sourceFiles.add(new File(javaPkgDir, baseName + "_.java"));
} else {
sourceFiles.add(new File(javaPkgDir, baseName + ".java"));
File impl = new File(javaPkgDir, baseName + "$impl.java");
if (impl.exists()) {
sourceFiles.add(impl);
}
}
}
@Test
public void compileSDK(){
String[] modules = {
"collection",
"dbc",
"file",
"interop.java",
"io",
"json",
"math",
"util",
"net",
"process",
};
String sourceDir = "../ceylon-sdk/source";
// don't run this if the SDK is not checked out
File sdkFile = new File(sourceDir);
if(!sdkFile.exists())
return;
java.util.List<String> moduleNames = new ArrayList<String>(modules.length);
for(String module : modules){
moduleNames.add("ceylon." + module);
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", sourceDir, "-d", "build/classes-sdk"),
moduleNames, null);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
//
// Java keyword avoidance
// Note class names and generic type arguments are not a problem because
// in Ceylon they must begin with an upper case latter, but the Java
// keywords are all lowercase
@Test
public void testKeywordVariable(){
compareWithJavaSource("keyword/Variable");
}
@Test
public void testKeywordAttribute(){
compareWithJavaSource("keyword/Attribute");
}
@Test
public void testKeywordMethod(){
compareWithJavaSource("keyword/Method");
}
@Test
public void testKeywordParameter(){
compareWithJavaSource("keyword/Parameter");
}
@Test
public void testJDKModules(){
Assert.assertTrue(JDKUtils.isJDKModule("java.base"));
Assert.assertTrue(JDKUtils.isJDKModule("java.desktop"));
Assert.assertTrue(JDKUtils.isJDKModule("java.compiler")); // last one
Assert.assertFalse(JDKUtils.isJDKModule("java.stef"));
}
@Test
public void testJDKPackages(){
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.awt"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.lang"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.util"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("javax.swing"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.w3c.dom"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.xml.sax.helpers"));// last one
Assert.assertFalse(JDKUtils.isJDKAnyPackage("fr.epardaud"));
}
@Test
public void testOracleJDKModules(){
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.base"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.desktop"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.httpserver"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.tools.base")); // last one
Assert.assertFalse(JDKUtils.isOracleJDKModule("oracle.jdk.stef"));
Assert.assertFalse(JDKUtils.isOracleJDKModule("jdk.base"));
}
@Test
public void testOracleJDKPackages(){
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.oracle.net"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.awt"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.imageio.plugins.bmp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.java.swing.plaf.gtk"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.nio.sctp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sun.nio"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sunw.util"));// last one
Assert.assertFalse(JDKUtils.isOracleJDKAnyPackage("fr.epardaud"));
}
}
| true | true | public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.metamodel"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalFirst", "internalSort",
"Keys", "language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
// Problem files
"LazySet"
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
| public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.metamodel"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
// Problem files
"LazySet"
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
|
diff --git a/src/test/java/org/nohope/akka/spring/ReflectActorFactoryTest.java b/src/test/java/org/nohope/akka/spring/ReflectActorFactoryTest.java
index 47886a0..979248c 100644
--- a/src/test/java/org/nohope/akka/spring/ReflectActorFactoryTest.java
+++ b/src/test/java/org/nohope/akka/spring/ReflectActorFactoryTest.java
@@ -1,54 +1,54 @@
package org.nohope.akka.spring;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import org.junit.Test;
import org.springframework.context.support.GenericApplicationContext;
import org.nohope.spring.SpringUtils;
import org.nohope.test.SerializationUtils;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.nohope.akka.Ask.waitReply;
import static org.nohope.akka.spring.Bean.Props.*;
/**
* @author <a href="mailto:[email protected]">ketoth xupack</a>
* @since 9/16/12 11:11 PM
*/
public class ReflectActorFactoryTest {
@Test
public void partialInject() throws Exception {
final GenericApplicationContext ctx = new GenericApplicationContext();
SpringUtils.registerSingleton(ctx, 1);
final ReflectActorFactory<Bean> beanFactory = new ReflectActorFactory<>(ctx, Bean.class);
beanFactory.addBean("param2", "test1");
beanFactory.addBean("param3", "test2");
final ActorSystem system = ActorSystem.create();
final ActorRef ref = system.actorOf(new Props(beanFactory));
- assertEquals(1, waitReply(ref, PARAM1));
- assertEquals("test1", waitReply(ref, PARAM2));
- assertEquals("test2", waitReply(ref, PARAM3));
+ assertEquals(1, (int) waitReply(Integer.class, ref, PARAM1));
+ assertEquals("test1", waitReply(String.class, ref, PARAM2));
+ assertEquals("test2", waitReply(String.class, ref, PARAM3));
assertEquals(ctx, beanFactory.getContext());
final Map<String,Object> namedBeans = beanFactory.getNamedBeans();
assertTrue(namedBeans.containsKey("param2") && namedBeans.containsKey("param3"));
final List<Object> beans = beanFactory.getBeans();
assertEquals(0, beans.size());
assertEquals(Bean.class, beanFactory.getTargetClass());
}
@Test(expected = AssertionError.class)
public void javaSerialization() {
final GenericApplicationContext ctx = new GenericApplicationContext();
final ReflectActorFactory<Bean> beanFactory = new ReflectActorFactory<>(ctx, Bean.class);
SerializationUtils.cloneJava(beanFactory);
}
}
| true | true | public void partialInject() throws Exception {
final GenericApplicationContext ctx = new GenericApplicationContext();
SpringUtils.registerSingleton(ctx, 1);
final ReflectActorFactory<Bean> beanFactory = new ReflectActorFactory<>(ctx, Bean.class);
beanFactory.addBean("param2", "test1");
beanFactory.addBean("param3", "test2");
final ActorSystem system = ActorSystem.create();
final ActorRef ref = system.actorOf(new Props(beanFactory));
assertEquals(1, waitReply(ref, PARAM1));
assertEquals("test1", waitReply(ref, PARAM2));
assertEquals("test2", waitReply(ref, PARAM3));
assertEquals(ctx, beanFactory.getContext());
final Map<String,Object> namedBeans = beanFactory.getNamedBeans();
assertTrue(namedBeans.containsKey("param2") && namedBeans.containsKey("param3"));
final List<Object> beans = beanFactory.getBeans();
assertEquals(0, beans.size());
assertEquals(Bean.class, beanFactory.getTargetClass());
}
| public void partialInject() throws Exception {
final GenericApplicationContext ctx = new GenericApplicationContext();
SpringUtils.registerSingleton(ctx, 1);
final ReflectActorFactory<Bean> beanFactory = new ReflectActorFactory<>(ctx, Bean.class);
beanFactory.addBean("param2", "test1");
beanFactory.addBean("param3", "test2");
final ActorSystem system = ActorSystem.create();
final ActorRef ref = system.actorOf(new Props(beanFactory));
assertEquals(1, (int) waitReply(Integer.class, ref, PARAM1));
assertEquals("test1", waitReply(String.class, ref, PARAM2));
assertEquals("test2", waitReply(String.class, ref, PARAM3));
assertEquals(ctx, beanFactory.getContext());
final Map<String,Object> namedBeans = beanFactory.getNamedBeans();
assertTrue(namedBeans.containsKey("param2") && namedBeans.containsKey("param3"));
final List<Object> beans = beanFactory.getBeans();
assertEquals(0, beans.size());
assertEquals(Bean.class, beanFactory.getTargetClass());
}
|
diff --git a/src/com/github/groupENIGMA/journalEgocentrique/ListActivity.java b/src/com/github/groupENIGMA/journalEgocentrique/ListActivity.java
index bd702a7..ad014ea 100644
--- a/src/com/github/groupENIGMA/journalEgocentrique/ListActivity.java
+++ b/src/com/github/groupENIGMA/journalEgocentrique/ListActivity.java
@@ -1,311 +1,311 @@
package com.github.groupENIGMA.journalEgocentrique;
import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.github.groupENIGMA.journalEgocentrique.model.DB;
import com.github.groupENIGMA.journalEgocentrique.model.Entry;
import com.github.groupENIGMA.journalEgocentrique.model.Note;
public class ListActivity extends Activity {
public final static String EXTRA_WRITENOTE_NoteId = "NoteId";
public final static String EXTRA_WRITENOTE_EntryId = "EntryId";
public final static String EXTRA_MESSAGE = "com.github.groupENIGMA.journalEgocentrique.MESSAGE";
private List<Calendar> daysList;
private DB dataBase;
private Entry selectedEntry = null;
private SharedPreferences sharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setView();
dataBase = new DB(getApplicationContext());
// Open the shared preferences file
sharedPreferences = getSharedPreferences(
AppConstants.SHARED_PREFERENCES_FILENAME,
MODE_PRIVATE
);
}
/**
* Sets dinamically proportioned the size of the Entries, Images and Notes
*/
private void setView(){
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ListView list = (ListView)findViewById(R.id.list);
ImageView photo = (ImageView)findViewById(R.id.dailyPhoto);
ImageView mood = (ImageView)findViewById(R.id.emoticon);
ListView notes = (ListView)findViewById(R.id.notes);
FrameLayout frame = (FrameLayout)findViewById(R.id.frameLayout);
// Set the ListView size
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)list.getLayoutParams();
params.height = height;
params.width = width/4;
list.setLayoutParams(params);
// Set the FrameLayout
params = (RelativeLayout.LayoutParams)frame.getLayoutParams();
params.height = height;
params.width = width*3/4;
frame.setLayoutParams(params);
// Set the photo
FrameLayout.LayoutParams param = (FrameLayout.LayoutParams)photo.getLayoutParams();
param.width = width/2;
param.height = height/2;
photo.setLayoutParams(param);
// Set the mood
param = (FrameLayout.LayoutParams)mood.getLayoutParams();
param.width = width/2;
param.height = height/3;
mood.setLayoutParams(param);
// Set the notes
param = (FrameLayout.LayoutParams)notes.getLayoutParams();
param.width = width/4;
param.height = height;
notes.setLayoutParams(param);
}
@Override
protected void onResume() {
super.onResume();
// Open database connection
dataBase.open();
// Display the list of days with an Entry
daysList = dataBase.getDays();
ListView daysListView = (ListView)findViewById(R.id.list);
displayDaysList(daysListView, daysList);
// Display the last viewed Entry (if any)
SharedPreferences pref = getPreferences(MODE_PRIVATE);
long id = pref.getLong("Id", -1);
if(id != -1) {
selectedEntry = dataBase.getEntry(id);
// Display the Photo and Mood Image
displayImages();
// Display the Notes
ListView notesListView = (ListView)findViewById(R.id.notes);
displayNotes(notesListView);
}
else {
selectedEntry = null;
}
}
/**
* Display the list of all Days having an associated Entry
* It is also created a OnItemClickListener that at the click will display
* the details of the day.
*
* @param list The list to populate.
* @param entry With this List we will populate the ListView
*/
private void displayDaysList(ListView list, List<Calendar> entry){
// Create and set the custom ArrayAdapter DaysArrayAdapter
DaysArrayAdapter arrayAdapter = new DaysArrayAdapter(
this, R.layout.row, entry
);
list.setAdapter(arrayAdapter);
// Set the listener
OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
selectedEntry = dataBase.getEntry(
(Calendar)adapter.getItemAtPosition(position)
);
// Refresh notes and images
displayImages();
// Display the Notes
ListView notesListView = (ListView)findViewById(R.id.notes);
displayNotes(notesListView);
}
};
list.setOnItemClickListener(clickListener);
}
/**
* Displays the Notes of the selectedEntry
*
* @param list The ListView that will be used to display the Entry
*/
private void displayNotes(ListView list) {
// Display the Notes
List<Note> notes = selectedEntry.getNotes();
ArrayAdapter<Note> arrayAdapter = new ArrayAdapter<Note>(
this, R.layout.row, R.id.textViewList, notes
);
list.setAdapter(arrayAdapter);
// Add the onLongClickListener that activates the WriteNote activity
// that can be used to update the Note text
OnItemLongClickListener clickListener = new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapter, View view,
int position, long id) {
// Enable the onLongClickListener only if the Note can be
// updated.
Note selectedNote = (Note) adapter.getItemAtPosition(position);
if (selectedNote.canBeUpdated(sharedPreferences)) {
Intent intent = new Intent(
getApplicationContext(), WriteNote.class
);
intent.putExtra(
EXTRA_WRITENOTE_NoteId, selectedNote.getId()
);
startActivity(intent);
return true;
}
// The Note can't be updated
else {
return false;
}
}
};
list.setOnItemLongClickListener(clickListener);
}
/**
* Sets the correct image for photo and mood selected by the user.
*/
private void displayImages(){
/*
* No selected entry; display the default images
*/
if(selectedEntry == null){
ImageView img = (ImageView) findViewById(R.id.dailyPhoto);
img.setImageResource(R.drawable.ic_launcher);
img = (ImageView)findViewById(R.id.emoticon);
img.setImageResource(R.drawable.ic_launcher);
}
/*
* Entry selected: display its images (if any) or the default ones
* If the Entry is editable also add the listeners that activate
* MoodActivity and PhotoActivity.to change the Mood and Photo
*/
else{
boolean editable = selectedEntry.canBeUpdated();
ImageView img = (ImageView) findViewById(R.id.dailyPhoto);
if(selectedEntry.getPhoto() != null)
img.setImageURI(Uri.parse(selectedEntry.getPhoto().getPath()));
else
img.setImageResource(R.drawable.ic_launcher);
ImageView mood = (ImageView)findViewById(R.id.emoticon);
if(selectedEntry.getMood() == null)
mood.setImageResource(R.drawable.ic_launcher);
else
mood.setImageResource((selectedEntry.getMood().getEmoteId(getApplicationContext())));
if(editable){
img.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// qui carica la vista per la fotoCamera
Intent intent = new Intent(getApplicationContext(), PhotoActivity.class);//ho messo PhotoActivity.class
intent.putExtra(EXTRA_MESSAGE, selectedEntry.getId());
startActivity(intent);
return false;
}
});
mood.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// qui carica la vista per il moood
Intent intent = new Intent(getApplicationContext(), MoodActivity.class);//ho messo MoodActivity.class
- intent.putExtra(EXTRA_MESSAGE, selectedEntry.getId());
+ intent.putExtra("EntryId", selectedEntry.getId());
startActivity(intent);
return false;
}
});
}
}
}
@Override
protected void onPause(){
super.onPause();
// Save selected Entry
SharedPreferences pref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putLong("Id", selectedEntry.getId());
edit.commit();
// Close database connection
dataBase.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.newEntry:
selectedEntry = dataBase.createEntry();
Log.e("New Entry", selectedEntry.getId()+"");//debug
daysList = dataBase.getDays();
ListView list = (ListView)findViewById(R.id.list);
displayDaysList(list, daysList);
return true;
case R.id.newNote:
Intent intent = new Intent(
getApplicationContext(), WriteNote.class
);
intent.putExtra(EXTRA_WRITENOTE_NoteId, -1L);
intent.putExtra(EXTRA_WRITENOTE_EntryId, selectedEntry.getId());
startActivity(intent);
return true;
case R.id.settings:
Intent settings = new Intent(getApplicationContext(), Settings.class);
startActivity(settings);
return true;
case R.id.deleteEntry:
if(selectedEntry != null){
//dataBase.deleteEntry(selectedEntry);
return true;
}
case R.id.gallery:
Intent gallery = new Intent(getApplicationContext(), GalleryActivity.class);
startActivity(gallery);
}
return false;
}
}
| true | true | private void displayImages(){
/*
* No selected entry; display the default images
*/
if(selectedEntry == null){
ImageView img = (ImageView) findViewById(R.id.dailyPhoto);
img.setImageResource(R.drawable.ic_launcher);
img = (ImageView)findViewById(R.id.emoticon);
img.setImageResource(R.drawable.ic_launcher);
}
/*
* Entry selected: display its images (if any) or the default ones
* If the Entry is editable also add the listeners that activate
* MoodActivity and PhotoActivity.to change the Mood and Photo
*/
else{
boolean editable = selectedEntry.canBeUpdated();
ImageView img = (ImageView) findViewById(R.id.dailyPhoto);
if(selectedEntry.getPhoto() != null)
img.setImageURI(Uri.parse(selectedEntry.getPhoto().getPath()));
else
img.setImageResource(R.drawable.ic_launcher);
ImageView mood = (ImageView)findViewById(R.id.emoticon);
if(selectedEntry.getMood() == null)
mood.setImageResource(R.drawable.ic_launcher);
else
mood.setImageResource((selectedEntry.getMood().getEmoteId(getApplicationContext())));
if(editable){
img.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// qui carica la vista per la fotoCamera
Intent intent = new Intent(getApplicationContext(), PhotoActivity.class);//ho messo PhotoActivity.class
intent.putExtra(EXTRA_MESSAGE, selectedEntry.getId());
startActivity(intent);
return false;
}
});
mood.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// qui carica la vista per il moood
Intent intent = new Intent(getApplicationContext(), MoodActivity.class);//ho messo MoodActivity.class
intent.putExtra(EXTRA_MESSAGE, selectedEntry.getId());
startActivity(intent);
return false;
}
});
}
}
}
| private void displayImages(){
/*
* No selected entry; display the default images
*/
if(selectedEntry == null){
ImageView img = (ImageView) findViewById(R.id.dailyPhoto);
img.setImageResource(R.drawable.ic_launcher);
img = (ImageView)findViewById(R.id.emoticon);
img.setImageResource(R.drawable.ic_launcher);
}
/*
* Entry selected: display its images (if any) or the default ones
* If the Entry is editable also add the listeners that activate
* MoodActivity and PhotoActivity.to change the Mood and Photo
*/
else{
boolean editable = selectedEntry.canBeUpdated();
ImageView img = (ImageView) findViewById(R.id.dailyPhoto);
if(selectedEntry.getPhoto() != null)
img.setImageURI(Uri.parse(selectedEntry.getPhoto().getPath()));
else
img.setImageResource(R.drawable.ic_launcher);
ImageView mood = (ImageView)findViewById(R.id.emoticon);
if(selectedEntry.getMood() == null)
mood.setImageResource(R.drawable.ic_launcher);
else
mood.setImageResource((selectedEntry.getMood().getEmoteId(getApplicationContext())));
if(editable){
img.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// qui carica la vista per la fotoCamera
Intent intent = new Intent(getApplicationContext(), PhotoActivity.class);//ho messo PhotoActivity.class
intent.putExtra(EXTRA_MESSAGE, selectedEntry.getId());
startActivity(intent);
return false;
}
});
mood.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// qui carica la vista per il moood
Intent intent = new Intent(getApplicationContext(), MoodActivity.class);//ho messo MoodActivity.class
intent.putExtra("EntryId", selectedEntry.getId());
startActivity(intent);
return false;
}
});
}
}
}
|
diff --git a/solr/src/java/org/apache/solr/core/SolrConfig.java b/solr/src/java/org/apache/solr/core/SolrConfig.java
index dcb42489..d5f6ffe7 100644
--- a/solr/src/java/org/apache/solr/core/SolrConfig.java
+++ b/solr/src/java/org/apache/solr/core/SolrConfig.java
@@ -1,476 +1,476 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.core;
import org.apache.solr.common.util.DOMUtil;
import org.apache.solr.common.util.RegexFileFilter;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.handler.PingRequestHandler;
import org.apache.solr.handler.component.SearchComponent;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.QueryResponseWriter;
import org.apache.solr.search.CacheConfig;
import org.apache.solr.search.FastLRUCache;
import org.apache.solr.search.QParserPlugin;
import org.apache.solr.search.ValueSourceParser;
import org.apache.solr.update.SolrIndexConfig;
import org.apache.solr.update.processor.UpdateRequestProcessorChain;
import org.apache.solr.spelling.QueryConverter;
import org.apache.solr.highlight.SolrHighlighter;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
/**
* Provides a static reference to a Config object modeling the main
* configuration data for a a Solr instance -- typically found in
* "solrconfig.xml".
*
* @version $Id$
*/
public class SolrConfig extends Config {
public static final Logger log = LoggerFactory.getLogger(SolrConfig.class);
public static final String DEFAULT_CONF_FILE = "solrconfig.xml";
/**
* Compatibility feature for single-core (pre-solr{215,350} patch); should go away at solr-2.0
* @deprecated Use {@link SolrCore#getSolrConfig()} instead.
*/
@Deprecated
public static SolrConfig config = null;
/**
* Singleton keeping track of configuration errors
*/
public static final Collection<Throwable> severeErrors = new HashSet<Throwable>();
/** Creates a default instance from the solrconfig.xml. */
public SolrConfig()
throws ParserConfigurationException, IOException, SAXException {
this( (SolrResourceLoader) null, DEFAULT_CONF_FILE, null );
}
/** Creates a configuration instance from a configuration name.
* A default resource loader will be created (@see SolrResourceLoader)
*@param name the configuration name used by the loader
*/
public SolrConfig(String name)
throws ParserConfigurationException, IOException, SAXException {
this( (SolrResourceLoader) null, name, null);
}
/** Creates a configuration instance from a configuration name and stream.
* A default resource loader will be created (@see SolrResourceLoader).
* If the stream is null, the resource loader will open the configuration stream.
* If the stream is not null, no attempt to load the resource will occur (the name is not used).
*@param name the configuration name
*@param is the configuration stream
*/
public SolrConfig(String name, InputStream is)
throws ParserConfigurationException, IOException, SAXException {
this( (SolrResourceLoader) null, name, is );
}
/** Creates a configuration instance from an instance directory, configuration name and stream.
*@param instanceDir the directory used to create the resource loader
*@param name the configuration name used by the loader if the stream is null
*@param is the configuration stream
*/
public SolrConfig(String instanceDir, String name, InputStream is)
throws ParserConfigurationException, IOException, SAXException {
this(new SolrResourceLoader(instanceDir), name, is);
}
/** Creates a configuration instance from a resource loader, a configuration name and a stream.
* If the stream is null, the resource loader will open the configuration stream.
* If the stream is not null, no attempt to load the resource will occur (the name is not used).
*@param loader the resource loader
*@param name the configuration name
*@param is the configuration stream
*/
SolrConfig(SolrResourceLoader loader, String name, InputStream is)
throws ParserConfigurationException, IOException, SAXException {
super(loader, name, is, "/config/");
initLibs();
defaultIndexConfig = new SolrIndexConfig(this, null, null);
mainIndexConfig = new SolrIndexConfig(this, "mainIndex", defaultIndexConfig);
reopenReaders = getBool("mainIndex/reopenReaders", true);
booleanQueryMaxClauseCount = getInt("query/maxBooleanClauses", BooleanQuery.getMaxClauseCount());
luceneMatchVersion = getLuceneVersion("luceneMatchVersion", Version.LUCENE_24);
log.info("Using Lucene MatchVersion: " + luceneMatchVersion);
filtOptEnabled = getBool("query/boolTofilterOptimizer/@enabled", false);
filtOptCacheSize = getInt("query/boolTofilterOptimizer/@cacheSize",32);
filtOptThreshold = getFloat("query/boolTofilterOptimizer/@threshold",.05f);
useFilterForSortedQuery = getBool("query/useFilterForSortedQuery", false);
- queryResultWindowSize = getInt("query/queryResultWindowSize", 1);
+ queryResultWindowSize = Math.max(1, getInt("query/queryResultWindowSize", 1));
queryResultMaxDocsCached = getInt("query/queryResultMaxDocsCached", Integer.MAX_VALUE);
enableLazyFieldLoading = getBool("query/enableLazyFieldLoading", false);
filterCacheConfig = CacheConfig.getConfig(this, "query/filterCache");
queryResultCacheConfig = CacheConfig.getConfig(this, "query/queryResultCache");
documentCacheConfig = CacheConfig.getConfig(this, "query/documentCache");
CacheConfig conf = CacheConfig.getConfig(this, "query/fieldValueCache");
if (conf == null) {
Map<String,String> args = new HashMap<String,String>();
args.put("name","fieldValueCache");
args.put("size","10000");
args.put("initialSize","10");
args.put("showItems","-1");
conf = new CacheConfig(FastLRUCache.class, args, null);
}
fieldValueCacheConfig = conf;
unlockOnStartup = getBool("mainIndex/unlockOnStartup", false);
useColdSearcher = getBool("query/useColdSearcher",false);
dataDir = get("dataDir", null);
if (dataDir != null && dataDir.length()==0) dataDir=null;
userCacheConfigs = CacheConfig.getMultipleConfigs(this, "query/cache");
org.apache.solr.search.SolrIndexSearcher.initRegenerators(this);
hashSetInverseLoadFactor = 1.0f / getFloat("//HashDocSet/@loadFactor",0.75f);
hashDocSetMaxSize= getInt("//HashDocSet/@maxSize",3000);
pingQueryParams = readPingQueryParams(this);
httpCachingConfig = new HttpCachingConfig(this);
Node jmx = getNode("jmx", false);
if (jmx != null) {
jmxConfig = new JmxConfiguration(true, get("jmx/@agentId", null), get(
"jmx/@serviceUrl", null));
} else {
jmxConfig = new JmxConfiguration(false, null, null);
}
maxWarmingSearchers = getInt("query/maxWarmingSearchers",Integer.MAX_VALUE);
loadPluginInfo(SolrRequestHandler.class,"requestHandler",true, true);
loadPluginInfo(QParserPlugin.class,"queryParser",true, true);
loadPluginInfo(QueryResponseWriter.class,"queryResponseWriter",true, true);
loadPluginInfo(ValueSourceParser.class,"valueSourceParser",true, true);
loadPluginInfo(SearchComponent.class,"searchComponent",true, true);
loadPluginInfo(QueryConverter.class,"queryConverter",true, true);
// this is hackish, since it picks up all SolrEventListeners,
// regardless of when/how/why thye are used (or even if they are
// declared outside of the appropriate context) but there's no nice
// way arround that in the PluginInfo framework
loadPluginInfo(SolrEventListener.class, "//listener",false, true);
loadPluginInfo(DirectoryFactory.class,"directoryFactory",false, true);
loadPluginInfo(IndexDeletionPolicy.class,"mainIndex/deletionPolicy",false, true);
loadPluginInfo(IndexReaderFactory.class,"indexReaderFactory",false, true);
loadPluginInfo(UpdateRequestProcessorChain.class,"updateRequestProcessorChain",false, false);
//TODO deprecated remove it later
loadPluginInfo(SolrHighlighter.class,"highlighting",false, false);
if( pluginStore.containsKey( SolrHighlighter.class.getName() ) )
log.warn( "Deprecated syntax found. <highlighting/> should move to <searchComponent/>" );
updateHandlerInfo = loadUpdatehandlerInfo();
Config.log.info("Loaded SolrConfig: " + name);
// TODO -- at solr 2.0. this should go away
config = this;
}
protected UpdateHandlerInfo loadUpdatehandlerInfo() {
return new UpdateHandlerInfo(get("updateHandler/@class",null),
getInt("updateHandler/autoCommit/maxDocs",-1),
getInt("updateHandler/autoCommit/maxTime",-1),
getInt("updateHandler/commitIntervalLowerBound",-1));
}
private void loadPluginInfo(Class clazz, String tag, boolean requireName, boolean requireClass) {
List<PluginInfo> result = readPluginInfos(tag, requireName, requireClass);
if(!result.isEmpty()) pluginStore.put(clazz.getName(),result);
}
public List<PluginInfo> readPluginInfos(String tag, boolean requireName, boolean requireClass) {
ArrayList<PluginInfo> result = new ArrayList<PluginInfo>();
NodeList nodes = (NodeList) evaluate(tag, XPathConstants.NODESET);
for (int i=0; i<nodes.getLength(); i++) {
PluginInfo pluginInfo = new PluginInfo(nodes.item(i), "[solrconfig.xml] " + tag, requireName, requireClass);
if(pluginInfo.isEnabled()) result.add(pluginInfo);
}
return result;
}
/* The set of materialized parameters: */
public final int booleanQueryMaxClauseCount;
// SolrIndexSearcher - nutch optimizer
public final boolean filtOptEnabled;
public final int filtOptCacheSize;
public final float filtOptThreshold;
// SolrIndexSearcher - caches configurations
public final CacheConfig filterCacheConfig ;
public final CacheConfig queryResultCacheConfig;
public final CacheConfig documentCacheConfig;
public final CacheConfig fieldValueCacheConfig;
public final CacheConfig[] userCacheConfigs;
// SolrIndexSearcher - more...
public final boolean useFilterForSortedQuery;
public final int queryResultWindowSize;
public final int queryResultMaxDocsCached;
public final boolean enableLazyFieldLoading;
public final boolean reopenReaders;
// DocSet
public final float hashSetInverseLoadFactor;
public final int hashDocSetMaxSize;
// default & main index configurations
public final SolrIndexConfig defaultIndexConfig;
public final SolrIndexConfig mainIndexConfig;
protected UpdateHandlerInfo updateHandlerInfo ;
private Map<String, List<PluginInfo>> pluginStore = new LinkedHashMap<String, List<PluginInfo>>();
public final int maxWarmingSearchers;
public final boolean unlockOnStartup;
public final boolean useColdSearcher;
public final Version luceneMatchVersion;
protected String dataDir;
//JMX configuration
public final JmxConfiguration jmxConfig;
private final HttpCachingConfig httpCachingConfig;
public HttpCachingConfig getHttpCachingConfig() {
return httpCachingConfig;
}
/**
* ping query request parameters
* @deprecated Use {@link PingRequestHandler} instead.
*/
@Deprecated
private final NamedList pingQueryParams;
static private NamedList readPingQueryParams(SolrConfig config) {
String urlSnippet = config.get("admin/pingQuery", "").trim();
StringTokenizer qtokens = new StringTokenizer(urlSnippet,"&");
String tok;
NamedList params = new NamedList();
while (qtokens.hasMoreTokens()) {
tok = qtokens.nextToken();
String[] split = tok.split("=", 2);
params.add(split[0], split[1]);
}
if (0 < params.size()) {
log.warn("The <pingQuery> syntax is deprecated, " +
"please use PingRequestHandler instead");
}
return params;
}
/**
* Returns a Request object based on the admin/pingQuery section
* of the Solr config file.
*
* @deprecated use {@link PingRequestHandler} instead
*/
@Deprecated
public SolrQueryRequest getPingQueryRequest(SolrCore core) {
if(pingQueryParams.size() == 0) {
throw new IllegalStateException
("<pingQuery> not configured (consider registering " +
"PingRequestHandler with the name '/admin/ping' instead)");
}
return new LocalSolrQueryRequest(core, pingQueryParams);
}
public static class JmxConfiguration {
public boolean enabled = false;
public String agentId;
public String serviceUrl;
public JmxConfiguration(boolean enabled, String agentId, String serviceUrl) {
this.enabled = enabled;
this.agentId = agentId;
this.serviceUrl = serviceUrl;
}
}
public static class HttpCachingConfig {
/** config xpath prefix for getting HTTP Caching options */
private final static String CACHE_PRE
= "requestDispatcher/httpCaching/";
/** For extracting Expires "ttl" from <cacheControl> config */
private final static Pattern MAX_AGE
= Pattern.compile("\\bmax-age=(\\d+)");
public static enum LastModFrom {
OPENTIME, DIRLASTMOD, BOGUS;
/** Input must not be null */
public static LastModFrom parse(final String s) {
try {
return valueOf(s.toUpperCase(Locale.ENGLISH));
} catch (Exception e) {
log.warn( "Unrecognized value for lastModFrom: " + s, e);
return BOGUS;
}
}
}
private final boolean never304;
private final String etagSeed;
private final String cacheControlHeader;
private final Long maxAge;
private final LastModFrom lastModFrom;
private HttpCachingConfig(SolrConfig conf) {
never304 = conf.getBool(CACHE_PRE+"@never304", false);
etagSeed = conf.get(CACHE_PRE+"@etagSeed", "Solr");
lastModFrom = LastModFrom.parse(conf.get(CACHE_PRE+"@lastModFrom",
"openTime"));
cacheControlHeader = conf.get(CACHE_PRE+"cacheControl",null);
Long tmp = null; // maxAge
if (null != cacheControlHeader) {
try {
final Matcher ttlMatcher = MAX_AGE.matcher(cacheControlHeader);
final String ttlStr = ttlMatcher.find() ? ttlMatcher.group(1) : null;
tmp = (null != ttlStr && !"".equals(ttlStr))
? Long.valueOf(ttlStr)
: null;
} catch (Exception e) {
log.warn( "Ignoring exception while attempting to " +
"extract max-age from cacheControl config: " +
cacheControlHeader, e);
}
}
maxAge = tmp;
}
public boolean isNever304() { return never304; }
public String getEtagSeed() { return etagSeed; }
/** null if no Cache-Control header */
public String getCacheControlHeader() { return cacheControlHeader; }
/** null if no max age limitation */
public Long getMaxAge() { return maxAge; }
public LastModFrom getLastModFrom() { return lastModFrom; }
}
public static class UpdateHandlerInfo{
public final String className;
public final int autoCommmitMaxDocs,autoCommmitMaxTime,commitIntervalLowerBound;
/**
* @param className
* @param autoCommmitMaxDocs set -1 as default
* @param autoCommmitMaxTime set -1 as default
* @param commitIntervalLowerBound set -1 as default
*/
public UpdateHandlerInfo(String className, int autoCommmitMaxDocs, int autoCommmitMaxTime, int commitIntervalLowerBound) {
this.className = className;
this.autoCommmitMaxDocs = autoCommmitMaxDocs;
this.autoCommmitMaxTime = autoCommmitMaxTime;
this.commitIntervalLowerBound = commitIntervalLowerBound;
}
}
// public Map<String, List<PluginInfo>> getUpdateProcessorChainInfo() { return updateProcessorChainInfo; }
public UpdateHandlerInfo getUpdateHandlerInfo() { return updateHandlerInfo; }
public String getDataDir() { return dataDir; }
/**SolrConfig keeps a repository of plugins by the type. The known interfaces are the types.
* @param type The key is FQN of the plugin class there are a few known types : SolrFormatter, SolrFragmenter
* SolrRequestHandler,QParserPlugin, QueryResponseWriter,ValueSourceParser,
* SearchComponent, QueryConverter, SolrEventListener, DirectoryFactory,
* IndexDeletionPolicy, IndexReaderFactory
*/
public List<PluginInfo> getPluginInfos(String type){
List<PluginInfo> result = pluginStore.get(type);
return result == null ?
(List<PluginInfo>) Collections.EMPTY_LIST:
result;
}
public PluginInfo getPluginInfo(String type){
List<PluginInfo> result = pluginStore.get(type);
return result == null || result.isEmpty() ? null: result.get(0);
}
private void initLibs() {
NodeList nodes = (NodeList) evaluate("lib", XPathConstants.NODESET);
if (nodes==null || nodes.getLength()==0)
return;
log.info("Adding specified lib dirs to ClassLoader");
for (int i=0; i<nodes.getLength(); i++) {
Node node = nodes.item(i);
String baseDir = DOMUtil.getAttr(node, "dir");
String path = DOMUtil.getAttr(node, "path");
if (null != baseDir) {
// :TODO: add support for a simpler 'glob' mutually eclusive of regex
String regex = DOMUtil.getAttr(node, "regex");
FileFilter filter = (null == regex) ? null : new RegexFileFilter(regex);
getResourceLoader().addToClassLoader(baseDir, filter);
} else if (null != path) {
getResourceLoader().addToClassLoader(path);
} else {
throw new RuntimeException
("lib: missing mandatory attributes: 'dir' or 'path'");
}
}
}
}
| true | true | SolrConfig(SolrResourceLoader loader, String name, InputStream is)
throws ParserConfigurationException, IOException, SAXException {
super(loader, name, is, "/config/");
initLibs();
defaultIndexConfig = new SolrIndexConfig(this, null, null);
mainIndexConfig = new SolrIndexConfig(this, "mainIndex", defaultIndexConfig);
reopenReaders = getBool("mainIndex/reopenReaders", true);
booleanQueryMaxClauseCount = getInt("query/maxBooleanClauses", BooleanQuery.getMaxClauseCount());
luceneMatchVersion = getLuceneVersion("luceneMatchVersion", Version.LUCENE_24);
log.info("Using Lucene MatchVersion: " + luceneMatchVersion);
filtOptEnabled = getBool("query/boolTofilterOptimizer/@enabled", false);
filtOptCacheSize = getInt("query/boolTofilterOptimizer/@cacheSize",32);
filtOptThreshold = getFloat("query/boolTofilterOptimizer/@threshold",.05f);
useFilterForSortedQuery = getBool("query/useFilterForSortedQuery", false);
queryResultWindowSize = getInt("query/queryResultWindowSize", 1);
queryResultMaxDocsCached = getInt("query/queryResultMaxDocsCached", Integer.MAX_VALUE);
enableLazyFieldLoading = getBool("query/enableLazyFieldLoading", false);
filterCacheConfig = CacheConfig.getConfig(this, "query/filterCache");
queryResultCacheConfig = CacheConfig.getConfig(this, "query/queryResultCache");
documentCacheConfig = CacheConfig.getConfig(this, "query/documentCache");
CacheConfig conf = CacheConfig.getConfig(this, "query/fieldValueCache");
if (conf == null) {
Map<String,String> args = new HashMap<String,String>();
args.put("name","fieldValueCache");
args.put("size","10000");
args.put("initialSize","10");
args.put("showItems","-1");
conf = new CacheConfig(FastLRUCache.class, args, null);
}
fieldValueCacheConfig = conf;
unlockOnStartup = getBool("mainIndex/unlockOnStartup", false);
useColdSearcher = getBool("query/useColdSearcher",false);
dataDir = get("dataDir", null);
if (dataDir != null && dataDir.length()==0) dataDir=null;
userCacheConfigs = CacheConfig.getMultipleConfigs(this, "query/cache");
org.apache.solr.search.SolrIndexSearcher.initRegenerators(this);
hashSetInverseLoadFactor = 1.0f / getFloat("//HashDocSet/@loadFactor",0.75f);
hashDocSetMaxSize= getInt("//HashDocSet/@maxSize",3000);
pingQueryParams = readPingQueryParams(this);
httpCachingConfig = new HttpCachingConfig(this);
Node jmx = getNode("jmx", false);
if (jmx != null) {
jmxConfig = new JmxConfiguration(true, get("jmx/@agentId", null), get(
"jmx/@serviceUrl", null));
} else {
jmxConfig = new JmxConfiguration(false, null, null);
}
maxWarmingSearchers = getInt("query/maxWarmingSearchers",Integer.MAX_VALUE);
loadPluginInfo(SolrRequestHandler.class,"requestHandler",true, true);
loadPluginInfo(QParserPlugin.class,"queryParser",true, true);
loadPluginInfo(QueryResponseWriter.class,"queryResponseWriter",true, true);
loadPluginInfo(ValueSourceParser.class,"valueSourceParser",true, true);
loadPluginInfo(SearchComponent.class,"searchComponent",true, true);
loadPluginInfo(QueryConverter.class,"queryConverter",true, true);
// this is hackish, since it picks up all SolrEventListeners,
// regardless of when/how/why thye are used (or even if they are
// declared outside of the appropriate context) but there's no nice
// way arround that in the PluginInfo framework
loadPluginInfo(SolrEventListener.class, "//listener",false, true);
loadPluginInfo(DirectoryFactory.class,"directoryFactory",false, true);
loadPluginInfo(IndexDeletionPolicy.class,"mainIndex/deletionPolicy",false, true);
loadPluginInfo(IndexReaderFactory.class,"indexReaderFactory",false, true);
loadPluginInfo(UpdateRequestProcessorChain.class,"updateRequestProcessorChain",false, false);
//TODO deprecated remove it later
loadPluginInfo(SolrHighlighter.class,"highlighting",false, false);
if( pluginStore.containsKey( SolrHighlighter.class.getName() ) )
log.warn( "Deprecated syntax found. <highlighting/> should move to <searchComponent/>" );
updateHandlerInfo = loadUpdatehandlerInfo();
Config.log.info("Loaded SolrConfig: " + name);
// TODO -- at solr 2.0. this should go away
config = this;
}
| SolrConfig(SolrResourceLoader loader, String name, InputStream is)
throws ParserConfigurationException, IOException, SAXException {
super(loader, name, is, "/config/");
initLibs();
defaultIndexConfig = new SolrIndexConfig(this, null, null);
mainIndexConfig = new SolrIndexConfig(this, "mainIndex", defaultIndexConfig);
reopenReaders = getBool("mainIndex/reopenReaders", true);
booleanQueryMaxClauseCount = getInt("query/maxBooleanClauses", BooleanQuery.getMaxClauseCount());
luceneMatchVersion = getLuceneVersion("luceneMatchVersion", Version.LUCENE_24);
log.info("Using Lucene MatchVersion: " + luceneMatchVersion);
filtOptEnabled = getBool("query/boolTofilterOptimizer/@enabled", false);
filtOptCacheSize = getInt("query/boolTofilterOptimizer/@cacheSize",32);
filtOptThreshold = getFloat("query/boolTofilterOptimizer/@threshold",.05f);
useFilterForSortedQuery = getBool("query/useFilterForSortedQuery", false);
queryResultWindowSize = Math.max(1, getInt("query/queryResultWindowSize", 1));
queryResultMaxDocsCached = getInt("query/queryResultMaxDocsCached", Integer.MAX_VALUE);
enableLazyFieldLoading = getBool("query/enableLazyFieldLoading", false);
filterCacheConfig = CacheConfig.getConfig(this, "query/filterCache");
queryResultCacheConfig = CacheConfig.getConfig(this, "query/queryResultCache");
documentCacheConfig = CacheConfig.getConfig(this, "query/documentCache");
CacheConfig conf = CacheConfig.getConfig(this, "query/fieldValueCache");
if (conf == null) {
Map<String,String> args = new HashMap<String,String>();
args.put("name","fieldValueCache");
args.put("size","10000");
args.put("initialSize","10");
args.put("showItems","-1");
conf = new CacheConfig(FastLRUCache.class, args, null);
}
fieldValueCacheConfig = conf;
unlockOnStartup = getBool("mainIndex/unlockOnStartup", false);
useColdSearcher = getBool("query/useColdSearcher",false);
dataDir = get("dataDir", null);
if (dataDir != null && dataDir.length()==0) dataDir=null;
userCacheConfigs = CacheConfig.getMultipleConfigs(this, "query/cache");
org.apache.solr.search.SolrIndexSearcher.initRegenerators(this);
hashSetInverseLoadFactor = 1.0f / getFloat("//HashDocSet/@loadFactor",0.75f);
hashDocSetMaxSize= getInt("//HashDocSet/@maxSize",3000);
pingQueryParams = readPingQueryParams(this);
httpCachingConfig = new HttpCachingConfig(this);
Node jmx = getNode("jmx", false);
if (jmx != null) {
jmxConfig = new JmxConfiguration(true, get("jmx/@agentId", null), get(
"jmx/@serviceUrl", null));
} else {
jmxConfig = new JmxConfiguration(false, null, null);
}
maxWarmingSearchers = getInt("query/maxWarmingSearchers",Integer.MAX_VALUE);
loadPluginInfo(SolrRequestHandler.class,"requestHandler",true, true);
loadPluginInfo(QParserPlugin.class,"queryParser",true, true);
loadPluginInfo(QueryResponseWriter.class,"queryResponseWriter",true, true);
loadPluginInfo(ValueSourceParser.class,"valueSourceParser",true, true);
loadPluginInfo(SearchComponent.class,"searchComponent",true, true);
loadPluginInfo(QueryConverter.class,"queryConverter",true, true);
// this is hackish, since it picks up all SolrEventListeners,
// regardless of when/how/why thye are used (or even if they are
// declared outside of the appropriate context) but there's no nice
// way arround that in the PluginInfo framework
loadPluginInfo(SolrEventListener.class, "//listener",false, true);
loadPluginInfo(DirectoryFactory.class,"directoryFactory",false, true);
loadPluginInfo(IndexDeletionPolicy.class,"mainIndex/deletionPolicy",false, true);
loadPluginInfo(IndexReaderFactory.class,"indexReaderFactory",false, true);
loadPluginInfo(UpdateRequestProcessorChain.class,"updateRequestProcessorChain",false, false);
//TODO deprecated remove it later
loadPluginInfo(SolrHighlighter.class,"highlighting",false, false);
if( pluginStore.containsKey( SolrHighlighter.class.getName() ) )
log.warn( "Deprecated syntax found. <highlighting/> should move to <searchComponent/>" );
updateHandlerInfo = loadUpdatehandlerInfo();
Config.log.info("Loaded SolrConfig: " + name);
// TODO -- at solr 2.0. this should go away
config = this;
}
|
diff --git a/src/VASSAL/chat/node/NodeClient.java b/src/VASSAL/chat/node/NodeClient.java
index 1be67438..4ba62b56 100644
--- a/src/VASSAL/chat/node/NodeClient.java
+++ b/src/VASSAL/chat/node/NodeClient.java
@@ -1,533 +1,536 @@
/*
*
* Copyright (c) 2000-2006 by Rodney Kinney
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* 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, copies are available
* at http://www.opensource.org.
*/
package VASSAL.chat.node;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.util.Properties;
import VASSAL.Info;
import VASSAL.build.GameModule;
import VASSAL.chat.CgiServerStatus;
import VASSAL.chat.ChatServerConnection;
import VASSAL.chat.Compressor;
import VASSAL.chat.InviteCommand;
import VASSAL.chat.InviteEncoder;
import VASSAL.chat.MainRoomChecker;
import VASSAL.chat.Player;
import VASSAL.chat.PlayerEncoder;
import VASSAL.chat.PrivateChatEncoder;
import VASSAL.chat.PrivateChatManager;
import VASSAL.chat.Room;
import VASSAL.chat.ServerStatus;
import VASSAL.chat.SimplePlayer;
import VASSAL.chat.SimpleRoom;
import VASSAL.chat.SimpleStatus;
import VASSAL.chat.SoundEncoder;
import VASSAL.chat.SynchEncoder;
import VASSAL.chat.WelcomeMessageServer;
import VASSAL.chat.messageboard.Message;
import VASSAL.chat.messageboard.MessageBoard;
import VASSAL.chat.ui.ChatControlsInitializer;
import VASSAL.chat.ui.ChatServerControls;
import VASSAL.chat.ui.InviteAction;
import VASSAL.chat.ui.KickAction;
import VASSAL.chat.ui.LockableRoomControls;
import VASSAL.chat.ui.LockableRoomTreeRenderer;
import VASSAL.chat.ui.MessageBoardControlsInitializer;
import VASSAL.chat.ui.PrivateMessageAction;
import VASSAL.chat.ui.RoomInteractionControlsInitializer;
import VASSAL.chat.ui.SendSoundAction;
import VASSAL.chat.ui.ServerStatusControlsInitializer;
import VASSAL.chat.ui.ShowProfileAction;
import VASSAL.chat.ui.SimpleStatusControlsInitializer;
import VASSAL.chat.ui.SynchAction;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.i18n.Resources;
import VASSAL.tools.ArrayUtils;
import VASSAL.tools.Base64;
import VASSAL.tools.PropertiesEncoder;
import VASSAL.tools.SequenceEncoder;
/**
* @author rkinney
*/
public abstract class NodeClient implements ChatServerConnection, PlayerEncoder, ChatControlsInitializer {
public static final String ZIP_HEADER = "!ZIP!"; //$NON-NLS-1$
protected PropertyChangeSupport propSupport = new PropertyChangeSupport(this);
protected NodePlayer me;
protected SimpleRoom currentRoom;
protected String defaultRoomName = "Main Room"; //$NON-NLS-1$
protected NodeRoom[] allRooms = new NodeRoom[0];
protected MessageBoard msgSvr;
protected WelcomeMessageServer welcomer;
protected ServerStatus serverStatus;
protected String moduleName;
protected String playerId;
protected MainRoomChecker checker = new MainRoomChecker();
protected int compressionLimit = 1000;
protected CommandEncoder encoder;
protected MessageBoardControlsInitializer messageBoardControls;
protected RoomInteractionControlsInitializer roomControls;
protected ServerStatusControlsInitializer serverStatusControls;
protected SimpleStatusControlsInitializer playerStatusControls;
protected SoundEncoder soundEncoder;
protected PrivateChatEncoder privateChatEncoder;
protected SynchEncoder synchEncoder;
protected InviteEncoder inviteEncoder;
protected PropertyChangeListener nameChangeListener;
protected PropertyChangeListener profileChangeListener;
protected NodeRoom pendingSynchToRoom;
public NodeClient(String moduleName, String playerId, CommandEncoder encoder, MessageBoard msgSvr, WelcomeMessageServer welcomer) {
this.encoder = encoder;
this.msgSvr = msgSvr;
this.welcomer = welcomer;
this.playerId = playerId;
this.moduleName = moduleName;
serverStatus = new CgiServerStatus();
me = new NodePlayer(playerId);
messageBoardControls = new MessageBoardControlsInitializer(Resources.getString("Chat.messages"), msgSvr); //$NON-NLS-1$
roomControls = new LockableRoomControls(this);
roomControls.addPlayerActionFactory(ShowProfileAction.factory());
roomControls.addPlayerActionFactory(SynchAction.factory(this));
PrivateChatManager privateChatManager = new PrivateChatManager(this);
roomControls.addPlayerActionFactory(PrivateMessageAction.factory(this, privateChatManager));
roomControls.addPlayerActionFactory(SendSoundAction.factory(this, Resources.getString("Chat.send_wakeup"), "wakeUpSound", "phone1.wav")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
roomControls.addPlayerActionFactory(InviteAction.factory(this));
roomControls.addPlayerActionFactory(KickAction.factory(this));
serverStatusControls = new ServerStatusControlsInitializer(serverStatus);
playerStatusControls = new SimpleStatusControlsInitializer(this);
synchEncoder = new SynchEncoder(this, this);
privateChatEncoder = new PrivateChatEncoder(this, privateChatManager);
soundEncoder = new SoundEncoder();
inviteEncoder = new InviteEncoder(this);
nameChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
SimplePlayer p = (SimplePlayer) getUserInfo();
p.setName((String) evt.getNewValue());
setUserInfo(p);
}
};
profileChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
SimplePlayer p = (SimplePlayer) getUserInfo();
SimpleStatus s = (SimpleStatus) p.getStatus();
s = new SimpleStatus(s.isLooking(), s.isAway(), (String) evt.getNewValue(), s.getClient(), s.getIp(), s.getModuleVersion(), s.getCrc());
p.setStatus(s);
setUserInfo(p);
}
};
}
public void setConnected(boolean connect) {
if (connect) {
if (!isConnected()) {
try {
NodePlayer oldPlayer = me;
me = new NodePlayer(playerId);
setUserInfo(oldPlayer);
initializeConnection();
Command welcomeMessage = welcomer.getWelcomeMessage();
if (welcomeMessage != null) {
welcomeMessage.execute();
}
registerNewConnection();
}
// FIXME: review error message
catch (IOException e) {
propSupport.firePropertyChange(STATUS, null, Resources.getString("Chat.unable_to_establish", e.getMessage())); //$NON-NLS-1$
}
}
}
else {
if (isConnected()) {
closeConnection();
}
currentRoom = null;
allRooms = new NodeRoom[0];
}
propSupport.firePropertyChange(CONNECTED, null, isConnected() ? Boolean.TRUE : Boolean.FALSE);
}
protected void registerNewConnection() {
String path = new SequenceEncoder(moduleName, '/').append(defaultRoomName).getValue();
send(Protocol.encodeRegisterCommand(me.getId(), path, new PropertiesEncoder(me.toProperties()).getStringValue()));
if (GameModule.getGameModule() != null) {
String username = (String) GameModule.getGameModule().getPrefs().getValue("Login"); //$NON-NLS-1$
if (username != null) {
send(Protocol.encodeLoginCommand(username));
}
}
}
protected abstract void closeConnection();
protected abstract void initializeConnection() throws IOException;
public abstract void send(String command);
public void setDefaultRoomName(String defaultRoomName) {
this.defaultRoomName = defaultRoomName;
}
public String getDefaultRoomName() {
return defaultRoomName;
}
protected void sendStats() {
if (isConnected()) {
send(Protocol.encodeStatsCommand(new PropertiesEncoder(me.toProperties()).getStringValue()));
}
}
public void sendToOthers(Command c) {
sendToOthers(encoder.encode(c));
}
public void sendToAll(String msg) {
if (currentRoom != null) {
String path = new SequenceEncoder(moduleName, '/').append(currentRoom.getName()).getValue();
forward(path, msg);
}
}
public void forward(String receipientPath, String msg) {
if (isConnected() && currentRoom != null && msg != null) {
msg = checker.filter(msg, defaultRoomName, currentRoom.getName());
if (msg.length() > compressionLimit) {
try {
msg = ZIP_HEADER + Base64.encodeBytes(Compressor.compress(msg.getBytes("UTF-8")), Base64.DONT_BREAK_LINES); //$NON-NLS-1$
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
}
send(Protocol.encodeForwardCommand(receipientPath, msg));
}
}
public void sendToOthers(String msg) {
if (currentRoom != null) {
String path = new SequenceEncoder(moduleName, '/').append(currentRoom.getName()).append("~" + me.getId()).getValue(); //$NON-NLS-1$
forward(path, msg);
}
}
public void sendTo(Player recipient, Command c) {
String path = new SequenceEncoder(moduleName, '/').append("*").append(((NodePlayer) recipient).getId()).getValue(); //$NON-NLS-1$
forward(path, encoder.encode(c));
}
public void kick(Player kickee) {
send(Protocol.encodeKickCommand(kickee.getId()));
}
/**
* Send Invitation to another player to join the current room
*
* @param invitee Player to invite
*/
public void sendInvite(Player invitee) {
sendTo(invitee, new InviteCommand(me.getName(), me.getId(), getRoom().getName()));
}
/**
* Process an invitation request from a player to join a room
*
* @param player Inviting player name
* @param room Inviting room
*/
public void doInvite(String playerId, String roomName) {
for (Room room : getAvailableRooms()) {
if (room.getName().equals(roomName)) {
if (room instanceof NodeRoom) {
final String owner = ((NodeRoom) room).getOwner();
if (owner != null && owner.equals(playerId)) {
setRoom(room, playerId);
return;
}
}
}
}
}
public Room getRoom() {
return currentRoom;
}
public Room[] getAvailableRooms() {
return allRooms;
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) {
propSupport.addPropertyChangeListener(propertyName, l);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propSupport.addPropertyChangeListener(l);
}
public Player getUserInfo() {
return me;
}
public NodePlayer getMyInfo() {
return me;
}
public void setUserInfo(Player p) {
me.setName(p.getName());
me.setStatus(p.getStatus());
sendStats();
propSupport.firePropertyChange(PLAYER_INFO, null, me);
}
public void lockRoom(NodeRoom r) {
if (r.getOwner().equals(me.getId())) {
r.toggleLock();
sendRoomInfo(r);
propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
}
public void sendRoomInfo(NodeRoom r) {
Node dummy = new Node(null, r.getName(), new PropertiesEncoder(r.getInfo()).getStringValue());
if (isConnected()) {
String msg = Protocol.encodeRoomsInfo(new Node[]{dummy});
send(msg);
}
}
public void setRoom(Room r) {
setRoom(r, null);
}
public void setRoom(Room r, String password) {
if (isConnected()) {
final String newRoom = r.getName();
final String newPath = new SequenceEncoder(moduleName, '/').append(newRoom).getValue();
String msg = Protocol.encodeJoinCommand(newPath, password);
send(msg);
// Request a synch if we are not the owner
if (r instanceof NodeRoom) {
final NodeRoom room = (NodeRoom) r;
if (newRoom.equals(defaultRoomName)) {
GameModule.getGameModule().getGameState().setup(false);
}
else if (! room.isOwner(me)) {
// We are not actually recorded as being in the new room until we get an update back from
// the server. Record a Synch required to the new room.
pendingSynchToRoom = room;
GameModule.getGameModule().warn(Resources.getString("Chat.synchronize_pending"));
}
}
}
}
/**
* Process a message received from the server
* @param msg Encoded message
*/
public void handleMessageFromServer(String msg) {
Node n;
Properties p;
if ((n = Protocol.decodeListCommand(msg)) != null) {
Node mod = n.getChild(moduleName);
if (mod != null) {
updateRooms(mod);
}
// Rooms have been updated with any new players (including us), so perform a Synchronize
// for a move to a new room if needed.
if (pendingSynchToRoom != null) {
new SynchAction(((NodeRoom) pendingSynchToRoom).getOwningPlayer(), this).actionPerformed(null);
pendingSynchToRoom = null;
GameModule.getGameModule().warn(Resources.getString("Chat.synchronize_complete"));
}
}
else if ((p = Protocol.decodeRoomsInfo(msg)) != null) {
for (int i = 0; i < allRooms.length; ++i) {
String infoString = p.getProperty(allRooms[i].getName());
if (infoString != null && infoString.length() > 0) {
try {
Properties info = new PropertiesEncoder(infoString).getProperties();
allRooms[i].setInfo(info);
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
}
}
propSupport.firePropertyChange(ROOM, null, currentRoom);
propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
else if (Protocol.decodeRegisterRequest(msg)) {
registerNewConnection();
}
else {
if (msg.startsWith(ZIP_HEADER)) {
try {
msg = new String(Compressor.decompress(Base64.decode(msg.substring(ZIP_HEADER.length()))), "UTF-8"); //$NON-NLS-1$
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
}
propSupport.firePropertyChange(INCOMING_MSG, null, msg);
}
}
protected void updateRooms(Node module) {
Node[] roomNodes = module.getChildren();
NodeRoom[] rooms = new NodeRoom[roomNodes.length];
int defaultRoomIndex = -1;
for (int i = 0; i < roomNodes.length; ++i) {
Node[] playerNodes = roomNodes[i].getChildren();
NodePlayer[] players = new NodePlayer[playerNodes.length];
boolean containsMe = false;
for (int j = 0; j < playerNodes.length; ++j) {
players[j] = new NodePlayer(playerNodes[j].getId());
if (players[j].equals(me)) {
containsMe = true;
}
try {
Properties p = new PropertiesEncoder(playerNodes[j].getInfo()).getProperties();
players[j].setInfo(p);
+ if (players[j].equals(me)) {
+ me.setInfo(p);
+ }
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
}
rooms[i] = new NodeRoom(roomNodes[i].getId(), players);
// Lock room to start with. The ROOM_INFO message will unlock
// any rooms that are not locked. Prevents unwanted clients from
// connecting while room is in an undefined state.
if (! rooms[i].getName().equals(defaultRoomName)) {
rooms[i].lock();
}
try {
if (roomNodes[i].getInfo() != null) {
rooms[i].setInfo(new PropertiesEncoder(roomNodes[i].getInfo()).getProperties());
}
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
if (containsMe) {
currentRoom = rooms[i];
}
if (defaultRoomName.equals(rooms[i].getName())) {
defaultRoomIndex = i;
}
}
if (defaultRoomIndex < 0) {
allRooms = ArrayUtils.prepend(rooms, new NodeRoom(defaultRoomName));
}
else {
allRooms = rooms;
NodeRoom swap = allRooms[0];
allRooms[0] = allRooms[defaultRoomIndex];
allRooms[defaultRoomIndex] = swap;
}
// Do not fire a PropertyChange request, The server will be following immediately
// with a Room List refresh which can cause Icons to flash unexpectedly.
// propSupport.firePropertyChange(ROOM, null, currentRoom);
// propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
public MessageBoard getMessageServer() {
return msgSvr;
}
public Message[] getMessages() {
return msgSvr.getMessages();
}
public void postMessage(String msg) {
msgSvr.postMessage(msg);
}
public Player stringToPlayer(String s) {
NodePlayer p = null;
try {
PropertiesEncoder propEncoder = new PropertiesEncoder(s);
p = new NodePlayer(null);
p.setInfo(propEncoder.getProperties());
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
return p;
}
public String playerToString(Player p) {
Properties props = ((NodePlayer) p).toProperties();
return new PropertiesEncoder(props).getStringValue();
}
public void initializeControls(ChatServerControls controls) {
playerStatusControls.initializeControls(controls);
messageBoardControls.initializeControls(controls);
roomControls.initializeControls(controls);
serverStatusControls.initializeControls(controls);
final GameModule g = GameModule.getGameModule();
g.addCommandEncoder(synchEncoder);
g.addCommandEncoder(privateChatEncoder);
g.addCommandEncoder(soundEncoder);
g.addCommandEncoder(inviteEncoder);
me.setName((String) g.getPrefs().getValue(GameModule.REAL_NAME));
g.getPrefs().getOption(GameModule.REAL_NAME).addPropertyChangeListener(nameChangeListener);
SimpleStatus s = (SimpleStatus) me.getStatus();
s = new SimpleStatus(
s.isLooking(),
s.isAway(),
(String) g.getPrefs().getValue(GameModule.PERSONAL_INFO),
Info.getVersion(),
s.getIp(),
g.getGameVersion() + ((g.getArchiveWriter() == null) ? "" : " (Editing)"),
Long.toHexString(g.getCrc()));
me.setStatus(s);
g.getPrefs().getOption(GameModule.PERSONAL_INFO).addPropertyChangeListener(profileChangeListener);
controls.getRoomTree().setCellRenderer(new LockableRoomTreeRenderer());
}
public void uninitializeControls(ChatServerControls controls) {
messageBoardControls.uninitializeControls(controls);
roomControls.uninitializeControls(controls);
serverStatusControls.uninitializeControls(controls);
playerStatusControls.uninitializeControls(controls);
GameModule.getGameModule().removeCommandEncoder(synchEncoder);
GameModule.getGameModule().removeCommandEncoder(privateChatEncoder);
GameModule.getGameModule().removeCommandEncoder(soundEncoder);
GameModule.getGameModule().removeCommandEncoder(inviteEncoder);
GameModule.getGameModule().getPrefs().getOption(GameModule.REAL_NAME).removePropertyChangeListener(nameChangeListener);
GameModule.getGameModule().getPrefs().getOption(GameModule.PERSONAL_INFO).removePropertyChangeListener(profileChangeListener);
}
}
| true | true | protected void updateRooms(Node module) {
Node[] roomNodes = module.getChildren();
NodeRoom[] rooms = new NodeRoom[roomNodes.length];
int defaultRoomIndex = -1;
for (int i = 0; i < roomNodes.length; ++i) {
Node[] playerNodes = roomNodes[i].getChildren();
NodePlayer[] players = new NodePlayer[playerNodes.length];
boolean containsMe = false;
for (int j = 0; j < playerNodes.length; ++j) {
players[j] = new NodePlayer(playerNodes[j].getId());
if (players[j].equals(me)) {
containsMe = true;
}
try {
Properties p = new PropertiesEncoder(playerNodes[j].getInfo()).getProperties();
players[j].setInfo(p);
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
}
rooms[i] = new NodeRoom(roomNodes[i].getId(), players);
// Lock room to start with. The ROOM_INFO message will unlock
// any rooms that are not locked. Prevents unwanted clients from
// connecting while room is in an undefined state.
if (! rooms[i].getName().equals(defaultRoomName)) {
rooms[i].lock();
}
try {
if (roomNodes[i].getInfo() != null) {
rooms[i].setInfo(new PropertiesEncoder(roomNodes[i].getInfo()).getProperties());
}
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
if (containsMe) {
currentRoom = rooms[i];
}
if (defaultRoomName.equals(rooms[i].getName())) {
defaultRoomIndex = i;
}
}
if (defaultRoomIndex < 0) {
allRooms = ArrayUtils.prepend(rooms, new NodeRoom(defaultRoomName));
}
else {
allRooms = rooms;
NodeRoom swap = allRooms[0];
allRooms[0] = allRooms[defaultRoomIndex];
allRooms[defaultRoomIndex] = swap;
}
// Do not fire a PropertyChange request, The server will be following immediately
// with a Room List refresh which can cause Icons to flash unexpectedly.
// propSupport.firePropertyChange(ROOM, null, currentRoom);
// propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
| protected void updateRooms(Node module) {
Node[] roomNodes = module.getChildren();
NodeRoom[] rooms = new NodeRoom[roomNodes.length];
int defaultRoomIndex = -1;
for (int i = 0; i < roomNodes.length; ++i) {
Node[] playerNodes = roomNodes[i].getChildren();
NodePlayer[] players = new NodePlayer[playerNodes.length];
boolean containsMe = false;
for (int j = 0; j < playerNodes.length; ++j) {
players[j] = new NodePlayer(playerNodes[j].getId());
if (players[j].equals(me)) {
containsMe = true;
}
try {
Properties p = new PropertiesEncoder(playerNodes[j].getInfo()).getProperties();
players[j].setInfo(p);
if (players[j].equals(me)) {
me.setInfo(p);
}
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
}
rooms[i] = new NodeRoom(roomNodes[i].getId(), players);
// Lock room to start with. The ROOM_INFO message will unlock
// any rooms that are not locked. Prevents unwanted clients from
// connecting while room is in an undefined state.
if (! rooms[i].getName().equals(defaultRoomName)) {
rooms[i].lock();
}
try {
if (roomNodes[i].getInfo() != null) {
rooms[i].setInfo(new PropertiesEncoder(roomNodes[i].getInfo()).getProperties());
}
}
// FIXME: review error message
catch (IOException e) {
e.printStackTrace();
}
if (containsMe) {
currentRoom = rooms[i];
}
if (defaultRoomName.equals(rooms[i].getName())) {
defaultRoomIndex = i;
}
}
if (defaultRoomIndex < 0) {
allRooms = ArrayUtils.prepend(rooms, new NodeRoom(defaultRoomName));
}
else {
allRooms = rooms;
NodeRoom swap = allRooms[0];
allRooms[0] = allRooms[defaultRoomIndex];
allRooms[defaultRoomIndex] = swap;
}
// Do not fire a PropertyChange request, The server will be following immediately
// with a Room List refresh which can cause Icons to flash unexpectedly.
// propSupport.firePropertyChange(ROOM, null, currentRoom);
// propSupport.firePropertyChange(AVAILABLE_ROOMS, null, allRooms);
}
|
diff --git a/app/controllers/oauth2/AccessTokenFilter.java b/app/controllers/oauth2/AccessTokenFilter.java
index f743605..7216df7 100644
--- a/app/controllers/oauth2/AccessTokenFilter.java
+++ b/app/controllers/oauth2/AccessTokenFilter.java
@@ -1,62 +1,62 @@
package controllers.oauth2;
import models.User;
import oauth2.CheckUserAuthentication;
import oauth2.OAuth2Constants;
import play.Play;
import play.mvc.Before;
import play.mvc.Router;
import controllers.NoCookieFilter;
/**
*
* @author Alex Jarvis [email protected]
*/
public class AccessTokenFilter extends NoCookieFilter {
protected static CheckUserAuthentication userAuth;
/**
* Checks that the request is secure and therefore encrypted.
*/
@Before
static void checkSSL() {
// Check that HTTPS is being used.
final boolean sslRequired = Boolean.parseBoolean(Play.configuration.getProperty(OAuth2Constants.SSL_REQUIRED, Boolean.TRUE.toString()));
if (sslRequired && !request.secure) {
error(400, "HTTPS required");
}
}
/**
* Checks that the request contains a valid access token.
*/
@Before
static void checkAccessToken() {
// Check oauth_token present in request, if not, error
if (params._contains(OAuth2Constants.PARAM_OAUTH_TOKEN)) {
// Check token exists in system
userAuth = new CheckUserAuthentication();
if (!userAuth.validToken(params.get(OAuth2Constants.PARAM_OAUTH_TOKEN))) {
error(401, "Unauthorized");
}
- // Resources that do not require an access token
- } else if (!request.path.equals(Router.reverse("oauth2.AccessToken.auth").url) &&
- !request.path.equals(Router.reverse("Users.create").url)) {
+ // Resources actions that do not require an access token
+ } else if (!request.actionMethod.equals(Router.reverse("oauth2.AccessToken.auth").action) &&
+ !request.actionMethod.equals(Router.reverse("Users.create").action)) {
error(401, "Unauthorized");
}
}
/**
*
* @return
*/
public User getAuthorisedUser() {
return userAuth.getAuthroisedUser();
}
}
| true | true | static void checkAccessToken() {
// Check oauth_token present in request, if not, error
if (params._contains(OAuth2Constants.PARAM_OAUTH_TOKEN)) {
// Check token exists in system
userAuth = new CheckUserAuthentication();
if (!userAuth.validToken(params.get(OAuth2Constants.PARAM_OAUTH_TOKEN))) {
error(401, "Unauthorized");
}
// Resources that do not require an access token
} else if (!request.path.equals(Router.reverse("oauth2.AccessToken.auth").url) &&
!request.path.equals(Router.reverse("Users.create").url)) {
error(401, "Unauthorized");
}
}
| static void checkAccessToken() {
// Check oauth_token present in request, if not, error
if (params._contains(OAuth2Constants.PARAM_OAUTH_TOKEN)) {
// Check token exists in system
userAuth = new CheckUserAuthentication();
if (!userAuth.validToken(params.get(OAuth2Constants.PARAM_OAUTH_TOKEN))) {
error(401, "Unauthorized");
}
// Resources actions that do not require an access token
} else if (!request.actionMethod.equals(Router.reverse("oauth2.AccessToken.auth").action) &&
!request.actionMethod.equals(Router.reverse("Users.create").action)) {
error(401, "Unauthorized");
}
}
|
diff --git a/core/src/test/java/io/undertow/server/handlers/DateHandlerTestCase.java b/core/src/test/java/io/undertow/server/handlers/DateHandlerTestCase.java
index 783c4353c..4cce724bb 100644
--- a/core/src/test/java/io/undertow/server/handlers/DateHandlerTestCase.java
+++ b/core/src/test/java/io/undertow/server/handlers/DateHandlerTestCase.java
@@ -1,55 +1,55 @@
package io.undertow.server.handlers;
import java.io.IOException;
import io.undertow.testutils.DefaultServer;
import io.undertow.testutils.HttpClientUtils;
import io.undertow.util.DateUtils;
import io.undertow.testutils.TestHttpClient;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Stuart Douglas
*/
@RunWith(DefaultServer.class)
public class DateHandlerTestCase {
@BeforeClass
public static void setup() {
DefaultServer.setRootHandler(new DateHandler(ResponseCodeHandler.HANDLE_200));
}
@Test
public void testDateHandler() throws IOException, InterruptedException {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
TestHttpClient client = new TestHttpClient();
try {
HttpResponse result = client.execute(get);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
Header date = result.getHeaders("Date")[0];
final long firstDate = DateUtils.parseDate(date.getValue()).getTime();
Assert.assertTrue((firstDate + 3000) > System.currentTimeMillis());
- Assert.assertTrue(System.currentTimeMillis() > firstDate);
+ Assert.assertTrue(System.currentTimeMillis() >= firstDate);
HttpClientUtils.readResponse(result);
Thread.sleep(1500);
result = client.execute(get);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
date = result.getHeaders("Date")[0];
final long secondDate = DateUtils.parseDate(date.getValue()).getTime();
Assert.assertTrue((secondDate + 2000) > System.currentTimeMillis());
Assert.assertTrue(System.currentTimeMillis() >= secondDate);
Assert.assertTrue(secondDate > firstDate);
HttpClientUtils.readResponse(result);
} finally {
client.getConnectionManager().shutdown();
}
}
}
| true | true | public void testDateHandler() throws IOException, InterruptedException {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
TestHttpClient client = new TestHttpClient();
try {
HttpResponse result = client.execute(get);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
Header date = result.getHeaders("Date")[0];
final long firstDate = DateUtils.parseDate(date.getValue()).getTime();
Assert.assertTrue((firstDate + 3000) > System.currentTimeMillis());
Assert.assertTrue(System.currentTimeMillis() > firstDate);
HttpClientUtils.readResponse(result);
Thread.sleep(1500);
result = client.execute(get);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
date = result.getHeaders("Date")[0];
final long secondDate = DateUtils.parseDate(date.getValue()).getTime();
Assert.assertTrue((secondDate + 2000) > System.currentTimeMillis());
Assert.assertTrue(System.currentTimeMillis() >= secondDate);
Assert.assertTrue(secondDate > firstDate);
HttpClientUtils.readResponse(result);
} finally {
client.getConnectionManager().shutdown();
}
}
| public void testDateHandler() throws IOException, InterruptedException {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
TestHttpClient client = new TestHttpClient();
try {
HttpResponse result = client.execute(get);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
Header date = result.getHeaders("Date")[0];
final long firstDate = DateUtils.parseDate(date.getValue()).getTime();
Assert.assertTrue((firstDate + 3000) > System.currentTimeMillis());
Assert.assertTrue(System.currentTimeMillis() >= firstDate);
HttpClientUtils.readResponse(result);
Thread.sleep(1500);
result = client.execute(get);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
date = result.getHeaders("Date")[0];
final long secondDate = DateUtils.parseDate(date.getValue()).getTime();
Assert.assertTrue((secondDate + 2000) > System.currentTimeMillis());
Assert.assertTrue(System.currentTimeMillis() >= secondDate);
Assert.assertTrue(secondDate > firstDate);
HttpClientUtils.readResponse(result);
} finally {
client.getConnectionManager().shutdown();
}
}
|
diff --git a/enough-polish-j2me/source/src/de/enough/polish/ui/Item.java b/enough-polish-j2me/source/src/de/enough/polish/ui/Item.java
index cda9d6f..4ca3f54 100644
--- a/enough-polish-j2me/source/src/de/enough/polish/ui/Item.java
+++ b/enough-polish-j2me/source/src/de/enough/polish/ui/Item.java
@@ -1,6443 +1,6446 @@
//#condition polish.usePolishGui
// generated by de.enough.doc2java.Doc2Java (www.enough.de) on Sat Dec 06 15:06:44 CET 2003
/*
* Copyright (c) 2003, 2004 Robert Virkus / Enough Software
*
* This file is part of J2ME Polish.
*
* J2ME Polish 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.
*
* J2ME Polish 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 J2ME Polish; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Commercial licenses are also available, please
* refer to the accompanying LICENSE.txt or visit
* http://www.j2mepolish.org for details.
*/
package de.enough.polish.ui;
import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
//#if polish.android
import de.enough.polish.android.lcdui.AndroidDisplay;
import android.view.View;
//#endif
//#debug ovidiu
import de.enough.polish.benchmark.Benchmark;
//#if polish.blackberry
import net.rim.device.api.ui.Field;
//#endif
import de.enough.polish.event.AsynchronousMultipleCommandListener;
import de.enough.polish.event.EventManager;
import de.enough.polish.event.GestureEvent;
import de.enough.polish.event.UiEventListener;
import de.enough.polish.util.ArrayList;
import de.enough.polish.util.Arrays;
import de.enough.polish.util.DeviceControl;
import de.enough.polish.util.DrawUtil;
import de.enough.polish.util.HashMap;
import de.enough.polish.util.RgbImage;
/**
* A superclass for components that can be added to a Form.
*
* <p>Items support following CSS attributes:
* </p>
* <ul>
* <li><b>margin, margin-left, margin-right, margin-top, margin-bottom</b>: margins between border and next item.</li>
* <li><b>padding, padding-left, padding-right, padding-top, padding-bottom, padding-vertical, padding-horizontal</b>: paddings between border and content.</li>
* <li><b>background</b>: The background of this item.</li>
* <li><b>border</b>: The border of this item.</li>
* <li><b>min-width</b>: The minimum width of this item.</li>
* <li><b>max-width</b>: The maximum width of this item.</li>
* <li><b>min-height</b>: The minimum height of this item.</li>
* <li><b>max-height</b>: The maximum height of this item.</li>
* <li><b>before</b>: URL of image that should be placed before this item.</li>
* <li><b>after</b>: URL of image that should be placed after this item.</li>
* <li><b>include-label</b>: set to true when the background and border should include the label of this item as well.</li>
* <li><b>colspan</b>: when this item is embedded in a table, you can span it over several cells, e.g. colspan: 2;.</li>
* <li><b>label-style</b>: The name of the specialized label style for this item, e.g. "label-style: funnyLabel;"</li>
* <li><b>focused-style</b>: The name of the specialized focused style for this item, e.g. "focused-style: funnyFocused;"</li>
* <li><b>view-type</b>: The view of this item.</li>
* </ul>
*
* A superclass for components that can be added to a <A HREF="../../../javax/microedition/lcdui/Form.html"><CODE>Form</CODE></A>. All <code>Item</code> objects have a label field,
* which is a string that is
* attached to the item. The label is typically displayed near the component
* when it is displayed within a screen. The label should be positioned on
* the same horizontal row as the item or
* directly above the item. The implementation should attempt to distinguish
* label strings from other textual content, possibly by displaying the label
* in a different font, aligning it to a different margin, or appending a
* colon to it if it is placed on the same line as other string content.
* If the screen is scrolling, the implementation should try
* to keep the label visible at the same time as the <code>Item</code>.
*
* <p>In some cases,
* when the user attempts to interact with an <code>Item</code>,
* the system will switch to
* a system-generated screen where the actual interaction takes place. If
* this occurs, the label will generally be carried along and displayed within
* this new screen in order to provide the user with some context for the
* operation. For this reason it is recommended that applications supply a
* label to all interactive Item objects. However, this is not required, and
* a <code>null</code> value for a label is legal and specifies
* the absence of a label.
* </p>
*
* <h3>Item Layout</h3>
*
* <p>An <code>Item's</code> layout within its container is
* influenced through layout directives:</p>
*
* <ul>
* <li> <code>LAYOUT_DEFAULT</code> </li>
* <li> <code>LAYOUT_LEFT</code> </li>
* <li> <code>LAYOUT_RIGHT</code> </li>
* <li> <code>LAYOUT_CENTER</code> </li>
* <li> <code>LAYOUT_TOP</code> </li>
* <li> <code>LAYOUT_BOTTOM</code> </li>
* <li> <code>LAYOUT_VCENTER</code> </li>
* <li> <code>LAYOUT_NEWLINE_BEFORE</code> </li>
* <li> <code>LAYOUT_NEWLINE_AFTER</code> </li>
* <li> <code>LAYOUT_SHRINK</code> </li>
* <li> <code>LAYOUT_VSHRINK</code> </li>
* <li> <code>LAYOUT_EXPAND</code> </li>
* <li> <code>LAYOUT_VEXPAND</code> </li>
* <li> <code>LAYOUT_2</code> </li>
* </ul>
*
* <p>The <code>LAYOUT_DEFAULT</code> directive indicates
* that the container's default
* layout policy is to be used for this item.
* <code>LAYOUT_DEFAULT</code> has the value
* zero and has no effect when combined with other layout directives. It is
* useful within programs in order to document the programmer's intent.</p>
*
* <p>The <code>LAYOUT_LEFT</code>, <code>LAYOUT_RIGHT</code>, and
* <code>LAYOUT_CENTER</code> directives indicate
* horizontal alignment and are mutually exclusive. Similarly, the
* <code>LAYOUT_TOP</code>, <code>LAYOUT_BOTTOM</code>, and
* <code>LAYOUT_VCENTER</code> directives indicate vertical
* alignment and are mutually exclusive.</p>
*
* <p>A horizontal alignment directive, a vertical alignment directive, and
* any combination of other layout directives may be combined using the
* bit-wise <code>OR</code> operator (<code>|</code>) to compose a
* layout directive value. Such a value
* is used as the parameter to the <A HREF="../../../javax/microedition/lcdui/Item.html#setLayout(int)"><CODE>setLayout(int)</CODE></A> method and is the return
* value from the <A HREF="../../../javax/microedition/lcdui/Item.html#getLayout()"><CODE>getLayout()</CODE></A> method.</p>
*
* <p>Some directives have no defined behavior in some contexts. A layout
* directive is ignored if its behavior is not defined for the particular
* context within which the <code>Item</code> resides.</p>
*
* <p>A complete specification of the layout of <code>Items</code>
* within a <code>Form</code> is given
* <a href="Form.html#layout">here</a>.</p>
*
* <a name="sizes"></a>
* <h3>Item Sizes</h3>
*
* <p><code>Items</code> have two explicit size concepts: the <em>minimum</em>
* size and the
* <em>preferred</em> size. Both the minimum and the preferred sizes refer to
* the total area of the <code>Item</code>, which includes space for the
* <code>Item's</code> contents,
* the <code>Item's</code> label, as well as other space that is
* significant to the layout
* policy. These sizes do not include space that is not significant for
* layout purposes. For example, if the addition of a label to an
* <code>Item</code> would
* cause other <code>Items</code> to move in order to make room,
* then the space occupied by
* this label is significant to layout and is counted as part of
* the <code>Item's</code>
* minimum and preferred sizes. However, if an implementation were to place
* the label in a margin area reserved exclusively for labels, this would not
* affect the layout of neighboring <code>Items</code>.
* In this case, the space occupied
* by the label would not be considered part of the minimum and preferred
* sizes.</p>
*
* <p>The minimum size is the smallest size at which the
* <code>Item</code> can function and
* display its contents, though perhaps not optimally. The minimum size
* may be recomputed whenever the <code>Item's</code> contents changes.</p>
*
* <p>The preferred size is generally a size based on the
* <code>Item's</code> contents and
* is the smallest size at which no information is clipped and text wrapping
* (if any) is kept to a tolerable minimum. The preferred size may be
* recomputed whenever the <code>Item's</code> contents changes.
* The application can
* <em>lock</em> the preferred width or preferred height (or both) by
* supplying specific values for parameters to the <A HREF="../../../javax/microedition/lcdui/Item.html#setpreferredSize(int, int)"><CODE>setpreferredSize</CODE></A> method. The manner in which an
* <code>Item</code> fits its contents
* within an application-specified preferred size is implementation-specific.
* However, it is recommended that textual content be word-wrapped to fit the
* preferred size set by the application. The application can <em>unlock</em>
* either or both dimensions by supplying the value <code>-1</code>
* for parameters to the <code>setpreferredSize</code> method.</p>
*
* <p>When an <code>Item</code> is created, both the preferred width
* and height are
* unlocked. In this state, the implementation computes the preferred width
* and height based on the <code>Item's</code> contents, possibly
* including other relevant
* factors such as the <code>Item's</code> graphic design and the
* screen dimensions.
* After having locked either the preferred width or height, the application
* can restore the initial, unlocked state by calling
* <code>setpreferredSize(-1, -1)</code>.</p>
*
* <p>The application can lock one dimension of the preferred size and leave
* the other unlocked. This causes the system to compute an appropriate value
* for the unlocked dimension based on arranging the contents to fit the
* locked dimension. If the contents changes, the size on the unlocked
* dimension is recomputed to reflect the new contents, but the size on the
* locked dimension remains unchanged. For example, if the application called
* <code>setpreferredSize(50, -1)</code>, the preferred width would be
* locked at <code>50</code> pixels and the preferred height would
* be computed based on the
* <code>Item's</code> contents. Similarly, if the application called
* <code>setpreferredSize(-1, 60)</code>, the preferred height would be
* locked at <code>60</code> pixels and the preferred width would be
* computed based on the
* <code>Item's</code> contents. This feature is particularly useful
* for <code>Items</code> with
* textual content that can be line wrapped.</p>
*
* <p>The application can also lock both the preferred width and height to
* specific values. The <code>Item's</code> contents are truncated or padded
* as necessary to honor this request. For <code>Items</code> containing
* text, the text should be wrapped to the specified width, and any truncation
* should occur at the end of the text.</p>
*
* <p><code>Items</code> also have an implicit maximum size provided by the
* implementation. The maximum width is typically based on the width of the
* screen space available to a <code>Form</code>. Since <code>Forms</code>
* can scroll vertically, the maximum height should typically not be based on
* the height of the available screen space.</p>
*
* <p>If the application attempts to lock a preferred size dimension to a
* value smaller than the minimum or larger than the maximum, the
* implementation may disregard the requested value and instead use either the
* minimum or maximum as appropriate. If this occurs, the actual values used
* must be visible to the application via the values returned from the
* <A HREF="../../../javax/microedition/lcdui/Item.html#getpreferredWidth()"><CODE>getpreferredWidth</CODE></A> and
* <A HREF="../../../javax/microedition/lcdui/Item.html#getpreferredHeight()"><CODE>getpreferredHeight</CODE></A> methods.
* </p>
*
* <h3>Commands</h3>
*
* <p>A <code>Command</code> is said to be present on an <code>Item</code>
* if the <code>Command</code> has been
* added to this <code>Item</code> with a prior call to <A HREF="../../../javax/microedition/lcdui/Item.html#addCommand(javax.microedition.lcdui.Command)"><CODE>addCommand(javax.microedition.lcdui.Command)</CODE></A>
* or <A HREF="../../../javax/microedition/lcdui/Item.html#setDefaultCommand(javax.microedition.lcdui.Command)"><CODE>setDefaultCommand(javax.microedition.lcdui.Command)</CODE></A> and if
* the <code>Command</code> has not been removed with a subsequent call to
* <A HREF="../../../javax/microedition/lcdui/Item.html#removeCommand(javax.microedition.lcdui.Command)"><CODE>removeCommand(javax.microedition.lcdui.Command)</CODE></A>. <code>Commands</code> present on an
* item should have a command
* type of <code>ITEM</code>. However, it is not an error for a
* command whose type is
* other than <code>ITEM</code> to be added to an item.
* For purposes of presentation and
* placement within its user interface, the implementation is allowed to
* treat a command's items as if they were of type <code>ITEM</code>. </p>
*
* <p><code>Items</code> may have a <em>default</em> <code>Command</code>.
* This state is
* controlled by the <A HREF="../../../javax/microedition/lcdui/Item.html#setDefaultCommand(javax.microedition.lcdui.Command)"><CODE>setDefaultCommand(javax.microedition.lcdui.Command)</CODE></A> method. The default
* <code>Command</code> is eligible to be bound to a special
* platform-dependent user
* gesture. The implementation chooses which gesture is the most
* appropriate to initiate the default command on that particular
* <code>Item</code>.
* For example, on a device that has a dedicated selection key, pressing
* this key might invoke the item's default command. Or, on a
* stylus-based device, tapping on the <code>Item</code> might
* invoke its default
* command. Even if it can be invoked through a special gesture, the
* default command should also be invokable in the same fashion as
* other item commands.</p>
*
* <p>It is possible that on some devices there is no special gesture
* suitable for invoking the default command on an item. In this case
* the default command must be accessible to the user in the same
* fashion as other item commands. The implementation may use the state
* of a command being the default in deciding where to place the command
* in its user interface.</p>
*
* <p>It is possible for an <code>Item</code> not to have a default command.
* In this
* case, the implementation may bind its special user gesture (if any)
* for another purpose, such as for displaying a menu of commands. The
* default state of an <code>Item</code> is not to have a default command.
* An <code>Item</code>
* may be set to have no default <code>Command</code> by removing it from
* the <code>Item</code> or
* by passing <code>null</code> to the <code>setDefaultCommand()</code>
* method.</p>
*
* <p>The same command may occur on more than one
* <code>Item</code> and also on more than
* one <code>Displayable</code>. If this situation occurs, the user
* must be provided with
* distinct gestures to invoke that command on each <code>Item</code> or
* <code>Displayable</code> on
* which it occurs, while those <code>Items</code> or <code>Displayables</code>
* are visible on the
* display. When the user invokes the command, the listener
* (<code>CommandListener</code>
* or <code>ItemCommandListener</code> as appropriate) of just the
* object on which the
* command was invoked will be called.</p>
*
* <p>Adding commands to an <code>Item</code> may affect its appearance, the
* way it is laid out, and the traversal behavior. For example, the presence
* of commands on an <code>Item</code> may cause row breaks to occur, or it
* may cause additional graphical elements (such as a menu icon) to appear.
* In particular, if a <code>StringItem</code> whose appearance mode is
* <code>PLAIN</code> (see below) is given one or more <code>Commands</code>,
* the implementation is allowed to treat it as if it had a different
* appearance mode.</p>
*
* <p>J2ME Polish notifies the command-listener of the current screen,
* when an item-command has been selected and no item-command-listener
* has been registered.
* </p>
*
* <a name="appearance"></a>
* <h3>Appearance Modes</h3>
*
* <p>The <code>StringItem</code> and <code>ImageItem</code> classes have an
* <em>appearance mode</em> attribute that can be set in their constructors.
* This attribute can have one of the values <A HREF="../../../javax/microedition/lcdui/Item.html#PLAIN"><CODE>PLAIN</CODE></A>,
* <A HREF="../../../javax/microedition/lcdui/Item.html#HYPERLINK"><CODE>HYPERLINK</CODE></A>, or <A HREF="../../../javax/microedition/lcdui/Item.html#BUTTON"><CODE>BUTTON</CODE></A>.
* An appearance mode of <code>PLAIN</code> is typically used
* for non-interactive
* display of textual or graphical material. The appearance
* mode values do not have any side effects on the interactivity of the item.
* In order to be interactive, the item must have one or more
* <code>Commands</code>
* (preferably with a default command assigned), and it must have a
* <code>CommandListener</code> that receives notification of
* <code>Command</code> invocations. The
* appearance mode values also do not have any effect on the semantics of
* <code>Command</code> invocation on the item. For example,
* setting the appearance mode
* of a <code>StringItem</code> to be <code>HYPERLINK</code>
* requests that the implementation display
* the string contents as if they were a hyperlink in a browser. It is the
* application's responsibility to attach a <code>Command</code>
* and a listener to the
* <code>StringItem</code> that provide behaviors that the user
* would expect from invoking
* an operation on a hyperlink, such as loading the referent of the link or
* adding the link to the user's set of bookmarks.</p>
*
* <p>Setting the appearance mode of an <code>Item</code> to be other than
* <code>PLAIN</code> may affect its minimum, preferred, and maximum sizes, as
* well as the way it is laid out. For example, a <code>StringItem</code>
* with an appearance mode of <code>BUTTON</code> should not be wrapped across
* rows. (However, a <code>StringItem</code> with an appearance mode of
* <code>HYPERLINK</code> should be wrapped the same way as if its appearance
* mode is <code>PLAIN</code>.)</p>
*
* <p>A <code>StringItem</code> or <code>ImageItem</code>
* in <code>BUTTON</code> mode can be used to create a
* button-based user interface. This can easily lead to applications that are
* inconvenient to use. For example, in a traversal-based system, users must
* navigate to a button before they can invoke any commands on it. If buttons
* are spread across a long <code>Form</code>, users may be required
* to perform a
* considerable amount of navigation in order to discover all the available
* commands. Furthermore, invoking a command from a button at the
* other end of the <code>Form</code> can be quite cumbersome.
* Traversal-based systems
* often provide a means of invoking commands from anywhere (such as from a
* menu), without the need to traverse to a particular item. Instead of
* adding a command to a button and placing that button into a
* <code>Form</code>, it would
* often be more appropriate and convenient for users if that command were
* added directly to the <code>Form</code>. Buttons should be used
* only in cases where
* direct user interaction with the item's string or image contents is
* essential to the user's understanding of the commands that can be invoked
* from that item.</p>
*
* <h3>Default State</h3>
*
* <p>Unless otherwise specified by a subclass, the default state of newly
* created <code>Items</code> is as follows:</p>
*
* <ul>
* <li>the <code>Item</code> is not contained within
* ("owned by") any container;</li>
* <li>there are no <code>Commands</code> present;</li>
* <li>the default <code>Command</code> is <code>null</code>;</li>
* <li>the <code>ItemCommandListener</code> is <code>null</code>;</li>
* <li>the layout directive value is <code>LAYOUT_DEFAULT</code>; and</li>
* <li>both the preferred width and preferred height are unlocked.</li>
* </ul>
*
* <p>copyright Enough Software 2004 - 2009</p>
* @since MIDP 1.0
*/
public abstract class Item implements UiElement, Animatable
{
//#if polish.handleEvents || polish.css.animations
//#define tmp.handleEvents
private boolean hasBeenShownBefore;
//#endif
/**
* A J2ME Polish constant defining a transparent/invisible color.
* TRANSPARENT has the value -1.
*/
public static final int TRANSPARENT = -1;
/**
* A J2ME Polish constant defining a vertical orientation.
* VERTICAL has the value 0.
*/
public static final int VERTICAL = 0;
/**
* A J2ME Polish constant defining a horizontal orientation.
* HORIZONTAL has the value 1.
*/
public static final int HORIZONTAL = 1;
/**
* A layout directive indicating that this <code>Item</code>
* should follow the default layout policy of its container.
*
* <P>Value <code>0</code> is assigned to <code>LAYOUT_DEFAULT</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_DEFAULT = 0;
/**
* A layout directive indicating that this <code>Item</code> should have a
* left-aligned layout.
*
* <P>Value <code>1</code> is assigned to <code>LAYOUT_LEFT</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_LEFT = 1;
/**
* A layout directive indicating that this <code>Item</code> should have a
* right-aligned layout.
*
* <P>Value <code>2</code> is assigned to <code>LAYOUT_RIGHT</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_RIGHT = 2;
/**
* A layout directive indicating that this <code>Item</code> should have a
* horizontally centered layout.
*
* <P>Value <code>3</code> is assigned to <code>LAYOUT_CENTER</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_CENTER = 3;
/**
* A layout directive indicating that this <code>Item</code> should have a
* top-aligned layout.
*
* <P>Value <code>0x10</code> is assigned to <code>LAYOUT_TOP</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_TOP = 0x10;
/**
* A layout directive indicating that this <code>Item</code> should have a
* bottom-aligned layout.
*
* <P>Value <code>0x20</code> is assigned to <code>LAYOUT_BOTTOM</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_BOTTOM = 0x20;
/**
* A layout directive indicating that this <code>Item</code> should have a
* vertically centered layout.
*
* <P>Value <code>0x30</code> is assigned to
* <code>LAYOUT_VCENTER</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_VCENTER = 0x30;
/**
* A layout directive indicating that this <code>Item</code>
* should be placed at the beginning of a new line or row.
*
* <P>Value <code>0x100</code> is assigned to
* <code>LAYOUT_NEWLINE_BEFORE</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_NEWLINE_BEFORE = 0x100;
/**
* A layout directive indicating that this <code>Item</code>
* should the last on its line or row, and that the next
* <code>Item</code> (if any) in the container
* should be placed on a new line or row.
*
* <P>Value <code>0x200</code> is assigned to
* <code>LAYOUT_NEWLINE_AFTER</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_NEWLINE_AFTER = 0x200;
/**
* A layout directive indicating that this <code>Item's</code>
* width may be reduced to its minimum width.
*
* <P>Value <code>0x400</code> is assigned to <code>LAYOUT_SHRINK</code></P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_SHRINK = 0x400;
/**
* A layout directive indicating that this <code>Item's</code>
* width may be increased to fill available space.
*
* <P>Value <code>0x800</code> is assigned to <code>LAYOUT_EXPAND</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_EXPAND = 0x800;
/**
* A layout directive indicating that this <code>Item's</code>
* height may be reduced to its minimum height.
*
* <P>Value <code>0x1000</code> is assigned to
* <code>LAYOUT_VSHRINK</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_VSHRINK = 0x1000;
/**
* A layout directive indicating that this <code>Item's</code>
* height may be increased to fill available space.
*
* <P>Value <code>0x2000</code> is assigned to
* <code>LAYOUT_VEXPAND</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_VEXPAND = 0x2000;
/**
* A layout directive indicating that new MIDP 2.0 layout
* rules are in effect for this <code>Item</code>. If this
* bit is clear, indicates that MIDP 1.0 layout behavior
* applies to this <code>Item</code>.
*
* <P>Value <code>0x4000</code> is assigned to
* <code>LAYOUT_2</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int LAYOUT_2 = 0x4000;
/**
* An appearance mode value indicating that the <code>Item</code> is to have
* a normal appearance.
*
* <P>Value <code>0</code> is assigned to <code>PLAIN</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int PLAIN = 0;
/**
* An appearance mode value indicating that the <code>Item</code>
* is to appear as a hyperlink.
* <P>Value <code>1</code> is assigned to <code>HYPERLINK</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int HYPERLINK = 1;
/**
* An appearance mode value indicating that the <code>Item</code>
* is to appear as a button.
* <P>Value <code>2</code> is assigned to <code>BUTTON</code>.</P>
*
* @since MIDP 2.0
*/
public static final int BUTTON = 2;
/**
* A J2ME Polish appearance mode value indicating that the <code>Item</code>
* accepts input from the user.
* <P>Value <code>3</code> is assigned to <code>INTERACTIVE</code>.</P>
*/
public static final int INTERACTIVE = 3;
private static final ArrayList COMMANDS = new ArrayList();
protected int layout;
protected ItemCommandListener itemCommandListener;
protected Command defaultCommand;
protected int preferredWidth;
protected int preferredHeight;
//#ifdef polish.css.width
protected Dimension cssWidth;
//#endif
//#ifdef polish.css.height
protected Dimension cssHeight;
//#endif
protected Dimension minimumWidth;
protected Dimension minimumHeight;
//#ifdef polish.css.max-width
protected Dimension maximumWidth;
//#endif
//#ifdef polish.css.max-height
protected Dimension maximumHeight;
//#endif
//#ifdef polish.css.min-item-width
protected Dimension minimumItemWidth;
//#endif
//#ifdef polish.css.min-item-height
protected Dimension minimumItemHeight;
//#endif
//#ifdef polish.css.max-item-width
protected Dimension maximumItemWidth;
//#endif
//#ifdef polish.css.max-item-height
protected Dimension maximumItemHeight;
//#endif
boolean isInitialized;
/** the background of this item */
public Background background;
protected Border border;
//#if polish.css.border-adjust
private Dimension borderAdjust;
//#endif
//#if polish.css.bgborder
/** the background border of an item - this border is painted before the background. This field
* is only present when polish.css.bgborder is true.
*/
protected Border bgBorder;
//#endif
protected Style style;
/** the width of this item - only for read access */
public int itemWidth;
/** the height of this item - only for read access */
public int itemHeight;
protected int paddingLeft;
protected int paddingTop;
protected int paddingRight;
protected int paddingBottom;
protected int paddingVertical;
protected int paddingHorizontal;
protected int marginLeft;
protected int marginTop;
protected int marginRight;
protected int marginBottom;
/** The width of this item's content **/
protected int contentWidth;
/** The height of this item's content **/
protected int contentHeight;
protected int availContentWidth;
protected int availContentHeight;
protected int backgroundWidth;
protected int backgroundHeight;
/** The appearance mode of this item, either PLAIN or one of the interactive modes BUTTON, HYPERLINK or INTERACTIVE. */
public int appearanceMode;
/**
* The screen to which this item belongs to.
*/
protected Screen screen;
//#ifdef polish.useDynamicStyles
/**
* The appropriate CSS selector of this item.
* This is either the style's name or a selector
* depending on the state of this item. A StringItem
* can have the selector "p", "a" or "button", for example.
* This variable can only be used, when the proprocessing variable
* "polish.useDynamicStyles" is defined.
*/
protected String cssSelector;
//#endif
/**
* Determines whether the style has be dynamically assigned already.
*/
protected boolean isStyleInitialised;
/**
* The parent of this item.
*/
protected Item parent;
protected ArrayList commands;
protected boolean isLayoutCenter;
protected boolean isLayoutExpand;
protected boolean isLayoutRight;
// the current positions of this item:
/** the horizontal start position relative to it's parent's item left content edge */
public int relativeX;
/** the vertical start position of this item relative to it's parent item top content edge */
public int relativeY;
/** the horizontal position of this item's content relative to it's left edge (so for a left aligned item its marginLeft + border.widthLeft + paddingLeft */
protected int contentX;
/** the vertical position of this item's content relative to it's top edge */
protected int contentY; // absolute top vertical position of the content
// the current positions of an internal element relative to the content origin
// which should be visible:
/** no internal position has been set for this item, value is -9999.
* This is used as a value for internalX to describe that the item has no intenal position set
*/
public final static int NO_POSITION_SET = -9999;
/**
* The internal horizontal position of this item's content relative to it's left edge.
* When it is equal NO_POSITION_SET this item's internal position is not known.
* The internal position is useful for items that have a large content which
* needs to be scrolled, e.g. containers.
*/
protected int internalX = NO_POSITION_SET;
/** the vertical position of this item's internal content relative to it's top edge */
protected int internalY;
/** The internal width of this item's content. */
protected int internalWidth;
/** The internal height of this item's content. */
protected int internalHeight;
/** flag indicating whether this item is focused, please use isFocused() for accessing it. */
public boolean isFocused;
protected boolean isJustFocused;
//#ifdef polish.css.before
private String beforeUrl;
private int beforeWidth;
private int beforeHeight;
private Image beforeImage;
//#endif
//#ifdef polish.css.after
private String afterUrl;
private int afterWidth;
private int afterHeight;
private Image afterImage;
//#endif
// label settings:
protected Style labelStyle = StyleSheet.labelStyle;
protected StringItem label;
/** indicates that label and content are positioned on the same row if true */
protected boolean useSingleRow;
//#if polish.blackberry
/** a blackberry specific internal field */
public Field _bbField;
//#endif
//#if polish.android
protected View _androidView;
//#endif
protected Style focusedStyle;
protected boolean isPressed;
//#if polish.css.pressed-style
private Style normalStyle;
private Style pressedStyle;
//#endif
//#if polish.css.colspan
protected int colSpan = 1;
//#endif
//#if polish.css.rowspan
protected int rowSpan = 1;
//#endif
//#if polish.css.include-label
protected boolean includeLabel;
//#endif
//#if polish.css.complete-background
protected Background completeBackground;
//#endif
//#if polish.css.complete-border
protected Border completeBorder;
//#endif
//#if polish.css.complete-background || polish.css.complete-border
protected Dimension completeBackgroundPadding;
//#endif
/** The vertical offset for the background, can be used for smoother scrolling, for example */
protected int backgroundYOffset;
//#ifdef polish.css.view-type
protected ItemView view;
protected boolean preserveViewType;
protected boolean setView;
//#endif
//#if polish.supportInvisibleItems || polish.css.visible
//#define tmp.invisible
protected boolean isInvisible;
private int invisibleAppearanceModeCache;
private int invisibleItemHeight;
//#endif
protected boolean isShown;
private HashMap attributes;
//#if polish.css.opacity && polish.midp2
protected int opacity = 255;
protected int[] opacityRgbData;
protected boolean opacityPaintNormally;
private int opacityAtGeneration;
//#endif
private ItemStateListener itemStateListener;
//#if polish.css.x-adjust
protected Dimension xAdjustment;
//#endif
//#if polish.css.y-adjust
protected Dimension yAdjustment;
//#endif
//#if polish.css.content-x-adjust
protected Dimension contentXAdjustment;
//#endif
//#if polish.css.content-y-adjust
protected Dimension contentYAdjustment;
//#endif
//#if polish.css.background-width
private int originalBackgroundWidth;
//#endif
//#if polish.css.background-height
private int originalBackgroundHeight;
//#endif
//#if polish.css.background-anchor && (polish.css.background-width || polish.css.background-height)
private int backgroundAnchor;
//#endif
//#if polish.css.content-visible
protected boolean isContentVisible = true;
//#endif
//#if polish.css.filter
private RgbFilter[] filters;
private boolean isFiltersActive;
private boolean filterPaintNormally;
private RgbFilter[] originalFilters;
private RgbImage filterRgbImage;
private RgbImage filterProcessedRgbImage;
public boolean cacheItemImage ;
//#endif
//#if polish.css.inline-label
protected boolean isInlineLabel;
//#endif
protected int availableWidth;
protected int availableHeight;
protected boolean ignoreRepaintRequests;
private ItemTransition itemTransition;
private boolean preserveBackground;
private boolean preserveBorder;
//#if polish.css.visited-style
private boolean hasBeenVisited;
//#endif
//#if polish.css.portrait-style || polish.css.landscape-style
protected Style landscapeStyle;
protected Style portraitStyle;
//#endif
//#if polish.Item.ShowCommandsOnHold
//#define tmp.supportTouchGestures
private boolean isShowCommands;
private Container commandsContainer;
//#endif
//#if polish.supportTouchGestures
//#define tmp.supportTouchGestures
//#endif
//#if tmp.supportTouchGestures
private long gestureStartTime;
private int gestureStartX;
private int gestureStartY;
private boolean isIgnorePointerReleaseForGesture;
//#endif
//#if polish.useNativeGui
protected NativeItem nativeItem;
//#endif
private UiEventListener uiEventListener;
private CycleListener cycleListener;
/**
* Convenience constructor.
* Creates a new item without label, with a left aligned layout and Item.PLAIN appearance mode.
*/
protected Item() {
this( null, LAYOUT_DEFAULT, PLAIN, null );
}
/**
* Convenience constructor.
* Creates a new item without label, with a left aligned layout, an Item.PLAIN appearance mode and the given style.
* @param style the style for this item
*/
protected Item( Style style ) {
this( null, LAYOUT_DEFAULT, PLAIN, style );
}
/**
* Convenience constructor.
* Creates a new item with the specified label and layout, an Item.PLAIN appearance mode and default style.
* @param label the label of this item
* @param layout the layout of this item
*/
protected Item( String label, int layout) {
this( label, layout, PLAIN, null );
}
/**
* Creates a new Item.
*
* @param label the label of this item
* @param layout the layout of this item
* @param appearanceMode the mode of this item, either Item.PLAIN or Item.INTERACTIVE (Item.BUTTON, Item.HYPERLINK, Item.INTERACTIVE)
* @param style the style of this item - contains the background, border etc.
*/
protected Item(String label, int layout, int appearanceMode, Style style) {
this.style = style;
this.layout = layout;
this.appearanceMode = appearanceMode;
if (label != null && label.length() != 0) {
setLabel( label );
}
if (style == null) {
this.layout = layout;
} else {
this.style = style;
this.isStyleInitialised = false;
}
//#if polish.css.filter
cacheItemImage = true ;
//#endif
}
/**
* Sets the label of the <code>Item</code>. If <code>label</code>
* is <code>null</code>, specifies that this item has no label.
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param label - the label string
* @throws IllegalStateException - if this Item is contained within an Alert
* @see #getLabel()
*/
public void setLabel( String label)
{
if (this.label == null) {
this.label = new StringItem( null, label, this.labelStyle );
this.label.parent = this; // orginally used "this.parent", however that field might not be known at this moment.
if (this.isShown){
this.label.showNotify();
}
} else if ((label == null && this.label.getText() == null) || (label != null && label.equals(this.label.getText())) ){
return;
} else {
this.label.setText( label );
}
if (isInitialized()) {
setInitialized(false);
repaint();
}
}
/**
* Gets the label of this <code>Item</code> object.
*
* @return the label string
* @see #setLabel(java.lang.String)
*/
public String getLabel()
{
if (this.label == null) {
return null;
} else {
return this.label.getText();
}
}
/**
* Retrieves the label item that is used by this item.\
*
* @return the item or null when no item is used.
*/
public Item getLabelItem() {
return this.label;
}
/**
* Gets the layout directives used for placing the item.
*
* @return a combination of layout directive values
* @see #setLayout(int)
* @since MIDP 2.0
*/
public int getLayout()
{
return this.layout;
}
/**
* Sets the layout directives for this item.
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param layout - a combination of layout directive values for this item
* @throws IllegalArgumentException - if the value of layout is not a bit-wise OR combination of layout directives
* @throws IllegalStateException - if this Item is contained within an Alert
* @see #getLayout()
* @since MIDP 2.0
*/
public void setLayout(int layout)
{
if (layout != this.layout) {
this.layout = layout;
// horizontal styles: center -> right -> left
if ( ( layout & LAYOUT_CENTER ) == LAYOUT_CENTER ) {
this.isLayoutCenter = true;
this.isLayoutRight = false;
} else {
this.isLayoutCenter = false;
if ( (layout & LAYOUT_RIGHT ) == LAYOUT_RIGHT ) {
this.isLayoutRight = true;
} else {
this.isLayoutRight = false;
}
}
// vertical styles: vcenter -> bottom -> top
// expanding layouts:
if ( ( layout & LAYOUT_EXPAND ) == LAYOUT_EXPAND ) {
this.isLayoutExpand = true;
} else {
this.isLayoutExpand = false;
}
if (isInitialized()) {
setInitialized(false);
repaint();
} else if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
this.layout = layout;
}
}
}
/**
* Returns the appearance mode of this <code>Item</code>.
* See <a href="Item.html#appearance">Appearance Modes</a>.
*
* @return the appearance mode value, one of Item.PLAIN, Item.HYPERLINK, or Item.BUTTON
* @since MIDP 2.0
*/
public int getAppearanceMode()
{
return this.appearanceMode;
}
/**
* Sets the appearance mode of this item.
*
* @param appearanceMode the mode value, one of Item.PLAIN, Item.HYPERLINK, or Item.BUTTON
*/
public void setAppearanceMode( int appearanceMode ) {
this.appearanceMode = appearanceMode;
}
//#ifdef polish.css.view-type
/**
* Sets the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
* @param view the new view, use null to remove the current view
*/
public void setView( ItemView view ) {
if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
}
this.view = view;
if (view != null && this.style != null) {
view.setStyle( this.style );
}
}
//#endif
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @return the current view, may be null
*/
public ItemView getView() {
return this.view;
}
//#endif
/**
* Retrieves the style of this item.
*
* @return the style of this item.
*/
public Style getStyle() {
return this.style;
}
/**
* Sets a new background for this item.
* @param background the new background, use null for not showing a background
*/
public void setBackground( Background background ) {
this.preserveBackground = true;
this.background = background;
this.background.setParentItem(this);
}
/**
* Sets a new border for this item
* @param border the new border, use null for not showing a border
*/
public void setBorder( Border border ) {
this.preserveBorder = true;
this.border = border;
}
/**
* Sets the style for an item
* with the use of style preprocessing e.g.:
* //#style myStyle
* setStyle();
*/
public void setStyle() {
// do nothing here
}
/**
* Sets the style of this item.
*
* @param style the new style for this item.
* @throws NullPointerException when style is null
*/
public void setStyle( Style style ) {
//#debug
System.out.println("setting style " + style.name + " for " + this + ", prevStyle=" + (this.style == null ? "<null>" : this.style.name) );
this.isStyleInitialised = true;
this.style = style;
if (style != StyleSheet.defaultStyle) {
setLayout( style.layout );
}
//System.out.println( this + " style [" + style.name + "]: right: " + this.isLayoutRight + " center: " + this.isLayoutCenter + " expand: " + this.isLayoutExpand + " layout=" + Integer.toHexString(this.layout));
if (this.isShown) {
if (this.background != style.background && !this.preserveBackground) {
if (this.background != null) {
this.background.hideNotify();
}
if (style.background != null) {
style.background.showNotify();
}
}
if (this.border != style.border && !this.preserveBackground) {
if (this.border != null) {
this.border.hideNotify();
}
if (style.border != null) {
style.border.showNotify();
}
}
}
if (!this.preserveBackground) {
this.background = style.background;
}
if (!this.preserveBorder) {
this.border = style.border;
}
//#if polish.css.content-visible
Boolean contentVisibleBool = style.getBooleanProperty("content-visible");
if (contentVisibleBool != null) {
this.isContentVisible = contentVisibleBool.booleanValue();
}
//#endif
//#if polish.css.bgborder
Border bgBord = (Border) style.getObjectProperty("bgborder");
this.bgBorder = bgBord;
//#endif
//#ifdef polish.css.label-style
Style labStyle = (Style) style.getObjectProperty("label-style");
if (labStyle != null) {
this.labelStyle = labStyle;
} else if (this.labelStyle == null) {
this.labelStyle = StyleSheet.labelStyle;
}
//#else
this.labelStyle = StyleSheet.labelStyle;
//#endif
if (this.label != null) {
this.label.setStyle( this.labelStyle );
}
//#ifdef polish.css.focused-style
//Object object = style.getObjectProperty("focused-style");
//if (object != null) {
// System.out.println("focused-type: " + object.getClass().getName());
//}
Style focused = (Style) style.getObjectProperty("focused-style");
if (focused != null) {
this.focusedStyle = focused;
}
//#endif
//#if polish.css.pressed-style
Style pressed = (Style) style.getObjectProperty("pressed-style");
if (pressed != null) {
this.pressedStyle = pressed;
}
//#endif
//#if polish.css.complete-background
Background bg = (Background) style.getObjectProperty("complete-background");
if (this.isShown && this.completeBackground != bg) {
if (this.completeBackground != null) {
this.completeBackground.hideNotify();
}
if (bg != null) {
bg.showNotify();
}
}
this.completeBackground = bg;
//#endif
//#if polish.css.complete-border
Border brd = (Border) style.getObjectProperty("complete-border");
if (this.isShown && this.completeBorder != brd) {
if (this.completeBorder != null) {
this.completeBorder.hideNotify();
}
if (brd != null) {
brd.showNotify();
}
}
this.completeBorder = brd;
//#endif
//#ifdef polish.css.view-type
ItemView viewType = (ItemView) style.getObjectProperty("view-type");
// if (this instanceof ChoiceGroup) {
// System.out.println("SET.STYLE / CHOICEGROUP: found view-type (1): " + (viewType != null) + " for " + this);
// }
if (viewType != null && viewType.isValid(this, style)) {
this.view = getView( viewType, style );
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.setStyle(style);
}
//#endif
//#if polish.css.background-anchor && (polish.css.background-width || polish.css.background-height)
Integer bgAnchor = style.getIntProperty("background-anchor");
if (bgAnchor != null) {
this.backgroundAnchor = bgAnchor.intValue();
}
//#endif
//#if polish.css.filter
RgbFilter[] filterObjects = (RgbFilter[]) style.getObjectProperty("filter");
if (filterObjects != null) {
if (filterObjects != this.originalFilters) {
this.filters = new RgbFilter[ filterObjects.length ];
for (int i = 0; i < filterObjects.length; i++)
{
RgbFilter rgbFilter = filterObjects[i];
try
{
this.filters[i] = (RgbFilter) rgbFilter.getClass().newInstance();
} catch (Exception e)
{
//#debug warn
System.out.println("Unable to initialize filter class " + rgbFilter.getClass().getName() + e );
}
}
this.originalFilters = filterObjects;
}
}
//#endif
//#if polish.css.inline-label
Boolean inlineBool = style.getBooleanProperty("inline-label");
if (inlineBool != null) {
this.isInlineLabel = inlineBool.booleanValue();
}
//#endif
//#if polish.css.portrait-style || polish.css.landscape-style
//#if polish.css.landscape-style
Style lsStyle = (Style) style.getObjectProperty("landscape-style");
if (lsStyle != null && lsStyle != style) {
this.landscapeStyle = lsStyle;
if ((!this.isFocused)&& style.name != null && style.name.indexOf("landscape") == -1) {
this.portraitStyle = style;
}
}
//#endif
//#if polish.css.portrait-style
Style ptStyle = (Style) style.getObjectProperty("portrait-style");
if (ptStyle != null && ptStyle != style) {
if ((!this.isFocused)&& style.name != null && style.name.indexOf("portrait") == -1) {
this.landscapeStyle = style;
}
this.portraitStyle = ptStyle;
}
//#endif
//#endif
// now set other style attributes:
setStyle( style, true );
setInitialized(false);
}
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item or instantiates a new one.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @param viewType the view registered in the style
* @param viewStyle the style
* @return the view, may be null
*/
protected ItemView getView(ItemView viewType, Style viewStyle)
{
if (this.view == null || this.view.getClass() != viewType.getClass()) {
try {
// formerly we have used the style's instance when that instance was still free.
// However, that approach lead to GC problems, as the style is not garbage collected.
viewType = (ItemView) viewType.getClass().newInstance();
viewType.parentItem = this;
if (this.isShown) {
if (this.view != null) {
this.view.hideNotify();
}
viewType.showNotify();
}
return viewType;
} catch (Exception e) {
//#debug error
System.out.println("Container: Unable to init view-type " + e );
}
}
return this.view;
}
//#endif
/**
* Sets the style of this item for animatable CSS attributes.
*
* @param style the new style for this element.
* @param resetStyle true when style settings should be resetted. This is not the case
* when styles are animated, for example.
* @throws NullPointerException when style is null
*/
public void setStyle( Style style, boolean resetStyle ) {
if(!resetStyle && isInitialized()) {
// boolean initializationRequired = false;
Dimension value;
//#if polish.css.margin
value = (Dimension) style.getObjectProperty("margin");
if (value != null) {
int margin = value.getValue(this.availableWidth);
this.marginLeft = margin;
this.marginRight = margin;
this.marginTop = margin;
this.marginBottom = margin;
// initializationRequired = true;
}
//#endif
//#if polish.css.margin-left
value = (Dimension) style.getObjectProperty("margin-left");
if (value != null) {
this.marginLeft = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.margin-right
value = (Dimension) style.getObjectProperty("margin-right");
if (value != null) {
this.marginRight = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.margin-top
value = (Dimension) style.getObjectProperty("margin-top");
if (value != null) {
this.marginTop = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.margin-bottom
value = (Dimension) style.getObjectProperty("margin-bottom");
if (value != null) {
this.marginBottom = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.padding
value = (Dimension) style.getObjectProperty("padding");
if (value != null) {
int padding = value.getValue(this.availableWidth);
this.paddingLeft = padding;
this.paddingRight = padding;
this.paddingTop = padding;
this.paddingHorizontal = padding;
this.paddingVertical = padding;
// initializationRequired = true;
}
//#endif
//#if polish.css.padding-left
value = (Dimension) style.getObjectProperty("padding-left");
if (value != null) {
this.paddingLeft = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.padding-right
value = (Dimension) style.getObjectProperty("padding-right");
if (value != null) {
this.paddingRight = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.padding-top
value = (Dimension) style.getObjectProperty("padding-top");
if (value != null) {
this.paddingTop = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.padding-bottom
value = (Dimension) style.getObjectProperty("padding-bottom");
if (value != null) {
this.paddingBottom = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.padding-horizontal
value = (Dimension) style.getObjectProperty("padding-horizontal");
if (value != null) {
this.paddingHorizontal = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
//#if polish.css.padding-vertical
value = (Dimension) style.getObjectProperty("padding-vertical");
if (value != null) {
this.paddingVertical = value.getValue(this.availableWidth);
// initializationRequired = true;
}
//#endif
// if (initializationRequired) {
// if (this.parent != null) {
// this.parent.isInitialized = false;
// } else if (this.screen != null) {
// this.screen.requestInit();
// }
// }
}
//#ifdef polish.css.before
String beforeUrlStr = style.getProperty("before");
if (beforeUrlStr != null) {
if ( !beforeUrlStr.equals(this.beforeUrl) ) {
try {
this.beforeImage = StyleSheet.getImage(beforeUrlStr, null, true );
this.beforeWidth = this.beforeImage.getWidth();
this.beforeHeight = this.beforeImage.getHeight();
} catch (IOException e) {
this.beforeUrl = null;
this.beforeImage = null;
this.beforeWidth = 0;
this.beforeHeight = 0;
}
}
this.beforeUrl = beforeUrlStr;
} else if (resetStyle) {
this.beforeImage = null;
this.beforeWidth = 0;
this.beforeHeight = 0;
this.beforeUrl = beforeUrlStr;
}
//#endif
//#ifdef polish.css.after
String afterUrlStr = style.getProperty("after");
if (afterUrlStr != null) {
if ( !afterUrlStr.equals(this.afterUrl) ) {
try {
this.afterImage = StyleSheet.getImage(afterUrlStr, null, true );
this.afterWidth = this.afterImage.getWidth();
this.afterHeight = this.afterImage.getHeight();
} catch (IOException e) {
this.afterUrl = null;
this.afterWidth = 0;
this.afterHeight = 0;
this.afterImage = null;
}
}
this.afterUrl = afterUrlStr;
} else if (resetStyle) {
this.afterWidth = 0;
this.afterHeight = 0;
this.afterImage = null;
this.afterUrl = afterUrlStr;
}
//#endif
//#ifdef polish.css.min-width
Dimension minWidthDim = (Dimension) style.getObjectProperty("min-width");
if (minWidthDim != null) {
this.minimumWidth = minWidthDim;
}
//#endif
//#ifdef polish.css.max-width
Dimension maxWidthDim = (Dimension) style.getObjectProperty("max-width");
if (maxWidthDim != null) {
this.maximumWidth = maxWidthDim;
}
//#endif
//#ifdef polish.css.width
Dimension widthDim = (Dimension) style.getObjectProperty("width");
if (widthDim != null) {
this.cssWidth = widthDim;
}
//#endif
//#ifdef polish.css.min-item-width
Dimension minItemWidthDim = (Dimension) style.getObjectProperty("min-item-width");
if (minItemWidthDim != null) {
this.minimumItemWidth = minItemWidthDim;
}
//#endif
//#ifdef polish.css.max-item-width
Dimension maxItemWidthDim = (Dimension) style.getObjectProperty("max-item-width");
if (maxItemWidthDim != null) {
this.maximumItemWidth = maxItemWidthDim;
}
//#endif
//#ifdef polish.css.min-height
Dimension minHeightDim = (Dimension) style.getObjectProperty("min-height");
if (minHeightDim != null) {
this.minimumHeight = minHeightDim;
}
//#endif
//#ifdef polish.css.max-height
Dimension maxHeightDim = (Dimension) style.getObjectProperty("max-height");
if (maxHeightDim != null) {
this.maximumHeight = maxHeightDim;
}
//#endif
//#ifdef polish.css.height
Dimension heightDim = (Dimension) style.getObjectProperty("height");
if (heightDim != null) {
this.cssHeight = heightDim;
}
//#endif
//#ifdef polish.css.min-item-height
Dimension minItemHeightDim = (Dimension) style.getObjectProperty("min-item-height");
if (minItemHeightDim != null) {
this.minimumItemHeight = minItemHeightDim;
}
//#endif
//#ifdef polish.css.max-item-height
Dimension maxItemHeightDim = (Dimension) style.getObjectProperty("max-item-height");
if (maxItemHeightDim != null) {
this.maximumItemHeight = maxItemHeightDim;
}
//#endif
//#if polish.css.colspan
Integer colSpanInt = style.getIntProperty("colspan");
if ( colSpanInt != null ) {
this.colSpan = colSpanInt.intValue();
}
//#endif
//#if polish.css.rowspan
Integer rowSpanInt = style.getIntProperty("rowspan");
if ( rowSpanInt != null ) {
this.rowSpan = rowSpanInt.intValue();
}
//#endif
//#if polish.css.include-label
Boolean includeLabelBool = style.getBooleanProperty("include-label");
if (includeLabelBool != null) {
this.includeLabel = includeLabelBool.booleanValue();
}
//#endif
//#if polish.css.complete-background || polish.css.complete-border
//#if polish.css.complete-background-padding
Dimension completeBackgroundPaddingDim = (Dimension) style.getObjectProperty("complete-background-padding");
if (completeBackgroundPaddingDim != null) {
this.completeBackgroundPadding = completeBackgroundPaddingDim;
}
//#endif
//#endif
//#if polish.css.opacity && polish.midp2
Dimension opacityInt = (Dimension) style.getObjectProperty("opacity");
if (opacityInt != null) {
this.opacity = opacityInt.getValue(255);
//System.out.println("Setting opacity to " + this.opacity + " for item " + this + " and style " + style.name);
} else if (!resetStyle && this.opacity != 255 && this.opacity != 0) {
// when an attribut is changed, you have to re-generate the opacity buffer:
this.opacityAtGeneration = this.opacity + 1;
}
//#endif
//#if polish.css.visible
Boolean visibleBool = style.getBooleanProperty("visible");
if (visibleBool != null) {
setVisible( visibleBool.booleanValue() );
}
//#endif
//#if polish.css.x-adjust
Dimension xInt = (Dimension) style.getObjectProperty("x-adjust");
if (xInt != null) {
this.xAdjustment = xInt;
}
//#endif
//#if polish.css.y-adjust
Dimension yInt = (Dimension) style.getObjectProperty("y-adjust");
if (yInt != null) {
this.yAdjustment = yInt;
//System.out.println("setStyle: got yAdjustment of " + yInt.getValue(100) );
}
//#endif
//#if polish.css.content-x-adjust
Dimension contentXInt = (Dimension) style.getObjectProperty("content-x-adjust");
if (contentXInt != null) {
this.contentXAdjustment = contentXInt;
}
//#endif
//#if polish.css.content-y-adjust
Dimension contentYInt = (Dimension) style.getObjectProperty("content-y-adjust");
if (contentYInt != null) {
this.contentYAdjustment = contentYInt;
}
//#endif
if (!resetStyle && isInitialized()) {
//#if polish.css.background-width
Dimension bgWidth = (Dimension) style.getObjectProperty("background-width");
if (bgWidth != null) {
this.backgroundWidth = bgWidth.getValue(this.originalBackgroundWidth);
}
//#endif
//#if polish.css.background-height
Dimension bgHeight = (Dimension) style.getObjectProperty("background-height");
if (bgHeight != null) {
this.backgroundHeight = bgHeight.getValue(this.originalBackgroundHeight);
}
//#endif
}
//#if polish.css.border-adjust
Dimension borderAdjustDim = (Dimension) style.getObjectProperty("border-adjust");
if (borderAdjustDim != null) {
this.borderAdjust = borderAdjustDim;
} else if (resetStyle) {
this.borderAdjust = null;
}
//#endif
//#if polish.css.filter && polish.midp2
if (this.filters != null) {
boolean isActive = false;
for (int i=0; i<this.filters.length; i++) {
RgbFilter filter = this.filters[i];
filter.setStyle(style, resetStyle);
isActive |= filter.isActive();
}
this.isFiltersActive = isActive;
this.filterRgbImage = null;
}
//#endif
//#if polish.css.animations
if (!resetStyle) {
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.setStyle(style, resetStyle);
}
//#endif
if (this.background != null) {
this.background.setStyle(style);
}
if (this.border != null) {
this.border.setStyle(style);
}
}
//#endif
}
/**
* Retrieves the complete width of this item.
* Note that the width can dynamically change,
* e.g. when a StringItem gets a new text.
*
* @param firstLineWidth the maximum width of the first line
* @param availWidth the maximum visible width of any following lines
* @return the complete width of this item.
*/
public int getItemWidth( int firstLineWidth, int availWidth) {
return getItemWidth(firstLineWidth, availWidth, this.availableHeight);
}
/**
* Retrieves the complete width of this item.
* Note that the width can dynamically change,
* e.g. when a StringItem gets a new text.
*
* @param firstLineWidth the maximum width of the first line
* @param availWidth the maximum visible width of any following lines
* @param availHeight the maximum visible height, -1 if unknown
* @return the complete width of this item.
*/
public int getItemWidth( int firstLineWidth, int availWidth, int availHeight ) {
if (!isInitialized() || this.availableWidth != availWidth || this.availableHeight != availHeight ) {
init( firstLineWidth, availWidth, availHeight );
}
return this.itemWidth;
}
/**
* Retrieves the complete height of this item.
* Note that the width can dynamically change,
* e.g. when a new style is set.
*
* @param firstLineWidth the maximum width of the first line
* @param availWidth the maximum visible width of any following lines
* @return the complete heigth of this item.
*/
public int getItemHeight( int firstLineWidth, int availWidth) {
return getItemHeight(firstLineWidth, availWidth, this.availableHeight);
}
/**
* Retrieves the complete height of this item.
* Note that the width can dynamically change,
* e.g. when a new style is set.
*
* @param firstLineWidth the maximum width of the first line
* @param availWidth the maximum visible width of any following lines
* @param availHeight the maximum visible height, -1 if unknown
* @return the complete heigth of this item.
*/
public int getItemHeight( int firstLineWidth, int availWidth, int availHeight ) {
if (!isInitialized() || this.availableWidth != availWidth || this.availableHeight != availHeight ) {
init( firstLineWidth, availWidth, availHeight );
}
return this.itemHeight;
}
//#if polish.LibraryBuild
/**
* Adds a command to this item
*
* @param cmd the command
*/
public void addCommand(javax.microedition.lcdui.Command cmd) {
// ignore
}
//#endif
/**
* Adds a context sensitive <code>Command</code> to the item.
* The semantic type of
* <code>Command</code> should be <code>ITEM</code>. The implementation
* will present the command
* only when the item is active, for example, highlighted.
* <p>
* If the added command is already in the item (tested by comparing the
* object references), the method has no effect. If the item is
* actually visible on the display, and this call affects the set of
* visible commands, the implementation should update the display as soon
* as it is feasible to do so.
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param cmd the command to be added
* @throws IllegalStateException if this Item is contained within an Alert
* @throws NullPointerException if cmd is null
* @since MIDP 2.0
*/
public void addCommand( Command cmd) {
addCommand( cmd, null );
}
/**
* Adds a context sensitive <code>Command</code> to the item.
* The semantic type of
* <code>Command</code> should be <code>ITEM</code>. The implementation
* will present the command
* only when the item is active, for example, highlighted.
* <p>
* If the added command is already in the item (tested by comparing the
* object references), the method has no effect. If the item is
* actually visible on the display, and this call affects the set of
* visible commands, the implementation should update the display as soon
* as it is feasible to do so.
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param cmd the command to be added
* @param commandStyle the style of the command, for the moment this is ignored
* @throws IllegalStateException if this Item is contained within an Alert
* @throws NullPointerException if cmd is null
* @since MIDP 2.0
*/
public void addCommand( Command cmd, Style commandStyle )
{
if (this.commands == null) {
this.commands = new ArrayList();
}
if (!this.commands.contains( cmd )) {
this.commands.add(cmd);
//#if tmp.invisible
if (this.isInvisible) {
if (this.invisibleAppearanceModeCache == PLAIN) {
this.invisibleAppearanceModeCache = HYPERLINK;
}
} else {
//#endif
if (this.appearanceMode == PLAIN) {
this.appearanceMode = HYPERLINK;
}
//#if tmp.invisible
}
//#endif
if (this.isFocused) {
showCommands();
// Screen scr = getScreen();
// if (scr != null) {
// scr.addCommand( cmd );
// }
}
//#if polish.Item.ShowCommandsOnHold
this.commandsContainer = null;
//#endif
if (this.isInitialized) {
repaint();
}
}
}
/**
* Removes the context sensitive command from item. If the command is not
* in the <code>Item</code> (tested by comparing the object references),
* the method has
* no effect. If the <code>Item</code> is actually visible on the display,
* and this call
* affects the set of visible commands, the implementation should update
* the display as soon as it is feasible to do so.
*
*
* If the command to be removed happens to be the default command,
* the command is removed and the default command on this Item is
* set to <code>null</code>.
*
* The following code:
* <CODE> <pre>
* // Command c is the default command on Item item
* item.removeCommand(c);
* </pre> </CODE>
* is equivalent to the following code:
* <CODE> <pre>
* // Command c is the default command on Item item
* item.setDefaultCommand(null);
* item.removeCommand(c);
* </pre> </CODE>
*
* @param cmd - the command to be removed
* @since MIDP 2.0
*/
public void removeCommand( Command cmd ) {
if (this.commands != null) {
if (cmd == this.defaultCommand) {
this.defaultCommand = null;
}
if (this.commands.remove(cmd)) {
if (this.isFocused) {
Screen scr = getScreen();
if (scr != null) {
scr.removeCommand( cmd );
}
}
//#if polish.Item.ShowCommandsOnHold
this.commandsContainer = null;
//#endif
if (this.isInitialized) {
repaint();
}
}
}
}
/**
* Repaints the complete screen to which this item belongs to.
* Subclasses can call this method whenever their contents
* have changed and they need an immediate refresh.
*
* @see #repaint()
* @see #repaint(int, int, int, int)
*/
protected void repaintFully() {
//repaint( this.relativeX, this.relativeY, this.itemWidth, this.itemHeight );
//if (this.parent instanceof Container) {
// ((Container) this.parent).isInitialized = false;
//}
Screen scr = getScreen();
if (scr != null && scr == StyleSheet.currentScreen) {
scr.requestRepaint();
}
}
/**
* Repaints the screen to which this item belongs to depending on the isInitialized field
* When this item is initialized, only the area covered by this item is repainted (unless other repaint requests are queued).
* When this item is not initialized (isInitialized == false), a repaint for the complete screen is triggered, as there might be
* a size change involved.
* Subclasses can call this method whenever their contents have changed and they need an immediate refresh.
*
* @see #isInitialized
* @see #repaintFully()
* @see #repaint(int, int, int, int)
*/
protected void repaint() {
if (this.ignoreRepaintRequests) {
return;
}
//#if tmp.invisible
if (this.isInvisible) {
return;
}
//#endif
//#if polish.Bugs.fullRepaintRequired
repaintFully();
//#else
//System.out.println("repaint(): " + this.relativeX + ", " + this.relativeY + ", " + this.itemWidth + ", " + this.itemHeight);
if (this.isInitialized) {
// note: -contentX, -contentY fails for right or center layouts
repaint( - (this.paddingLeft + this.marginLeft + getBorderWidthLeft()), -(this.paddingTop + this.marginTop + getBorderWidthTop()), this.itemWidth, this.itemHeight );
} else {
repaintFully();
}
//#endif
}
/**
* Retrieves the border width.
*
* @return the border for the left side in pixels
*/
protected int getBorderWidthLeft()
{
if (this.border != null) {
return this.border.borderWidthLeft;
}
if (this.background != null) {
return this.background.borderWidth;
}
return 0;
}
/**
* Retrieves the border width.
*
* @return the border for the right side in pixels
*/
protected int getBorderWidthRight()
{
if (this.border != null) {
return this.border.borderWidthRight;
}
if (this.background != null) {
return this.background.borderWidth;
}
return 0;
}
/**
* Retrieves the border width.
*
* @return the border for the top side in pixels
*/
protected int getBorderWidthTop()
{
if (this.border != null) {
return this.border.borderWidthTop;
}
if (this.background != null) {
return this.background.borderWidth;
}
return 0;
}
/**
* Retrieves the border width.
*
* @return the border for the bottom side in pixels
*/
protected int getBorderWidthBottom()
{
if (this.border != null) {
return this.border.borderWidthBottom;
}
if (this.background != null) {
return this.background.borderWidth;
}
return 0;
}
/**
* Repaints the specified relative area of this item.
* The area is specified relative to the <code>Item's</code>
* content area.
*
* @param relX horizontal start position relative to this item's content area
* @param relY vertical start position relative to this item's content area
* @param width the width of the area
* @param height the height of the area
*
* @see #repaint()
* @see #repaintFully()
*/
protected void repaint( int relX, int relY, int width, int height ) {
//System.out.println("repaint called by class " + getClass().getName() );
// if (this.parent instanceof Container) {
// ((Container) this.parent).isInitialized = false;
// }
Screen scr = getScreen();
// rickyn: Removed second test to correct dropped redraw requests for screens within a tabbedPane
if (scr != null/* && scr == StyleSheet.currentScreen*/) {
relX += getAbsoluteX(); // + this.contentX;
relY += getAbsoluteY(); // + this.contentY;
//System.out.println("item.repaint(" + relX + ", " + relY+ ", " + width + ", " + height + ") for " + this );
scr.requestRepaint( relX, relY, width, height + 1 );
}
}
/**
* Requests that this item and all its parents are to be re-initialised, if the size of this item has been changed.
* All parents of this item are notified, too.
* This method should be called when an item changes its size more than usual.
*/
public void requestInit() {
if (this.isInitialized) {
setInitialized(false);
Item p = this.parent;
while ( p != null) {
p.setInitialized( false );
p = p.parent;
}
Screen scr = getScreen();
if (scr != null) {
scr.requestInit();
}
if (this.isShown) {
repaint();
}
}
}
/**
* Retrieves the screen to which this item belongs to.
*
* @return either the corresponding screen or null when no screen could be found
*/
public Screen getScreen() {
Item p = this;
while (p != null) {
if (p.screen != null) {
return p.screen;
}
p = p.parent;
}
return null;
}
/**
* Sets a listener for <code>Commands</code> to this <code>Item</code>,
* replacing any previous
* <code>ItemCommandListener</code>. A <code>null</code> reference
* is allowed and has the effect of removing any existing listener.
*
* When no listener is registered, J2ME Polish notifies the
* command-listener of the current screen, when an item command
* has been selected.
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param l the new listener, or null.
* @throws IllegalStateException if this Item is contained within an Alert
* @since MIDP 2.0
*/
public void setItemCommandListener( ItemCommandListener l)
{
this.itemCommandListener = l;
}
//#if polish.LibraryBuild
/**
* Sets a listener for <code>Commands</code> to this <code>Item</code>,
* replacing any previous
* <code>ItemCommandListener</code>. A <code>null</code> reference
* is allowed and has the effect of removing any existing listener.
*
* When no listener is registered, J2ME Polish notifies the
* command-listener of the current screen, when an item command
* has been selected.
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param l the new listener, or null.
* @throws IllegalStateException if this Item is contained within an Alert
* @since MIDP 2.0
*/
public void setItemCommandListener( javax.microedition.lcdui.ItemCommandListener l)
{
// ignore
}
//#endif
/**
* Gets the listener for <code>Commands</code> to this <code>Item</code>.
*
* When no listener is registered, null is returned
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @return the ItemCommandListener associated with this item
*/
public ItemCommandListener getItemCommandListener()
{
return this.itemCommandListener;
}
/**
* Sets an ItemStateListener specifically for this item.
* Change events are forwarded to both this listener as well as a possibly set listener of the
* corresponding screen.
*
* @param listener the listener which is set specifically for this item.
*/
public void setItemStateListener(ItemStateListener listener ) {
this.itemStateListener = listener;
}
/**
* Gets an ItemStateListener specifically for this item.
* Change events are forwarded to both this listener as well as a possibly set listener of the
* corresponding screen.
*
* @return the listener which has been set specifically for this item.
*/
public ItemStateListener getItemStateListener() {
return this.itemStateListener;
}
/**
* Gets the preferred width of this <code>Item</code>.
* If the application has locked
* the width to a specific value, this method returns that value.
* Otherwise, the return value is computed based on the
* <code>Item's</code> contents,
* possibly with respect to the <code>Item's</code> preferred height
* if it is locked.
* See <a href="#sizes">Item Sizes</a> for a complete discussion.
*
* @return the preferred width of the Item
* @see #getpreferredHeight()
* @see #setpreferredSize(int, int)
* @since MIDP 2.0
*/
public int getpreferredWidth()
{
return this.preferredWidth;
}
/**
* Gets the preferred height of this <code>Item</code>.
* If the application has locked
* the height to a specific value, this method returns that value.
* Otherwise, the return value is computed based on the
* <code>Item's</code> contents,
* possibly with respect to the <code>Item's</code> preferred
* width if it is locked.
* See <a href="#sizes">Item Sizes</a> for a complete discussion.
*
* @return the preferred height of the Item
* @see #getpreferredWidth()
* @see #setpreferredSize(int, int)
* @since MIDP 2.0
*/
public int getpreferredHeight()
{
return this.preferredHeight;
}
/**
* Sets the preferred width and height for this <code>Item</code>.
* Values for width and height less than <code>-1</code> are illegal.
* If the width is between zero and the minimum width, inclusive,
* the minimum width is used instead.
* If the height is between zero and the minimum height, inclusive,
* the minimum height is used instead.
*
* <p>Supplying a width or height value greater than the minimum width or
* height <em>locks</em> that dimension to the supplied
* value. The implementation may silently enforce a maximum dimension for
* an <code>Item</code> based on factors such as the screen size.
* Supplying a value of
* <code>-1</code> for the width or height unlocks that dimension.
* See <a href="#sizes">Item Sizes</a> for a complete discussion.</p>
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param width - the value to which the width should be locked, or -1 to unlock
* @param height - the value to which the height should be locked, or -1 to unlock
* @throws IllegalArgumentException - if width or height is less than -1
* @throws IllegalStateException - if this Item is contained within an Alert
* @see #getpreferredHeight()
* @see #getpreferredWidth()
* @since MIDP 2.0
*/
public void setpreferredSize(int width, int height)
{
this.preferredHeight = height;
this.preferredWidth = width;
}
/**
* Gets the minimum width for this <code>Item</code>. This is a width
* at which the item can function and display its contents,
* though perhaps not optimally.
* See <a href="#sizes">Item Sizes</a> for a complete discussion.
*
* @return the minimum width of the item
* @since MIDP 2.0
*/
public int getMinimumWidth()
{
return getMinimumWidth(100);
}
/**
* Gets the minimum width for this <code>Item</code>.
*
* @param availWidth the available width for percentage calculations
* @return the minimum width of the item
* @since MIDP 2.0
*/
public int getMinimumWidth(int availWidth) {
if (this.minimumWidth != null) {
return this.minimumWidth.getValue(availWidth);
} else {
return 0;
}
}
/**
* Gets the minimum height for this <code>Item</code>. This is a height
* at which the item can function and display its contents,
* though perhaps not optimally.
* See <a href="#sizes">Item Sizes</a> for a complete discussion.
*
* @return the minimum height of the item
* @since MIDP 2.0
*/
public int getMinimumHeight()
{
return getMinimumHeight(100);
}
/**
* Gets the minimum height for this <code>Item</code>.
*
* @param availHeight the available height for percentage calculations
* @return the minimum height of the item
* @since MIDP 2.0
*/
public int getMinimumHeight(int availHeight)
{
if (this.minimumHeight != null) {
return this.minimumHeight.getValue(availHeight);
} else {
return 0;
}
}
//#if polish.css.max-width
/**
* Gets the maximum width for this <code>Item</code>. This is a height
* at which the item can function and display its contents,
* though perhaps not optimally.
* See <a href="#sizes">Item Sizes</a> for a complete discussion.
*
* @return the minimum height of the item
* @since MIDP 2.0
*/
public int getMaximumWidth()
{
return getMaximumWidth(100);
}
/**
* Gets the maximum width for this <code>Item</code>.
*
* @param availWidth the available height for percentage calculations
* @return the minimum height of the item
* @since MIDP 2.0
*/
public int getMaximumWidth(int availWidth)
{
if (this.maximumWidth != null) {
return this.maximumWidth.getValue(availWidth);
} else {
return 0;
}
}
//#endif
//#if polish.css.max-height
/**
* Gets the maximum height for this <code>Item</code>. This is a height
* at which the item can function and display its contents,
* though perhaps not optimally.
* See <a href="#sizes">Item Sizes</a> for a complete discussion.
*
* @return the minimum height of the item
* @since MIDP 2.0
*/
public int getMaximumHeight()
{
return getMaximumHeight(100);
}
/**
* Gets the maximum height for this <code>Item</code>.
*
* @param availHeight the available height for percentage calculations
* @return the minimum height of the item
* @since MIDP 2.0
*/
public int getMaximumHeight(int availHeight)
{
if (this.maximumHeight != null) {
return this.maximumHeight.getValue(availHeight);
} else {
return 0;
}
}
//#endif
/**
* Sets default <code>Command</code> for this <code>Item</code>.
* If the <code>Item</code> previously had a
* default <code>Command</code>, that <code>Command</code>
* is no longer the default, but it
* remains present on the <code>Item</code>.
*
* <p>If not <code>null</code>, the <code>Command</code> object
* passed becomes the default <code>Command</code>
* for this <code>Item</code>. If the <code>Command</code> object
* passed is not currently present
* on this <code>Item</code>, it is added as if <A HREF="../../../javax/microedition/lcdui/Item.html#addCommand(javax.microedition.lcdui.Command)"><CODE>addCommand(javax.microedition.lcdui.Command)</CODE></A>
* had been called
* before it is made the default <code>Command</code>, unless the "polish.Item.suppressDefaultCommand" preprocessing variable is set to "true".</p>
*
* <p>If <code>null</code> is passed, the <code>Item</code> is set to
* have no default <code>Command</code>.
* The previous default <code>Command</code>, if any, remains present
* on the <code>Item</code>.
* </p>
*
* <p>It is illegal to call this method if this <code>Item</code>
* is contained within an <code>Alert</code>.</p>
*
* @param cmd the command to be used as this Item's default Command, or null if there is to be no default command
* @throws IllegalStateException - if this Item is contained within an Alert
* @since MIDP 2.0
*/
public void setDefaultCommand( Command cmd)
{
//#debug
System.out.println("set default command " + cmd.getLabel() + " for " + this);
//#if !polish.Item.suppressDefaultCommand
if (this.defaultCommand != null && cmd != this.defaultCommand) {
addCommand(this.defaultCommand);
}
//#endif
this.defaultCommand = cmd;
//#if !polish.Item.suppressDefaultCommand
if (cmd != null) {
addCommand(cmd);
}
//#else
if (cmd != null && this.appearanceMode == PLAIN) {
this.appearanceMode = INTERACTIVE;
}
//#endif
if (this.isFocused)
{
Screen scr = getScreen();
if(scr != null)
scr.notifyDefaultCommand( cmd );
}
}
//#if polish.LibraryBuild
/**
* Sets default <code>Command</code> for this <code>Item</code>.
* @param cmd the command to be used as this Item's default Command, or null if there is to be no default command
*/
public void setDefaultCommand( javax.microedition.lcdui.Command cmd)
{
// ignore
}
//#endif
/**
* Causes this <code>Item's</code> containing <code>Form</code> to notify
* the <code>Item's</code> <CODE>ItemStateListener</CODE>.
* The application calls this method to inform the
* listener on the <code>Item</code> that the <code>Item's</code>
* state has been changed in
* response to an action. Even though this method simply causes a call
* to another part of the application, this mechanism is useful for
* decoupling the implementation of an <code>Item</code> (in particular, the
* implementation of a <code>CustomItem</code>, though this also applies to
* subclasses of other items) from the consumer of the item.
*
* <p>If an edit was performed by invoking a separate screen, and the
* editor now wishes to "return" to the form which contained the
* selected <code>Item</code>, the preferred method is
* <code>Display.setCurrent(Item)</code>
* instead of <code>Display.setCurrent(Displayable)</code>,
* because it allows the
* <code>Form</code> to restore focus to the <code>Item</code>
* that initially invoked the editor.</p>
*
* <p>In order to make sure that the documented behavior of
* <code>ItemStateListener</code> is maintained, it is up to the caller
* (application) to guarantee that this function is
* not called unless:</p>
*
* <ul>
* <li>the <code>Item's</code> value has actually been changed, and</li>
* <li>the change was the result of a user action (an "edit")
* and NOT as a result of state change via calls to
* <code>Item's</code> APIs </li>
* </ul>
*
* <p>The call to <code>ItemStateListener.itemStateChanged</code>
* may be delayed in order to be serialized with the event stream.
* The <code>notifyStateChanged</code> method does not block awaiting
* the completion of the <code>itemStateChanged</code> method.</p>
*
* @throws IllegalStateException if the Item is not owned by a Form
* @since MIDP 2.0
*/
public void notifyStateChanged()
{
if (this.itemStateListener != null) {
try {
this.itemStateListener.itemStateChanged( this );
return;
} catch (Exception e) {
//#debug error
System.out.println("Unable to forward ItemStateChanged event to listener " + this.itemStateListener + e );
}
}
Screen scr = StyleSheet.currentScreen;
if (scr == null) {
scr = getScreen();
}
if (scr != null) {
scr.notifyStateListener(this);
}
}
/**
* Notifies this item about a change event, e.g. when the text of a StringItem has been changed or similar.
* In contrast to notifyStateChanged() this method is also called when the change is not user initiated, i.e. when
* the application itself changes the value.
* The default implementation notfies native UI items about the change and fires an Event when either CSS animations are used
* or when the preprocessing variable <code>polish.handleEvents</code> is set to <code>true</code>.
* @param newValue the changed value of this object
* @see #notifyStateChanged()
*/
protected void notifyValueChanged(Object newValue) {
//#if polish.useNativeGui
if (this.nativeItem != null) {
this.nativeItem.notifyValueChanged(this, newValue);
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_VALUE_CHANGE, this, newValue);
//#endif
}
void setAvailableDimensions(int leftBorder, int rightBorder)
{
int w = rightBorder - leftBorder;
int h = 0;
Item p = this.parent;
if (p != null) {
while (p != null && (w < 1 || h < 1)) {
if (p.contentWidth != 0) {
if (h < 1) {
h = Math.min( p.contentHeight, p.availableHeight );
}
if (w < 1) {
w = Math.min( p.contentWidth, p.availableWidth );
}
} else {
if (h < 1) {
h = p.availableHeight;
}
if (w < 1) {
w = p.availableWidth;
}
}
p = p.parent;
}
} else {
Screen scr = getScreen();
if (scr != null){
h = scr.contentHeight;
if (w < 1) {
w = scr.contentWidth;
}
}
}
this.availableWidth = w;
this.availableHeight = h;
}
/**
* Paints this item on the screen.
* This method should normally not be overriden. Override it
* only when you know what you are doing!
*
* @param x the left start position of this item.
* @param y the top start position of this item.
* @param leftBorder the left border, nothing must be painted left of this position
* @param rightBorder the right border, nothing must be painted right of this position,
* rightBorder > x >= leftBorder
* @param g the Graphics on which this item should be painted.
*/
public void paint( int x, int y, int leftBorder, int rightBorder, Graphics g ) {
//#if tmp.invisible
if (this.isInvisible) {
return;
}
//#endif
// Item p = this.parent; xxx
// String start = "";
// while (p != null) {
// start += " ";
// p = p.parent;
// }
// System.out.println(start + "paint at x=" + x + ", contentX=" + this.contentX + ", leftBorder=" + leftBorder +", rightBorder=" + rightBorder + " of " + this);
//#debug ovidiu
Benchmark.startSmartTimer("0");
// initialise this item if necessary:
if (!this.isInitialized) {
if (this.availableWidth == 0) {
setAvailableDimensions(leftBorder, rightBorder);
}
int previousItemWidth = this.itemWidth;
int previousItemHeight = this.itemHeight;
init(this.availableWidth, this.availableWidth, this.availableHeight);
if (this.itemHeight < previousItemHeight && this.isLayoutVerticalExpand()) {
setItemHeight( previousItemHeight );
}
if ((previousItemWidth != this.itemWidth || previousItemHeight != this.itemHeight) && this.parent != null)
{
this.parent.requestInit();
}
}
//#if polish.css.x-adjust
if (this.xAdjustment != null) {
int value = this.xAdjustment.getValue(this.itemWidth);
x += value;
leftBorder += value;
rightBorder += value;
}
//#endif
//#if polish.css.y-adjust
if (this.yAdjustment != null) {
y += this.yAdjustment.getValue(this.itemHeight);
}
//#endif
int origX = x;
int origY = y;
//#if polish.css.filter && polish.midp2
if (this.isFiltersActive && this.filters != null && !this.filterPaintNormally) {
RgbImage rgbImage = this.filterRgbImage;
// Do not use the cached item image.
// Used for real-time dynamic objects
// suct as ProcessingItem
if ( !this.cacheItemImage )
{
rgbImage = null ;
}
if ( (rgbImage == null) ) {
this.filterPaintNormally = true;
int[] rgbData = UiAccess.getRgbData( this );
rgbImage = new RgbImage( rgbData, this.itemWidth);
this.filterRgbImage = rgbImage;
this.filterPaintNormally = false;
}
//System.out.println("painting RGB data for " + this + ", pixel=" + Integer.toHexString( rgbData[ rgbData.length / 2 ]));
this.filterProcessedRgbImage = paintFilter(x, y, this.filters, rgbImage, this.layout, g);
if ( (this.filterProcessedRgbImage.getWidth() != this.itemWidth ) || ( this.filterProcessedRgbImage.getHeight() != this.itemHeight) )
{
repaint(0, 0, this.filterProcessedRgbImage.getWidth(), this.filterProcessedRgbImage.getHeight());
}
// for (int i=0; i<this.filters.length; i++) {
// RgbFilter filter = this.filters[i];
// rgbImage = filter.process(rgbImage);
// }
//
// int width = rgbImage.getWidth();
// int height = rgbImage.getHeight();
// int[] rgbData = rgbImage.getRgbData();
// if (this.isLayoutRight) {
// x = rightBorder - width;
// } else if (this.isLayoutCenter) {
// x = leftBorder + ((rightBorder - leftBorder)/2) - (width/2);
// }
// DrawUtil.drawRgb(rgbData, x, y, width, height, true, g );
//
//#mdebug ovidiu
Benchmark.pauseSmartTimer("0");
Benchmark.incrementSmartTimer("1");
Benchmark.check();
//#enddebug
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
paintCommands( origX, origY, g );
}
//#endif
return;
}
//#endif
//#if polish.css.opacity && polish.midp2
if (this.opacity != 255 && !this.opacityPaintNormally) {
if (this.opacity == 0) {
return;
}
int[] rgbData = this.opacityRgbData;
if ( rgbData == null || this.opacity != this.opacityAtGeneration ) {
this.opacityPaintNormally = true;
rgbData = UiAccess.getRgbData( this, this.opacity );
this.opacityRgbData = rgbData;
this.opacityPaintNormally = false;
this.opacityAtGeneration = this.opacity;
}
//System.out.println("painting RGB data for " + this + ", pixel=" + Integer.toHexString( rgbData[ rgbData.length / 2 ]));
DrawUtil.drawRgb(rgbData, x, y, this.itemWidth, this.itemHeight, true, g );
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
paintCommands( origX, origY, g );
}
//#endif
return;
}
//#endif
//boolean isLayoutShrink = (this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK;
// paint background and border when the label should be included in this:
//#if polish.css.include-label
if (this.includeLabel) {
int width = this.itemWidth - this.marginLeft - this.marginRight;
int height = this.itemHeight - this.marginTop - this.marginBottom;
int bX = x + this.marginLeft;
int bY = y + this.marginTop + this.backgroundYOffset;
paintBackgroundAndBorder( bX, bY, width, height, g );
}
//#endif
//#if polish.css.complete-background || polish.css.complete-border
int cbPadding = this.completeBackground == null ? 0 : this.completeBackgroundPadding.getValue(this.availContentWidth);
int width = this.itemWidth - this.marginLeft - this.marginRight + (cbPadding << 1);
int height = this.itemHeight - this.marginTop - this.marginBottom + (cbPadding << 1);
int bX = x + this.marginLeft - cbPadding;
int bY = y + this.marginTop + this.backgroundYOffset - cbPadding;
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.paint(bX, bY, width, height, g);
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder!= null) {
this.completeBorder.paint(bX, bY, width, height, g);
}
//#endif
//#endif
// paint label:
StringItem labelItem = this.label;
if (labelItem != null) {
int labelX = x + labelItem.relativeX;
labelItem.paint(labelX, y + labelItem.relativeY, labelX, labelX + labelItem.itemWidth, g );
if (this.useSingleRow) {
leftBorder += labelItem.itemWidth;
} else {
y += labelItem.itemHeight;
}
}
leftBorder += (this.marginLeft + getBorderWidthLeft() + this.paddingLeft);
//#ifdef polish.css.before
leftBorder += getBeforeWidthWithPadding();
//#endif
//System.out.println( this.style.name + ": increasing leftBorder by " + (this.marginLeft + this.borderWidth + this.paddingLeft));
rightBorder -= (this.marginRight + getBorderWidthRight() + this.paddingRight);
//#ifdef polish.css.after
rightBorder -= getAfterWidthWithPadding();
//#endif
//System.out.println( this.style.name + ": decreasing rightBorder by " + (this.marginRight + this.borderWidth + this.paddingRight));
// if ( this.isLayoutCenter && availWidth > this.itemWidth) {
// int difference = (availWidth - this.itemWidth) >> 1;
// System.out.println("increasing x from " + x + " to " + (x + difference) + ", availableWidth=" + this.availableWidth + ", availWidth=" + availWidth + ", itemWidth=" + this.itemWidth);
// x += difference;
// if (!this.isLayoutExpand) {
// leftBorder += difference;
// rightBorder -= difference;
// //System.out.println("item " + this + ": (center) shrinking left border to " + leftBorder + ", right border to " + rightBorder);
// }
// } else if ( this.isLayoutRight && availWidth > this.itemWidth) {
// // adjust the x-position so that the item is painted up to
// // the right border (when it starts at x):
// x += availWidth - this.itemWidth;
// if (!this.isLayoutExpand) {
// leftBorder += availWidth - this.itemWidth;
// //System.out.println("item " + this + ": (right) shrinking left border to " + leftBorder);
// }
// } else if (isLayoutShrink && availWidth > this.itemWidth) {
// rightBorder -= availWidth - this.itemWidth;
// //System.out.println("item " + this + ": (left) shrinking right border to " + rightBorder);
// }
x += this.marginLeft;
y += this.marginTop;
// paint background and border:
//#if polish.css.include-label
if (!this.includeLabel) {
//#endif
int backgroundX = x;
if (labelItem != null && this.useSingleRow) {
backgroundX += labelItem.itemWidth;
}
paintBackgroundAndBorder(backgroundX, y, this.backgroundWidth, this.backgroundHeight, g);
//#if polish.css.include-label
}
//#endif
//#if polish.css.content-x-adjust
if (this.contentXAdjustment != null) {
x += this.contentXAdjustment.getValue(this.contentWidth);
}
//#endif
//#if polish.css.content-y-adjust
if (this.contentYAdjustment != null) {
y += this.contentYAdjustment.getValue(this.contentHeight);
}
//#endif
x += this.contentX - this.marginLeft; //getBorderWidthLeft() + this.paddingLeft;
y += this.contentY - this.marginTop; //getBorderWidthTop() + this.paddingTop;
if (labelItem != null && !this.useSingleRow) {
y -= labelItem.itemHeight;
}
int originalContentY = y;
// paint before element:
//#if polish.css.before || polish.css.after || polish.css.min-height || polish.css.max-height
boolean isVerticalCenter = (this.layout & LAYOUT_VCENTER) == LAYOUT_VCENTER;
boolean isTop = !isVerticalCenter && (this.layout & LAYOUT_TOP) == LAYOUT_TOP;
boolean isBottom = !isVerticalCenter && (this.layout & LAYOUT_BOTTOM) == LAYOUT_BOTTOM;
//#endif
//#ifdef polish.css.before
if (this.beforeImage != null) {
int beforeX = origX + getBorderWidthLeft() + this.paddingLeft + this.marginLeft;
if (labelItem != null && this.useSingleRow) {
beforeX += labelItem.itemWidth;
}
int beforeY = y;
int yAdjust = this.beforeHeight - this.contentHeight;
if ( this.beforeHeight < this.contentHeight) {
if (isTop) {
//beforeY -= yAdjust;
} else if (isBottom) {
beforeY += yAdjust;
} else {
beforeY -= (yAdjust >> 1);
}
} else {
if (isTop) {
// keep contY
} else if (isBottom) {
y += yAdjust;
} else {
y += (yAdjust >> 1);
}
//contY += (this.beforeHeight - this.contentHeight) / 2;
}
if(this.isLayoutRight)
{
beforeX = rightBorder - (this.contentWidth + this.beforeWidth);
}
//System.out.println("drawing before at " + beforeX + ", contentX=" + this.contentX + ", this=" + this);
g.drawImage(this.beforeImage, beforeX, beforeY, Graphics.TOP | Graphics.LEFT );
x += getBeforeWidthWithPadding();
}
//#endif
// paint after element:
//#ifdef polish.css.after
if (this.afterImage != null) {
int afterY = originalContentY;
int yAdjust = this.afterHeight - this.contentHeight;
if ( this.afterHeight < this.contentHeight) {
if (isTop) {
afterY -= yAdjust;
} else if (isBottom) {
afterY += yAdjust;
} else {
afterY -= (yAdjust >> 1);
}
//afterY += (this.contentHeight - this.afterHeight) / 2;
} else {
//#ifdef polish.css.before
if (this.afterHeight > this.beforeHeight) {
//#endif
if (isTop) {
// keep contY
} else if (isBottom) {
y = originalContentY + yAdjust;
} else {
y = originalContentY + (yAdjust >> 1);
}
//contY = originalContentY + (this.afterHeight - this.contentHeight) / 2;
//#ifdef polish.css.before
}
//#endif
}
g.drawImage(this.afterImage, rightBorder + this.paddingHorizontal, afterY, Graphics.TOP | Graphics.LEFT );
}
//#endif
//#if polish.css.content-visible
if (!this.isContentVisible) {
this.contentWidth = 0;
this.contentHeight = 0;
} else {
//#endif
// paint content:
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.paintContent( this, x, y, leftBorder, rightBorder, g);
} else {
//#endif
paintContent( x, y, leftBorder, rightBorder, g );
//#ifdef polish.css.view-type
}
//#endif
//#if polish.css.content-visible
}
//#endif
// if (this.parent != null) {
// g.setColor(0x00ff00);
// g.drawRect( this.parent.getAbsoluteX() + this.parent.contentX + this.relativeX, this.parent.getAbsoluteY() + this.parent.contentY + this.relativeY, this.itemWidth, this.itemHeight);
// }
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
paintCommands( origX, origY, g );
}
//#endif
// g.setColor(0xff0000);
// g.drawRect( origX + this.contentX, origY + this.contentY, this.contentWidth, this.contentHeight );
// g.drawLine( origX + this.contentX, origY + this.contentY, origX + this.contentX + this.contentWidth, origY + this.contentY + this.contentHeight );
// g.setColor(0xffFF00);
// g.drawRect( getAbsoluteX() + 1, getAbsoluteY() + 1, this.itemWidth - 2, this.itemHeight - 2);
}
/**
* Paints the commands for this item after the user has pressed/clicked on an item for a long time.
* Note that the preproessing variable polish.Item.ShowCommandsOnHold needs to be set to true for this feature.
*
* @param x horizontal left start position
* @param y vertical top start position
* @param g the graphics context
*/
protected void paintCommands(int x, int y, Graphics g) {
//#if polish.Item.ShowCommandsOnHold
if (this.commandsContainer == null) {
//#style itemcommands?
this.commandsContainer = new Container(true);
this.commandsContainer.parent = this;
//#if polish.css.commands-style
if (this.style != null) {
Style commandsStyle = (Style) this.style.getObjectProperty("commands-style");
if (commandsStyle != null) {
this.commandsContainer.setStyle( commandsStyle );
}
}
//#endif
//#if polish.css.child-style
Style childStyle = null;
if (this.commandsContainer.style != null) {
childStyle = (Style) this.commandsContainer.style.getObjectProperty("child-style");
}
//#endif
Object[] commandsArr = this.commands.getInternalArray();
for (int i = 0; i < commandsArr.length; i++) {
Command cmd = (Command) commandsArr[i];
if (cmd == null) {
break;
}
CommandItem item = new CommandItem( cmd, this
//#if polish.css.child-style
, childStyle
//#endif
);
this.commandsContainer.add(item);
}
this.commandsContainer.init( this.availableWidth, this.availableWidth, this.availableHeight );
int relX = 0;
if (this.commandsContainer.isLayoutRight()) {
relX = this.availableWidth - this.commandsContainer.itemWidth;
} else if (this.commandsContainer.isLayoutCenter()) {
relX = (this.availableWidth - this.commandsContainer.itemWidth)/2;
}
this.commandsContainer.relativeX = relX;
int relY = this.itemHeight;
if (this.commandsContainer.isLayoutTop()) {
relY = - this.commandsContainer.itemHeight;
} else if (this.commandsContainer.isLayoutVerticalCenter()) {
relY = (this.itemHeight - this.commandsContainer.itemHeight)/2;
}
int absY = getAbsoluteY();
Screen scr = getScreen();
int contY = scr.getScreenContentY();
if (absY + relY < contY) {
relY = contY - absY;
} else if (absY + relY + this.commandsContainer.itemHeight > contY + scr.getScreenContentHeight()) {
relY = contY + scr.getScreenContentHeight() - absY - this.commandsContainer.itemHeight;
}
this.commandsContainer.relativeY = relY;
}
x += this.commandsContainer.relativeX;
this.commandsContainer.paint(x, y + this.commandsContainer.relativeY, x, x + this.commandsContainer.itemWidth, g);
//#endif
}
/**
* Paints the background and border of this item.
* The call is forwarded to paintBackground() and paintBorder().
*
* @param x the horizontal start position
* @param y the vertical start position
* @param width the width
* @param height the height
* @param g graphics context
* @see #paintBackground(int, int, int, int, Graphics)
* @see #paintBorder(int, int, int, int, Graphics)
*/
protected void paintBackgroundAndBorder(int x, int y, int width, int height, Graphics g) {
//#if polish.css.background-anchor && (polish.css.background-width || polish.css.background-height)
if (this.backgroundAnchor != 0) {
//#if polish.css.background-width
if (width != this.originalBackgroundWidth) {
if ((Graphics.HCENTER & this.backgroundAnchor) == Graphics.HCENTER) {
x += (this.originalBackgroundWidth - width) / 2;
} else if ((Graphics.RIGHT & this.backgroundAnchor) == Graphics.RIGHT) {
x += (this.originalBackgroundWidth - width);
}
}
//#endif
//#if polish.css.background-height
if (height != this.originalBackgroundHeight) {
if ((Graphics.VCENTER & this.backgroundAnchor) == Graphics.VCENTER) {
y += (this.originalBackgroundHeight - height) / 2;
} else if ((Graphics.BOTTOM & this.backgroundAnchor) == Graphics.BOTTOM) {
y += (this.originalBackgroundHeight - height);
}
}
//#endif
}
//#endif
if ( this.background != null ) {
int bWidthL = 0;
int bWidthR = 0;
int bWidthT = 0;
int bWidthB = 0;
if ( this.border != null ) {
bWidthL = getBorderWidthLeft();
bWidthR = getBorderWidthRight();
bWidthT = getBorderWidthTop();
bWidthB = getBorderWidthBottom();
x += bWidthL;
y += bWidthT;
width -= bWidthL + bWidthR;
height -= bWidthT + bWidthB;
}
paintBackground(x, y, width, height, g);
if (this.border != null) {
x -= bWidthL;
y -= bWidthT;
width += bWidthL + bWidthR;
height += bWidthT + bWidthB;
}
}
if ( this.border != null ) {
paintBorder( x, y, width, height, g );
}
}
/**
* Paints the border of this item.
*
* @param x the horizontal start position
* @param y the vertical start position
* @param width the width
* @param height the height
* @param g graphics context
*/
protected void paintBorder(int x, int y, int width, int height, Graphics g)
{
//#if polish.css.border-adjust
if (this.borderAdjust != null) {
int adjust = this.borderAdjust.getValue(this.availableWidth);
x += adjust;
y += adjust;
adjust <<= 1;
width -= adjust;
height -= adjust;
}
//#endif
//#if polish.css.view-type
if (this.view != null) {
this.view.paintBorder( this.border, x, y, width, height, g );
} else {
//#endif
this.border.paint(x, y, width, height, g);
//#if polish.css.view-type
}
//#endif
}
/**
* Paints the background and - if defined - the bgborder of this item.
*
* @param x the horizontal start position
* @param y the vertical start position
* @param width the width
* @param height the height
* @param g graphics context
*/
protected void paintBackground( int x, int y, int width, int height, Graphics g ) {
//#if polish.css.bgborder
if (this.bgBorder != null) {
int bgX = x - this.bgBorder.borderWidthLeft;
int bgW = width + this.bgBorder.borderWidthLeft + this.bgBorder.borderWidthRight;
int bgY = y - this.bgBorder.borderWidthTop;
int bgH = height + this.bgBorder.borderWidthTop + this.bgBorder.borderWidthBottom;
//#if polish.css.view-type
if (this.view != null) {
this.view.paintBorder( this.bgBorder, bgX, bgY, bgW, bgH, g );
} else {
//#endif
this.bgBorder.paint(bgX, bgY, bgW, bgH, g);
//#if polish.css.view-type
}
//#endif
}
//#endif
//#if polish.css.view-type
if (this.view != null) {
this.view.paintBackground( this.background, x, y, width, height, g );
} else {
//#endif
this.background.paint(x, y, width, height, g);
//#if polish.css.view-type
}
//#endif
}
/**
* Paints the given filters and retrieves the last processed RGB image.
* @param x horizontal paint position
* @param y vertical paint position
* @param partFilters the filters
* @param rgbImage the initial RGB image
* @param lo the layout for the processed RGB image
* @param g the graphics context
* @return the processed RGB image
*/
protected RgbImage paintFilter(int x, int y, RgbFilter[] partFilters, RgbImage rgbImage, int lo, Graphics g) {
//System.out.println("painting RGB data for " + this + ", pixel=" + Integer.toHexString( rgbData[ rgbData.length / 2 ]));
int origWidth = rgbImage.getWidth();
int origHeight = rgbImage.getHeight();
for (int i=0; i<partFilters.length; i++) {
RgbFilter filter = partFilters[i];
rgbImage = filter.process(rgbImage);
}
int width = rgbImage.getWidth();
int height = rgbImage.getHeight();
//System.out.println("Changed dimension from " + this.imageWidth +"x" + this.imageHeight + " to " + width + "x" + height);
int[] rgb = rgbImage.getRgbData();
if (origWidth != width) {
if ((lo & LAYOUT_CENTER) == LAYOUT_CENTER) {
x -= (width - origWidth) / 2;
} else if ((lo & LAYOUT_CENTER) == LAYOUT_RIGHT) {
x -= (width - origWidth);
}
}
if (origHeight != height) {
if ((lo & LAYOUT_VCENTER) == LAYOUT_VCENTER) {
y -= (height - origHeight) / 2;
} else if ((lo & LAYOUT_VCENTER) == LAYOUT_TOP) {
y -= (height - origHeight);
}
}
DrawUtil.drawRgb(rgb, x , y, width, height, true, g );
return rgbImage;
}
/**
* Initialises this item.
* You should always call super.init( firstLineWidth, lineWidth) when overriding this method.
* This method call either ItemView.initContent() or Item.initContent() to initialize the actual content.
* A valid case for overriding would be if additional initialization needs to be done even when an
* ItemView is associated with this Item. Usually implementing initContent() should suffice.
*
* @param firstLineWidth the maximum width of the first line
* @param availWidth the maximum width of any following lines
* @param availHeight the maximum height that can be used without scrolling
* @see #initContent(int, int, int)
* @see ItemView#initContent(Item, int, int, int)
*/
protected void init( int firstLineWidth, int availWidth, int availHeight ) {
//#debug
System.out.println("initialising item " + this + " with availWidth " + firstLineWidth + "/" + availWidth + ", height " + availHeight + " (was: " + this.availableWidth + ", " + this.availableHeight + ")" );
this.availableWidth = availWidth;
this.availableHeight = availHeight;
//#if tmp.invisible
if (this.isInvisible) {
//#debug
System.out.println("init: Aborting init due to invisibility for item " + this );
this.itemWidth = 0;
this.itemHeight = 0;
return;
}
//#endif
if (this.style != null && !this.isStyleInitialised) {
setStyle( this.style );
}
//#ifdef polish.useDynamicStyles
else if (this.style == null) {
initStyle();
}
//#else
else if (this.style == null && !this.isStyleInitialised) {
//#debug
System.out.println("Setting default style for item " + getClass().getName() );
setStyle( StyleSheet.defaultStyle );
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.parentItem = this;
}
//#endif
Style myStyle = this.style;
if (myStyle != null) {
initLayout(myStyle, availWidth);
}
int labelWidth = 0;
int labelHeight = 0;
Item labelItem = this.label;
if (labelItem != null) {
labelWidth = labelItem.getItemWidth( firstLineWidth, availWidth, availHeight );
labelHeight = labelItem.itemHeight;
}
// calculate content width and content height:
int noneContentWidth =
this.marginLeft + getBorderWidthLeft() + this.paddingLeft
+ this.paddingRight + getBorderWidthRight() + this.marginRight;
//#ifdef polish.css.before
noneContentWidth += getBeforeWidthWithPadding();
//#endif
//#ifdef polish.css.after
noneContentWidth += getAfterWidthWithPadding();
//#endif
int firstLineContentWidth = firstLineWidth - noneContentWidth;
int availableContentWidth = availWidth - noneContentWidth;
//#ifdef polish.css.max-width
if (this.maximumWidth != null ) {
int maxWidth = this.maximumWidth.getValue(availableContentWidth);
if(firstLineContentWidth > maxWidth) {
firstLineContentWidth = maxWidth;
}
if(availableContentWidth > maxWidth) {
availableContentWidth = maxWidth;
}
}
//#endif
//#ifdef polish.css.width
int targetWidth = 0;
if (this.cssWidth != null) {
availableContentWidth = this.cssWidth.getValue(availWidth - noneContentWidth);
firstLineContentWidth = availableContentWidth;
targetWidth = availableContentWidth;
}
//#endif
//#ifdef polish.css.max-item-width
if (this.maximumItemWidth != null && this.isLayoutExpand) {
int maxWidth = this.maximumItemWidth.getValue(availWidth);
if (availableContentWidth + noneContentWidth > maxWidth ) {
availableContentWidth = maxWidth - noneContentWidth;
if (firstLineContentWidth > availableContentWidth) {
firstLineContentWidth = availableContentWidth;
}
}
}
//#endif
this.contentX = this.marginLeft + getBorderWidthLeft() + this.paddingLeft;
//#ifdef polish.css.before
this.contentX += getBeforeWidthWithPadding();
//#endif
int noneContentHeight = this.marginTop + getBorderWidthTop() + this.paddingTop;
this.contentY = noneContentHeight;
noneContentHeight += this.paddingBottom + getBorderWidthBottom() + this.marginBottom;
//#ifdef polish.css.height
int targetHeight = 0;
if(this.cssHeight != null) {
// according to css specs the base for the height calculation is the available width
targetHeight = this.cssHeight.getValue(
//#if polish.Item.useHeightInsteadOfWidth
//# availHeight
//#else
availWidth
//#endif
);
availHeight = targetHeight;
}
//#endif
// initialise content by subclass:
//#if polish.css.content-visible
if (!this.isContentVisible) {
this.contentWidth = 0;
this.contentHeight = 0;
} else {
//#endif
availHeight -= noneContentHeight;
this.availContentWidth = availableContentWidth;
this.availContentHeight = availHeight;
//#if polish.css.inline-label
if (this.isInlineLabel && labelWidth < (90 * availWidth)/100) {
firstLineContentWidth -= labelWidth;
availableContentWidth -= labelWidth;
}
//#endif
//#ifdef polish.css.view-type
ItemView myView = this.view;
if (myView != null) {
myView.init(this, firstLineContentWidth, availableContentWidth, availHeight);
this.contentWidth = myView.contentWidth;
this.contentHeight = myView.contentHeight;
} else {
//#endif
initContent( firstLineContentWidth, availableContentWidth, availHeight );
//#ifdef polish.css.view-type
}
//#endif
//#if polish.css.inline-label
if (this.isInlineLabel && labelWidth < (90 * availWidth)/100) {
availableContentWidth += labelWidth;
}
//#endif
//#if polish.css.content-visible
}
//#endif
int cWidth = this.contentWidth;
int cHeight = this.contentHeight;
if (cWidth == 0 && cHeight == 0) {
this.itemWidth = labelWidth;
this.itemHeight = labelHeight;
this.backgroundHeight = 0;
this.backgroundWidth = 0;
setInitialized(true);
return;
}
if (cWidth > availableContentWidth) {
cWidth = availableContentWidth;
}
//#ifdef polish.css.width
if(this.cssWidth != null) {
setContentWidth( targetWidth );
int diff = this.contentWidth - cWidth;
if (isLayoutCenter()) {
this.contentX += diff/2;
} else if (isLayoutRight()) {
this.contentX += diff;
}
cWidth = this.contentWidth;
}
//#endif
//#ifdef polish.css.min-width
if (this.minimumWidth != null) {
int minWidth = this.minimumWidth.getValue(availWidth - noneContentWidth);
if (cWidth < minWidth ) {
setContentWidth( minWidth );
int diff = this.contentWidth - cWidth;
if (isLayoutCenter()) {
this.contentX += diff/2;
} else if (isLayoutRight()) {
this.contentX += diff;
}
cWidth = this.contentWidth;
}
}
//#endif
//#ifdef polish.css.max-width
if (this.maximumWidth != null) {
int maxWidth = this.maximumWidth.getValue(availWidth - noneContentWidth);
if (cWidth > maxWidth ) {
setContentWidth( maxWidth );
cWidth = this.contentWidth;
}
}
//#endif
this.itemWidth = noneContentWidth + cWidth;
//#ifdef polish.css.min-item-width
if (this.minimumItemWidth != null) {
if (this.itemWidth < this.minimumItemWidth.getValue(availWidth) ) {
int minWidth = this.minimumItemWidth.getValue(availWidth);
if (minWidth > availWidth) {
minWidth = availWidth;
}
int diff = minWidth - this.itemWidth;
setItemWidth( this.itemWidth + diff );
setContentWidth( this.contentWidth + diff );
cWidth = this.contentWidth;
}
}
//#endif
//#ifdef polish.css.max-item-width
if (this.maximumItemWidth != null) {
int maxWidth = this.maximumItemWidth.getValue(availWidth);
if (this.itemWidth > maxWidth ) {
int diff = maxWidth - this.itemWidth;
this.itemWidth += diff;
setContentWidth( this.contentWidth + diff );
cWidth = this.contentWidth;
}
}
//#endif
if ( this.isLayoutExpand ) {
if (cWidth < availableContentWidth) {
int iWidth = this.itemWidth;
if (
//#if polish.css.max-width
this.maximumWidth == null &&
//#endif
this.itemWidth + labelWidth <= availWidth && (this.label == null || !(this.label.isLayoutNewlineAfter() || isLayoutNewlineBefore())))
{
iWidth += availableContentWidth - cWidth - labelWidth;
} else {
iWidth += availableContentWidth - cWidth;
}
setItemWidth( iWidth );
}
} else if (this.itemWidth > availWidth) {
setItemWidth( availWidth );
}
if (this.itemWidth + labelWidth <= availWidth) {
// label and content fit on one row:
this.useSingleRow = true;
if (this.label != null) {
if ( (this.label.layout & LAYOUT_NEWLINE_AFTER) != 0 || ((this.layout & LAYOUT_NEWLINE_BEFORE) == LAYOUT_NEWLINE_BEFORE )) {
this.useSingleRow = false;
cHeight += labelHeight;
this.contentY += labelHeight;
if (this.itemWidth < labelWidth) {
setItemWidth(labelWidth);
}
}
}
if (this.useSingleRow && labelWidth > 0) {
this.itemWidth += labelWidth; //TODO: when calling setItemWidth() here it will affect center and right layout items within a Container, but setting the variable directly is also not cool...
this.contentX += labelWidth;
if ( cHeight + noneContentHeight < labelHeight ) {
cHeight = labelHeight - noneContentHeight;
}
}
} else {
this.useSingleRow = false;
cHeight += labelHeight;
this.contentY += labelHeight;
if (labelWidth > 0) {
int labelX = 0;
if (isLayoutCenter()) {
labelX = (this.itemWidth - availWidth) / 2;
} else if (isLayoutRight()) {
labelX = this.itemWidth - availWidth;
}
//#if polish.css.include-label
else if (this.includeLabel) {
labelX += this.marginLeft;
}
//#endif
//#if polish.css.complete-background
else if (this.completeBackground != null) {
labelX += this.marginLeft;
}
//#endif
//#if polish.css.complete-border
else if (this.completeBorder != null) {
labelX += this.marginLeft;
}
//#endif
if (this.label.isLayoutCenter()) {
labelX += (availWidth - labelWidth)/2;
} else if (this.label.isLayoutRight()) {
labelX += (availWidth - labelWidth);
}
this.label.relativeX = labelX;
}
}
int originalContentHeight = cHeight;
int heightRelativeValue = availWidth;
//#if polish.Item.useHeightInsteadOfWidth
heightRelativeValue = availHeight;
//#endif
//#ifdef polish.css.height
if(this.cssHeight != null) {
setContentHeight( targetHeight );
cHeight = this.contentHeight;
}
//#endif
//#ifdef polish.css.min-height
if (this.minimumHeight != null) {
int minHeight = this.minimumHeight.getValue(heightRelativeValue);
if (cHeight < minHeight ) {
setContentHeight( minHeight );
cHeight = this.contentHeight;
}
}
//#endif
//#ifdef polish.css.max-height
if (this.maximumHeight != null) {
int maxHeight = this.maximumHeight.getValue(heightRelativeValue);
if (cHeight > maxHeight ) {
setContentHeight( maxHeight );
cHeight = this.contentHeight;
}
}
//#endif
//#if polish.css.min-item-height
if (this.minimumItemHeight != null && cHeight + noneContentHeight < this.minimumItemHeight.getValue(heightRelativeValue)) {
cHeight = this.minimumItemHeight.getValue(heightRelativeValue) - noneContentHeight;
}
//#endif
//#if polish.css.max-item-height
if (this.maximumItemHeight != null && cHeight + noneContentHeight > this.maximumItemHeight.getValue(heightRelativeValue)) {
cHeight = this.maximumItemHeight.getValue(heightRelativeValue) - noneContentHeight;
}
//#endif
if (cHeight > originalContentHeight) {
int ch = cHeight;
if (!this.useSingleRow) {
ch -= labelHeight;
}
if (isLayoutVerticalCenter()) {
this.contentY += ( (ch - originalContentHeight) >> 1);
} else if (isLayoutBottom()) {
this.contentY += ( ch - originalContentHeight );
}
}
//#ifdef polish.css.before
if (cHeight < this.beforeHeight) {
cHeight = this.beforeHeight;
}
//#endif
//#ifdef polish.css.after
if (cHeight < this.afterHeight) {
cHeight = this.afterHeight;
}
//#endif
this.itemHeight = cHeight + noneContentHeight;
if (this.useSingleRow) {
this.backgroundWidth = this.itemWidth - this.marginLeft - this.marginRight - labelWidth;
this.backgroundHeight = cHeight
+ noneContentHeight
- this.marginTop
- this.marginBottom;
} else {
this.backgroundWidth = this.itemWidth - this.marginLeft - this.marginRight;
this.backgroundHeight = cHeight
+ noneContentHeight
- this.marginTop
- this.marginBottom
- labelHeight;
// if (labelWidth > this.itemWidth) {
// int diff = labelWidth - this.itemWidth;
// if (isLayoutCenter()) {
// this.contentX += diff/2;
// } else if (isLayoutRight()) {
// this.contentX += diff;
// }
// this.itemWidth = labelWidth;
// }
}
// if (labelWidth > 0 && availableContentWidth > this.contentWidth) {
// //int diff = availableContentWidth - this.contentWidth;
// int contX = this.contentX;
// if (isLayoutCenter()) {
// contX = (availWidth - this.contentWidth)/2;
// } else if (isLayoutRight()) {
// contX = (availWidth - this.contentWidth);
// }
// if (contX > this.contentX) {
// //System.out.println("init: changing contentX from " + contentX + " to " + contX);
// //this.contentX = contX;
// setItemWidth( availWidth );
// }
// }
if (labelWidth > 0 && this.useSingleRow && labelHeight < this.itemHeight) {
if (this.label.isLayoutVerticalCenter()) {
this.label.relativeY = (this.itemHeight - labelHeight) / 2;
} else if (this.label.isLayoutBottom()) {
this.label.relativeY = (this.itemHeight - labelHeight);
}
}
//#if polish.css.background-width
this.originalBackgroundWidth = this.backgroundWidth;
if (this.style != null) {
Dimension bgWidth = (Dimension) this.style.getObjectProperty("background-width");
if (bgWidth != null) {
this.backgroundWidth = bgWidth.getValue(this.backgroundWidth);
}
}
//#endif
//#if polish.css.background-height
this.originalBackgroundHeight = this.backgroundHeight;
if (this.style != null) {
Dimension bgHeight = (Dimension) this.style.getObjectProperty("background-height");
if (bgHeight != null) {
this.backgroundHeight = bgHeight.getValue(this.backgroundHeight);
}
}
//#endif
//#if tmp.invisible
if (this.isInvisible) {
this.itemWidth = 0;
this.itemHeight = 0;
}
//#endif
//#if polish.css.opacity && polish.midp2
this.opacityRgbData = null;
//#endif
setInitialized(true);
//#debug
System.out.println("Item.init(): contentHeight=" + this.contentHeight + ", itemHeight=" + this.itemHeight + " for " + this);
//#debug
System.out.println("Item.init(): contentWidth=" + this.contentWidth + ", itemWidth=" + this.itemWidth + ", backgroundWidth=" + this.backgroundWidth);
}
//#if polish.css.before
/**
* Gets the before width along plus the horizontal padding when there is an before element defined.
* @return the width of the before element plus the horizontal padding or 0.
*/
protected int getBeforeWidthWithPadding() {
int w = this.beforeWidth;
if (w != 0) {
w += this.paddingHorizontal;
}
return w;
}
//#endif
//#if polish.css.after
/**
* Gets the after width along plus the horizontal padding when there is an after element defined.
* @return the width of the after element plus the horizontal padding or 0.
*/
protected int getAfterWidthWithPadding() {
int w = this.afterWidth;
if (w != 0) {
w += this.paddingHorizontal;
}
return w;
}
//#endif
/**
* Initializes paddings and margins.
* @param layoutStyle the style of this item
* @param availWidth the available width in case paddings or margins include relative values
*/
protected void initLayout(Style layoutStyle, int availWidth) {
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.initPadding(layoutStyle, availWidth);
} else
//#endif
{
initPadding(layoutStyle, availWidth);
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.initMargin(layoutStyle, availWidth);
} else
//#endif
{
initMargin(layoutStyle, availWidth);
}
}
/**
* Initializes the margin of this item
* Subclasses can override this (e.g. the container embedded in a screen)
* @param itemStyle the style
* @param availWidth the available width
*/
protected void initMargin(Style itemStyle, int availWidth) {
this.marginLeft = itemStyle.getMarginLeft(availWidth);
this.marginRight = itemStyle.getMarginRight(availWidth);
this.marginTop = itemStyle.getMarginTop(availWidth);
this.marginBottom = itemStyle.getMarginBottom(availWidth);
}
/**
* Initializes the padding of this item
* Subclasses can override this (e.g. the container embedded in a screen)
* @param itemStyle the style
* @param availWidth the available width
*/
protected void initPadding(Style itemStyle, int availWidth) {
this.paddingLeft = itemStyle.getPaddingLeft(availWidth);
this.paddingRight = itemStyle.getPaddingRight(availWidth);
this.paddingTop = itemStyle.getPaddingTop(availWidth);
this.paddingBottom = itemStyle.getPaddingBottom(availWidth);
this.paddingVertical = itemStyle.getPaddingVertical(availWidth);
this.paddingHorizontal = itemStyle.getPaddingHorizontal(availWidth);
}
/**
* Retrieves the right padding of this item.
* Note that the padding is only initialized AFTER init() or initContent() has been called.
* @return the padding in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getPaddingRight() {
return this.paddingRight;
}
/**
* Retrieves the left padding of this item.
* Note that the padding is only initialized AFTER init() or initContent() has been called.
* @return the padding in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getPaddingLeft() {
return this.paddingLeft;
}
/**
* Retrieves the rop padding of this item.
* Note that the padding is only initialized AFTER init() or initContent() has been called.
* @return the padding in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getPaddingTop() {
return this.paddingTop;
}
/**
* Retrieves the bottom padding of this item.
* Note that the padding is only initialized AFTER init() or initContent() has been called.
* @return the padding in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getPaddingBottom() {
return this.paddingBottom;
}
/**
* Retrieves the horizontal padding of this item.
* Note that the padding is only initialized AFTER init() or initContent() has been called.
* @return the padding in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getPaddingHorizontal() {
return this.paddingHorizontal;
}
/**
* Retrieves the vertical padding of this item.
* Note that the padding is only initialized AFTER init() or initContent() has been called.
* @return the padding in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getPaddingVertical() {
return this.paddingVertical;
}
/**
* Retrieves the right margin of this item.
* Note that the margin is only initialized AFTER init() or initContent() has been called.
* @return the margin in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getMarginRight() {
return this.marginRight;
}
/**
* Retrieves the left margin of this item.
* Note that the margin is only initialized AFTER init() or initContent() has been called.
* @return the margin in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getMarginLeft() {
return this.marginLeft;
}
/**
* Retrieves the rop margin of this item.
* Note that the margin is only initialized AFTER init() or initContent() has been called.
* @return the margin in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getMarginTop() {
return this.marginTop;
}
/**
* Retrieves the bottom margin of this item.
* Note that the margin is only initialized AFTER init() or initContent() has been called.
* @return the margin in pixels.
* @see Item#init(int, int, int)
* @see Item#initContent(int, int, int)
*/
public int getMarginBottom() {
return this.marginBottom;
}
/**
* Sets the content width of this item.
* Subclasses can override this to react to content width changes
* @param width the new content width in pixel
*/
protected void setContentWidth( int width ) {
this.contentWidth = width;
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.setContentWidth( width );
}
//#endif
}
/**
* Sets the content height of this item.
* Subclasses can override this to react to content height changes
* @param height the new content height in pixel
*/
protected void setContentHeight( int height ) {
this.contentHeight = height;
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.setContentHeight( height );
}
//#endif
}
//#ifdef polish.useDynamicStyles
/**
* Initialises the appropriate style for this item.
*/
protected void initStyle() {
//System.out.println("item [" + this.getClass().getName() + "/" + this.cssSelector + "/" + this.hashCode() + "] has been initalised: " + this.isStyleInitialised );
if (this.screen == null) {
if (this.parent != null) {
this.screen = getScreen();
} else {
this.screen = StyleSheet.currentScreen;
}
}
if (this.style == null) {
this.cssSelector = createCssSelector();
//#debug
System.out.println("getting style for item [" + this.cssSelector + "].");
Style myStyle = StyleSheet.getStyle( this );
if (myStyle == null) {
myStyle = StyleSheet.defaultStyle;
}
if (myStyle != null) {
setStyle( myStyle );
}
} else {
//System.out.println("item has already style [" + this.style.name + "].");
this.cssSelector = this.style.name;
}
this.isStyleInitialised = true;
}
//#endif
/**
* Initialises this item.
* The implementation needs to calculate and set the contentWidth and
* contentHeight fields.
* The implementation should take the fields preferredWidth and preferredHeight
* into account.
*
*
* @param firstLineWidth the maximum width of the first line
* @param availWidth the available maximum width of this item in pixels
* @param availHeight the available maximum height of this item in pixels
* @see #contentWidth
* @see #contentHeight
* @see #preferredWidth
* @see #preferredHeight
*/
protected abstract void initContent(int firstLineWidth, int availWidth, int availHeight);
/**
* Paints the content of this item.
* The background has already been painted and the border will be added after
* this method returns.
*
* @param x the left start position
* @param y the upper start position
* @param leftBorder the left border, nothing must be painted left of this position
* @param rightBorder the right border, nothing must be painted right of this position
* @param g the Graphics on which this item should be painted.
*/
protected abstract void paintContent( int x, int y, int leftBorder, int rightBorder, Graphics g );
//#ifdef polish.useDynamicStyles
/**
* Retrieves the CSS selector for this item.
* The CSS selector is used for the dynamic assignment of styles -
* that is the styles are assigned by the usage of the item and
* not by a predefined style-name.
* With the #style preprocessing command styles are set fix, this method
* yields in a faster GUI and is recommended. When in a style-sheet
* dynamic styles are used, e.g. "Form>p", than the selector of the
* item is needed.
* <br/>
* This abstract method needs only be implemented, when dynamic styles
* are used: #ifdef polish.useDynamicStyles
* <br/>
* The returned selector needs to be in lower case.
*
* @return the appropriate CSS selector for this item.
* The selector needs to be in lower case.
*/
protected abstract String createCssSelector();
//#endif
/**
* Handles the key-pressed event.
* Please note, that implementation should first try to handle the
* given key-code, before the game-action is processed.
*
* The default implementation just handles the FIRE game-action
* when a default-command and an item-command-listener have been
* registered.
*
* @param keyCode the code of the pressed key, e.g. Canvas.KEY_NUM2
* @param gameAction the corresponding game-action, e.g. Canvas.UP
* @return true when the key has been handled / recognized
*/
protected boolean handleKeyPressed( int keyCode, int gameAction ) {
//#debug
System.out.println("item " + this + ": handling keyPressed for keyCode=" + keyCode + ", gameAction=" + gameAction);
Screen scr = getScreen();
if ( this.appearanceMode != PLAIN && null != scr && scr.isGameActionFire(keyCode, gameAction) )
{
return notifyItemPressedStart();
}
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handleKeyPressed(keyCode, gameAction);
}
//#endif
return false;
}
/**
* Handles the key-repeated event.
* Please note, that implementation should first try to handle the
* given key-code, before the game-action is processed.
*
* The default implementation forwards the event to the handleKeyPressed method.
*
* @param keyCode the code of the pressed key, e.g. Canvas.KEY_NUM2
* @param gameAction the corresponding game-action, e.g. Canvas.UP
* @return true when the key has been handled / recognized
* @see #handleKeyPressed(int, int)
*/
protected boolean handleKeyRepeated( int keyCode, int gameAction ) {
boolean handled = handleKeyPressed(keyCode, gameAction);
//#ifdef polish.css.view-type
if(!handled && this.view != null) {
handled = this.view.handleKeyPressed(keyCode, gameAction);
}
//#endif
return handled;
}
/**
* Handles the key-released event.
* Please note, that implementation should first try to handle the
* given key-code, before the game-action is processed.
*
* The default implementation invokes the default command if one is present
*
* @param keyCode the code of the pressed key, e.g. Canvas.KEY_NUM2
* @param gameAction the corresponding game-action, e.g. Canvas.UP
* @return true when the key has been handled / recognized
* @see #handleKeyPressed(int, int)
*/
protected boolean handleKeyReleased( int keyCode, int gameAction ) {
//#debug
System.out.println("handleKeyReleased(" + keyCode + ", " + gameAction + ") for " + this + ", isPressed=" + this.isPressed );
Screen scr = getScreen();
if (this.appearanceMode != PLAIN && this.isPressed && scr != null && scr.isGameActionFire(keyCode, gameAction) )
{
notifyItemPressedEnd();
Item item = this;
if (this.defaultCommand == null && this.parent != null) {
item = this.parent;
}
if (item.defaultCommand != null) {
if (!item.defaultCommand.commandAction(this, scr)) {
if (item.itemCommandListener != null) {
//#if polish.executeCommandsAsynchrone
AsynchronousMultipleCommandListener.getInstance().commandAction(item.itemCommandListener, item.defaultCommand, this);
//#else
item.itemCommandListener.commandAction(item.defaultCommand, this);
//#endif
} else {
scr.callCommandListener(item.defaultCommand);
}
}
//#if polish.css.visited-style
notifyVisited();
//#endif
return true;
}
}
int clearKey =
//#if polish.key.ClearKey:defined
//#= ${polish.key.ClearKey};
//#else
-8;
//#endif
if (keyCode == clearKey && this.commands != null) {
Command deleteCommand = null;
Object[] cmds = this.commands.getInternalArray();
for (int i = 0; i < cmds.length; i++)
{
Command cmd = (Command) cmds[i];
if (cmd == null) {
break;
}
if (cmd.getCommandType() == Command.CANCEL && (deleteCommand == null || deleteCommand.getPriority() > cmd.getPriority()) ) {
deleteCommand = cmd;
}
}
if (deleteCommand != null) {
if (this.itemCommandListener != null) {
this.itemCommandListener.commandAction(deleteCommand, this);
} else if (scr != null ) {
scr.callCommandListener(deleteCommand);
}
}
}
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handleKeyReleased(keyCode, gameAction);
}
//#endif
return false;
}
/**
* Is called when this item has been visited.
*/
public void notifyVisited() {
//#if polish.css.visited-style
if (this.style != null && !this.hasBeenVisited) {
if (this.isPressed) {
notifyItemPressedEnd();
}
Style visitedStyle = (Style) this.style.getObjectProperty("visited-style");
if (visitedStyle != null) {
this.hasBeenVisited = true;
//#debug
System.out.println("found visited style " + visitedStyle.name + " in " + this.style.name);
setStyle( visitedStyle );
}
if (this.parent instanceof Container) {
Container cont = (Container) this.parent;
visitedStyle = (Style) cont.itemStyle.getObjectProperty("visited-style");
if (visitedStyle != null) {
//#debug
System.out.println("found visited style " + visitedStyle.name + " in " + cont.itemStyle.name);
cont.itemStyle = visitedStyle;
}
}
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_VISIT, this, null);
//#endif
}
/**
* Is called when the visited state of this item should be reset.
*/
public void notifyUnvisited() {
//#if polish.css.visited-style
if (this.style != null && this.hasBeenVisited) {
if (this.isPressed) {
notifyItemPressedEnd();
}
this.hasBeenVisited = false;
Style[] styles = (Style[]) Arrays.toArray(StyleSheet.getStyles().elements(), new Style[ StyleSheet.getStyles().size()] );
Container cont = null;
if (this.parent instanceof Container) {
cont = (Container) this.parent;
}
boolean oneLeft = false;
for (int i = 0; i < styles.length; i++) {
Style aStyle = styles[i];
Style visitedStyle = (Style) aStyle.getObjectProperty("visited-style");
if (visitedStyle == this.style) {
setStyle( aStyle );
if (oneLeft) {
break;
} else {
oneLeft = true;
}
}
else if (cont != null && cont.itemStyle == visitedStyle) {
cont.itemStyle = aStyle;
if (!oneLeft) {
Style focStyle = (Style) aStyle.getObjectProperty("focused-style");
if (focStyle != null) {
setStyle( focStyle );
}
}
break;
}
}
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_UNVISIT, this, null);
//#endif
}
/**
* Is called when an item is pressed using the FIRE game action
*
* @return true when the item requests a repaint after this action
*/
public boolean notifyItemPressedStart() {
//try { throw new RuntimeException(); } catch (Exception e) { e.printStackTrace(); }
if (this.isPressed) {
return false;
}
//#debug
System.out.println("notifyItemPressedStart for " + this);
this.isPressed = true;
boolean handled = false;
//#if polish.css.pressed-style
//System.out.println("notifyItemPressedStart for " + this + ", pressedStyle=" + (this.pressedStyle != null ? this.pressedStyle.name : "<null>") );
if (this.pressedStyle != null && this.style != this.pressedStyle) {
this.normalStyle = this.style;
setStyle( this.pressedStyle );
handled = true;
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_PRESS, this, null);
//#endif
return handled;
}
/**
* Determines whether this item is currently pressed.
* @return true when this item is pressed
*/
public boolean isPressed() {
return this.isPressed;
}
/**
* Determines whether this item is currently focused.
* @return true when this item is focused
*/
public boolean isFocused() {
return this.isFocused;
}
/**
* Is called when an item is pressed
*/
public void notifyItemPressedEnd() {
if (!this.isPressed) {
return;
}
//#debug
System.out.println("notifyItemPressedEnd for " + this + ", normalStyle=" + (this.normalStyle == null ? "<none>" : this.normalStyle.name ) + ", current=" + (this.style == null ? "<none>" : this.style.name) );
this.isPressed = false;
//#if polish.css.pressed-style
Style previousStyle = this.normalStyle;
if (previousStyle != null && this.style != previousStyle) {
//#ifdef polish.css.view-type
boolean removeViewType = ( this.style.getObjectProperty("view-type") != null && previousStyle.getObjectProperty( "view-type") == null);
//#endif
setStyle( previousStyle );
repaint();
this.normalStyle = null;
//#ifdef polish.css.view-type
if (removeViewType) {
this.view = null;
}
//#endif
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_UNPRESS, this, null);
//#endif
if (this.parent != null) {
this.parent.notifyItemPressedEnd();
}
}
/**
* Determines whether the given relative x/y position is inside of this item's (visible) content area.
* Subclasses which extend their area over the declared/official content area, which is determined
* in the initContent() method (like popup items), might want to override this method or possibly the getContentX(), getContentY() methods.
* It is assumed that the item has been initialized before.
*
* @param relX the x position relative to this item's left position
* @param relY the y position relative to this item's top position
* @return true when the relX/relY coordinate is within this item's content area.
* @see #initContent(int, int, int)
*/
public boolean isInContentArea( int relX, int relY ) {
int contTop = this.contentY;
int contLeft = this.contentX;
int contW = this.contentWidth;
if (contW > this.availContentWidth) {
contW = this.availContentWidth;
}
if ( relY < contTop || relX < contLeft || relY > contTop + this.contentHeight || relX > contLeft + contW) {
//#debug
System.out.println("isInContentArea(" + relX + "," + relY + ") = false: contentY=" + this.contentY + ", contentY + contentHeight=" + (contTop + this.contentHeight) + " (" + this +")");
//#debug
System.out.println("isInContentArea(" + relX + "," + relY + ") = false: contentX=" + this.contentX + ", contentX + contentWidth=" + (contLeft + contW) + " (" + this +")");
return false;
}
//#debug
System.out.println("isInContentArea(" + relX + "," + relY + ") = true: contentX=" + this.contentX + ", contentX + contentWidth=" + (contLeft + contW) + ", contentY=" + this.contentY + ", contentY + contentHeight=" + (contTop + this.contentHeight) + " (" + this +")");
return true;
}
/**
* Determines whether the given relative x/y position is inside of this item's content area.
* Subclasses which extend their area over the declared/official content area, which is determined
* in the initContent() method (like popup items), might want to override this method or possibly the getContentX(), getContentY() methods.
* It is assumed that the item has been initialized before.
*
* @param relX the x position relative to this item's left position
* @param relY the y position relative to this item's top position
* @return true when the relX/relY coordinate is within this item's content + padding area.
* @see #initContent(int, int, int)
*/
public boolean isInContentWithPaddingArea( int relX, int relY ) {
int contTop = this.contentY - this.paddingTop;
if ( relY < contTop || relY > contTop + this.contentHeight + this.paddingTop + this.paddingBottom ) {
//#debug
System.out.println("isInContentWithPaddingArea(" + relX + "," + relY + ") = false: contentY=" + this.contentY + ", contentY + contentHeight=" + (contTop + this.contentHeight) + " (" + this +")");
return false;
}
int contLeft = this.contentX - this.paddingLeft;
if (relX < contLeft || relX > contLeft + this.contentWidth + this.paddingLeft + this.paddingRight) {
//#debug
System.out.println("isInContentWithPaddingArea(" + relX + "," + relY + ") = false: contentX=" + this.contentX + ", contentX + contentWidth=" + (contLeft + this.contentWidth) + " (" + this +")");
return false;
}
//#debug
System.out.println("isInContentWithPaddingArea(" + relX + "," + relY + ") = true: contentX=" + this.contentX + ", contentX + contentWidth=" + (contLeft + this.contentWidth) + ", contentY=" + this.contentY + ", contentY + contentHeight=" + (contTop + this.contentHeight) + " (" + this +")");
return true;
}
/**
* Determines whether the given relative x/y position is inside of this item's area including paddings, margins and label.
* Subclasses which extend their area over the declared/official content area, which is determined
* in the initContent() method (like popup items), might want to override this method.
* It is assumed that the item has been initialized before.
*
* @param relX the x position relative to this item's left position
* @param relY the y position relative to this item's top position
* @return true when the relX/relY coordinate is within this item's area.
* @see #initContent(int, int, int)
*/
public boolean isInItemArea( int relX, int relY ) {
if (relY < 0 || relY > this.itemHeight || relX < 0 || relX > this.itemWidth) { //Math.max(this.itemWidth, this.contentX + this.contentWidth)) {
//#debug
System.out.println("isInItemArea(" + relX + "," + relY + ") = false: itemWidth=" + this.itemWidth + ", itemHeight=" + this.itemHeight + " (" + this + ")");
return false;
}
//#debug
System.out.println("isInItemArea(" + relX + "," + relY + ") = true: itemWidth=" + this.itemWidth + ", itemHeight=" + this.itemHeight + " (" + this + ")");
return true;
}
/**
* Determines whether the given relative x/y position is inside of the specified child item's area including paddings, margins and label.
* Subclasses which extend their area over the declared/official content area, which is determined
* in the initContent() method (like popup items), might want to override this method.
* It is assumed that the item has been initialized before.
*
* @param relX the x position relative to this item's left content position
* @param relY the y position relative to this item's top content position
* @param child the child
* @return true when the relX/relY coordinate is within the child item's area.
*/
public boolean isInItemArea( int relX, int relY, Item child ) {
if (child != null) {
return child.isInItemArea(relX - child.relativeX, relY - child.relativeY);
}
return false;
}
/**
* Handles the event when a pointer has been pressed at the specified position.
* The default method discards this event when relX/relY is outside of the item's area.
* When the event took place inside of the content area, the pointer-event is translated into an artificial
* FIRE game-action keyPressed event, which is subsequently handled
* by the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the pressing of the pointer was actually handled by this item.
* @see #isInItemArea(int, int) this method is used for determining whether the event belongs to this item
* @see #isInContentArea(int, int) for a helper method for determining whether the event took place into the actual content area
* @see #handleKeyPressed(int, int)
* @see #contentX for calculating the horizontal position relative to the content (relX - contentX)
* @see #contentY for calculating the vertical position relative to the content (relY - contentY)
*/
protected boolean handlePointerPressed( int relX, int relY ) {
//#ifdef polish.hasPointerEvents
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
Container cmdCont = this.commandsContainer;
if (cmdCont != null && cmdCont.handlePointerPressed(relX - cmdCont.relativeX, relY - cmdCont.relativeY)) {
return true;
}
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerPressed(relX, relY)) {
return true;
}
//#endif
if ( isInItemArea(relX, relY) ) {
//#if tmp.supportTouchGestures
this.gestureStartTime = System.currentTimeMillis();
this.gestureStartX = relX;
this.gestureStartY = relY;
//#endif
return handleKeyPressed( 0, Canvas.FIRE );
}
//#if polish.Item.ShowCommandsOnHold
else {
this.gestureStartTime = 0;
if (this.isShowCommands) {
this.isShowCommands = false;
return true;
}
}
//#endif
//#endif
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handlePointerPressed(relX, relY);
}
//#endif
return false;
}
/**
* Handles the event when a pointer has been released at the specified position.
* The default method discards this event when relX/relY is outside of the item's area.
* When the event took place inside of the content area, the pointer-event is translated into an artificial
* FIRE game-action keyReleased event, which is subsequently handled
* bu the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the pressing of the pointer was actually handled by this item.
* @see #isInItemArea(int, int) this method is used for determining whether the event belongs to this item
* @see #isInContentArea(int, int) for a helper method for determining whether the event took place into the actual content area
* @see #handleKeyPressed(int, int)
* @see #contentX for calculating the horizontal position relative to the content (relX - contentX)
* @see #contentY for calculating the vertical position relative to the content (relY - contentY)
*/
protected boolean handlePointerReleased( int relX, int relY ) {
//#ifdef polish.hasPointerEvents
//#debug
System.out.println("handlePointerReleased " + relX + ", " + relY + " for item " + this + " isPressed=" + this.isPressed);
// handle keyboard behaviour only if this not a container,
// its handled in the overwritten version
if (this.isJustFocused) {
this.isJustFocused = false;
handleOnFocusSoftKeyboardDisplayBehavior();
}
//#if tmp.supportTouchGestures
if (this.isIgnorePointerReleaseForGesture) {
this.isIgnorePointerReleaseForGesture = false;
return true;
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
this.commandsContainer.handlePointerReleased(relX - this.commandsContainer.relativeX, relY - this.commandsContainer.relativeY);
this.isShowCommands = false;
notifyItemPressedEnd();
return true;
}
//#endif
//#if tmp.supportTouchGestures
int verticalDiff = Math.abs( relY - this.gestureStartY );
if (verticalDiff < 20) {
int horizontalDiff = relX - this.gestureStartX;
if (horizontalDiff > this.itemWidth/2) {
if (handleGesture(GestureEvent.GESTURE_SWIPE_RIGHT, relX, relY)) {
return true;
}
} else if (horizontalDiff < -this.itemWidth/2) {
if (handleGesture(GestureEvent.GESTURE_SWIPE_LEFT, relX, relY)) {
return true;
}
}
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerReleased(relX, relY)) {
return true;
}
//#endif
if ( isInItemArea(relX, relY) ) {
return handleKeyReleased( 0, Canvas.FIRE );
} else if (this.isPressed) {
notifyItemPressedEnd();
return true;
}
//#endif
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handlePointerReleased(relX, relY);
}
//#endif
return false;
}
/**
* Handles the dragging/movement of a pointer.
* This method should be overwritten only when the polish.hasPointerEvents
* preprocessing symbol is defined.
* The default implementation returns false.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the dragging of the pointer was actually handled by this item.
*/
protected boolean handlePointerDragged(int relX, int relY, ClippingRegion repaintRegion)
{
boolean handled = false;
//#ifdef polish.hasPointerEvents
//#if tmp.supportTouchGestures
if (this.gestureStartTime != 0 && Math.abs( relX - this.gestureStartX) > 30 || Math.abs( relY - this.gestureStartY) > 30) {
// abort (hold) gesture after moving out for too much:
this.gestureStartTime = 0;
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands && this.commandsContainer.handlePointerDragged(relX - this.commandsContainer.relativeX, relY - this.commandsContainer.relativeY, repaintRegion)) {
handled = true;
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerDragged(relX, relY, repaintRegion)) {
handled = true;
}
//#endif
//#endif
if (handlePointerDragged(relX, relY)) {
addRepaintArea(repaintRegion);
handled = true;
}
return handled;
}
/**
* Handles the dragging/movement of a pointer.
* This method should be overwritten only when the polish.hasPointerEvents
* preprocessing symbol is defined.
* The default implementation returns false.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the dragging of the pointer was actually handled by this item.
*/
protected boolean handlePointerDragged(int relX, int relY)
{
return false;
}
/**
* Handles a touch down/press event.
* This is similar to a pointerPressed event, however it is only available on devices with screens that differentiate
* between press and touch events (read: BlackBerry Storm).
*
* @param x the horizontal pixel position of the touch event relative to this item's left position
* @param y the vertical pixel position of the touch event relative to this item's top position
* @return true when the event was handled
*/
public boolean handlePointerTouchDown( int x, int y ) {
//#if polish.hasTouchEvents && polish.css.view-type
if (this.view != null && this.view.handlePointerTouchDown(x, y)) {
return true;
}
//#endif
return false;
}
/**
* Handles a touch up/release event.
* This is similar to a pointerReleased event, however it is only available on devices with screens that differentiate
* between press and touch events (read: BlackBerry Storm).
*
* @param x the horizontal pixel position of the touch event relative to this item's left position
* @param y the vertical pixel position of the touch event relative to this item's top position
* @return true when the event was handled
*/
public boolean handlePointerTouchUp( int x, int y ) {
//#if polish.hasTouchEvents && polish.css.view-type
if (this.view != null && this.view.handlePointerTouchUp(x, y)) {
return true;
}
//#endif
return false;
}
/**
* Handles a touch gestures.
* Note that touch gesture support needs to be activated using the preprocessing variable polish.supportGestures.
* The default implementation calls handleGestureHold() in case GESTURE_HOLD is specified.
* @param gesture the gesture identifier, e.g. GESTURE_HOLD
* @return true when this gesture was handled
* @see #handleGestureHold(int, int)
*/
protected boolean handleGesture(int gesture, int x, int y) {
boolean handled = false;
switch (gesture) {
case GestureEvent.GESTURE_HOLD:
handled = handleGestureHold(x, y);
break;
case GestureEvent.GESTURE_SWIPE_LEFT:
handled = handleGestureSwipeLeft(x, y);
break;
case GestureEvent.GESTURE_SWIPE_RIGHT:
handled = handleGestureSwipeRight(x, y);
}
if (!handled) {
GestureEvent event = GestureEvent.getInstance();
event.reset( gesture, x, y );
UiEventListener listener = getUiEventListener();
if (listener != null) {
listener.handleUiEvent(event, this);
handled = event.isHandled();
}
//#if tmp.handleEvents
if (!handled) {
EventManager.fireEvent(event.getGestureName(), this, event );
handled = event.isHandled();
}
//#endif
}
return handled;
}
/**
* Handles the hold touch gestures.
* Note that touch gesture support needs to be activated using the preprocessing variable polish.supportGestures
* The default implementation shows the commands of this item, but only when the preprocessing variable
* polish.Item.ShowCommandsOnHold is set to true.
*
* @return true when this gesture was handled
*/
protected boolean handleGestureHold(int x, int y) {
//#if polish.Item.ShowCommandsOnHold
if (this.commands != null && !this.isShowCommands && this.commands.size() > 1) {
this.isShowCommands = true;
if (this.commandsContainer != null) {
this.commandsContainer.focusChild(-1);
}
return true;
}
//#endif
return false;
}
/**
* Handles the swipe left gesture.
* @return true when the gesture was handled
*/
protected boolean handleGestureSwipeLeft(int x, int y) {
return false;
}
/**
* Handles the swipe right gesture.
* @return true when the gesture was handled
*/
protected boolean handleGestureSwipeRight(int x, int y) {
return false;
}
/**
* Adds a repaint request for this item's space.
* @param repaintRegion the clipping rectangle to which the repaint area should be added
*/
public void addRepaintArea( ClippingRegion repaintRegion ) {
int absX = getAbsoluteX();
int absY = getAbsoluteY();
int w = this.itemWidth;
int h = this.itemHeight + 1;
//#if polish.css.filter
RgbImage img = this.filterProcessedRgbImage;
if (img != null && (img.getHeight() > h || img.getWidth() > w)) {
int lo = this.layout;
int wFilter = img.getWidth();
int hFilter = img.getHeight();
int horDiff = wFilter - w;
int verDiff = hFilter - h;
if ((lo & LAYOUT_CENTER) == LAYOUT_CENTER) {
absX -= horDiff / 2;
w += horDiff;
} else if ((lo & LAYOUT_CENTER) == LAYOUT_RIGHT) {
absX -= horDiff;
} else {
w += horDiff;
}
if ((lo & LAYOUT_VCENTER) == LAYOUT_VCENTER) {
absY -= verDiff / 2;
h += verDiff;
} else if ((lo & LAYOUT_VCENTER) == LAYOUT_TOP) {
absY -= verDiff;
} else {
h += verDiff;
}
}
//#endif
//System.out.println("adding repaint area x=" + getAbsoluteX() + ", width=" + this.itemWidth + ", y=" + getAbsoluteY() + " for " + this);
repaintRegion.addRegion(
absX,
absY,
w,
h );
}
/**
* Adds a region relative to this item's content x/y start position.
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's content position
* @param y vertical start relative to this item's content position
* @param width width
* @param height height
* @see #getContentWidth()
* @see #getContentHeight()
*/
public void addRelativeToContentRegion(ClippingRegion repaintRegion, int x, int y, int width, int height) {
repaintRegion.addRegion(
getAbsoluteX() + this.contentX + x,
getAbsoluteY() + this.contentY + y,
width,
height
);
}
/**
* Adds a region relative to this item's background x/y start position.
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's background position
* @param y vertical start relative to this item's background position
* @param width width
* @param height height
* @see #getBackgroundWidth()
* @see #getBackgroundHeight()
*/
public void addRelativeToBackgroundRegion( ClippingRegion repaintRegion, int x, int y, int width, int height) {
repaintRegion.addRegion(
getAbsoluteX() + getBackgroundX() + x - 1,
getAbsoluteY() + getBackgroundY() + y - 1,
width + 2,
height + 2
);
}
/**
* Adds a region relative to this item's background x/y start position.
*
* @param animatedBackground the background that requests the repaint (could be a complete-background), can be null
* @param animatedBorder the border that requests the repaint (could be a complete-border), can be null
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's background position
* @param y vertical start relative to this item's background position
* @param width width
* @param height height
* @see #getBackgroundWidth()
* @see #getBackgroundHeight()
*/
public void addRelativeToBackgroundRegion( Background animatedBackground, Border animatedBorder, ClippingRegion repaintRegion, int x, int y, int width, int height) {
//#if polish.css.complete-background || polish.css.complete-border
boolean addAbsolute = false;
//#if polish.css.complete-background
addAbsolute = (this.completeBackground != null && animatedBackground == this.completeBackground);
//#endif
//#if polish.css.complete-border
addAbsolute |= (this.completeBorder != null && animatedBorder == this.completeBorder);
//#endif
if (addAbsolute) {
//System.out.println("adding absolute repaint: bgX=" + getBackgroundX() + ", bgY=" + getBackgroundY() + ", itemHeight-bgHeight=" + (this.itemHeight - this.backgroundHeight) + ", itemWidth-bgWidth=" + (this.itemWidth - this.backgroundWidth));
int padding = this.completeBackgroundPadding.getValue(this.availContentWidth);
repaintRegion.addRegion(
getAbsoluteX() + x - 1 - padding,
getAbsoluteY() + y - 1 - padding,
width + 2 + (padding << 1),
height + 2 + (this.itemHeight - this.backgroundHeight) + (padding << 1)
);
} else {
//#endif
repaintRegion.addRegion(
getAbsoluteX() + getBackgroundX() + x - 1,
getAbsoluteY() + getBackgroundY() + y - 1,
width + 2,
height + 2
);
//#if polish.css.complete-background || polish.css.complete-border
}
//#endif
}
/**
* Animates this item.
* Subclasses can override this method to create animations.
* The default implementation animates the background and the item view if present.
*
* @param currentTime the current time in milliseconds
* @param repaintRegion the repaint area that needs to be updated when this item is animated
* @see #addRelativeToContentRegion(ClippingRegion, int, int, int, int)
*/
public void animate( long currentTime, ClippingRegion repaintRegion) {
if (this.label != null) {
this.label.animate( currentTime, repaintRegion );
}
if (this.background != null) {
this.background.animate( this.screen, this, currentTime, repaintRegion );
}
if (this.border != null) {
this.border.animate( this.screen, this, currentTime, repaintRegion );
}
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.animate( this.screen, this, currentTime, repaintRegion );
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.animate( this.screen, this, currentTime, repaintRegion );
}
//#endif
if (animate()) {
addRepaintArea(repaintRegion);
}
//#if polish.css.view-type
if (this.view != null) {
this.view.animate(currentTime, repaintRegion);
}
//#endif
//#if tmp.supportTouchGestures
if (this.isPressed && (this.gestureStartTime != 0) && (currentTime - this.gestureStartTime > 500)) {
boolean handled = handleGesture( GestureEvent.GESTURE_HOLD, this.gestureStartX, this.gestureStartY );
if (handled) {
this.isIgnorePointerReleaseForGesture = true;
notifyItemPressedEnd();
this.gestureStartTime = 0;
Screen scr = getScreen();
repaintRegion.addRegion( scr.contentX, scr.contentY, scr.contentWidth, scr.contentHeight );
} else {
this.gestureStartTime = 0;
}
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands && this.commandsContainer != null) {
this.commandsContainer.animate(currentTime, repaintRegion);
}
//#endif
}
/**
* Animates this item.
* Subclasses can override this method to create animations.
* The default implementation returns false
*
* @return true when this item has been animated.
* @see #animate(long, ClippingRegion)
*/
public boolean animate() {
return false;
}
/**
* Retrieves the approriate style for focusing this item.
* This is either a item specific one or one inherit by its parents.
* When no parent has a specific focus style, the StyleSheet.focusedStyle is used.
*
* @return the style used for focussing this item.
*/
public Style getFocusedStyle() {
if (!this.isStyleInitialised) {
if (this.style != null) {
setStyle( this.style );
}
//#ifdef polish.useDynamicStyles
else {
initStyle();
}
//#endif
}
Style focStyle;
if (this.focusedStyle != null) {
focStyle = this.focusedStyle;
} else if (this.parent != null) {
focStyle = this.parent.getFocusedStyle();
} else {
focStyle= StyleSheet.focusedStyle;
}
//#if polish.css.visited-style
if (this.hasBeenVisited && focStyle != null) {
Style visitedStyle = (Style) focStyle.getObjectProperty("visited-style");
//#debug
System.out.println("found visited style " + (visitedStyle != null ? visitedStyle.name : "<none>") + " in " + focStyle.name);
if (visitedStyle != null) {
focStyle = visitedStyle;
}
}
//#endif
return focStyle;
}
//#if polish.hasPointerEvents
/**
* Handles the behavior of the virtual keyboard when the item is focused.
* By default, the virtual keyboard is hidden. Components which need to have the virtual keyboard
* shown when they are focused can override this method.
*/
public void handleOnFocusSoftKeyboardDisplayBehavior() {
DeviceControl.hideSoftKeyboard();
}
//#endif
/**
* Focuses this item.
*
* @param newStyle the style which is used to indicate the focused state
* @param direction the direction from which this item is focused,
* either Canvas.UP, Canvas.DOWN, Canvas.LEFT, Canvas.RIGHT or 0.
* When 0 is given, the direction is unknown.
* @return the current style of this item
*/
protected Style focus( Style newStyle, int direction ) {
//#debug
System.out.println("focus " + this);
Style oldStyle = this.style;
if ((!this.isFocused) || (newStyle != this.style && newStyle != null)) {
if (!this.isStyleInitialised && oldStyle != null) {
setStyle( oldStyle );
}
if (newStyle == null) {
newStyle = getFocusedStyle();
}
//#if polish.css.view-type
this.preserveViewType = true;
//#endif
this.isFocused = true;
this.isJustFocused = true;
setStyle( newStyle );
//#if polish.css.pressed-style
if (this.isPressed) {
this.normalStyle = newStyle;
}
//#endif
//#if polish.css.view-type
this.preserveViewType = false;
//#endif
// now set any commands of this item:
if (this.commands != null) {
showCommands();
}
if (oldStyle == null) {
oldStyle = StyleSheet.defaultStyle;
}
//#if polish.android
if (this._androidView != null) {
this._androidView.requestFocus();
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_FOCUS, this, new Integer(direction));
//#endif
}
return oldStyle;
}
/**
* Removes the focus from this item.
*
* @param originalStyle the original style which will be restored.
*/
protected void defocus( Style originalStyle ) {
//#debug
System.out.println("defocus " + this + " with style " + (originalStyle != null ? originalStyle.name : "<no style>"));
if (this.isPressed) {
notifyItemPressedEnd();
}
this.backgroundYOffset = 0;
this.isFocused = false;
if (originalStyle != null) {
setStyle( originalStyle );
if (this.label != null) {
Style prevLabelStyle = this.label.style;
//#if polish.css.label-style
prevLabelStyle = (Style) originalStyle.getObjectProperty("label-style");
if (prevLabelStyle == null) {
prevLabelStyle = this.label.style;
}
//#endif
this.label.defocus(prevLabelStyle);
}
} else {
this.background = null;
this.border = null;
this.style = null;
}
// now remove any commands which are associated with this item:
if (this.commands != null) {
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
}
//#if polish.Item.ShowCommandsOnHold
this.isShowCommands = false;
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_DEFOCUS, this, null);
//#endif
}
/**
* Shows the commands on the screen.
*/
public void showCommands() {
COMMANDS.clear();
addCommands( COMMANDS );
Screen scr = getScreen();
if (scr != null) {
scr.setItemCommands( COMMANDS, this );
}
}
// /**
// * Shows the commands on the screen.
// *
// * @param commandsList an ArrayList with the commands from this item.
// */
// protected void showCommands(ArrayList commandsList) {
// addCommands(commandsList);
// if (this.commands != null) {
// commandsList.addAll( this.commands );
// }
// if (this.parent != null) {
// this.parent.showCommands(commandsList);
// } else {
// Screen scr = getScreen();
// if (scr != null) {
// scr.setItemCommands( commandsList, this );
// }
// }
// }
/**
* Adds all commands to the specified list.
*
* @param commandsList an ArrayList into which the commands from this item should be added.
*/
protected void addCommands( ArrayList commandsList) {
if (this.commands != null) {
commandsList.addAll( this.commands );
}
if (this.parent != null) {
this.parent.addCommands(commandsList);
}
}
/**
* Tries to handle the specified command.
* The item checks if the command belongs to this item and if it has an associated ItemCommandListener.
* Only then it handles the command.
* @param cmd the command
* @return true when the command has been handled by this item
*/
protected boolean handleCommand( Command cmd ) {
if (cmd == this.defaultCommand) {
notifyVisited();
}
if (cmd.commandAction(this, null)) {
return true;
}
ItemCommandListener listener = this.itemCommandListener;
if (this.commands == null || listener == null || !this.commands.contains(cmd) ) {
//#if polish.Item.suppressDefaultCommand
if (listener == null || cmd != this.defaultCommand) {
//#endif
return false;
//#if polish.Item.suppressDefaultCommand
}
//#endif
}
try {
listener.commandAction( cmd, this );
return true;
} catch (Exception e) {
//#debug error
System.out.println("Unable to handle command " + cmd.getLabel() + e );
}
return false;
}
//#if polish.LibraryBuild
/**
* Tries to handle the specified command.
* The item checks if the command belongs to this item and if it has an associated ItemCommandListener.
* Only then it handles the command.
* @param cmd the command
* @return true when the command has been handled by this item
*/
protected boolean handleCommand( javax.microedition.lcdui.Command cmd ) {
return false;
}
//#endif
/**
* Called by the system to notify the item that it is now at least
* partially visible, when it previously had been completely invisible.
* The item may receive <code>paint()</code> calls after
* <code>showNotify()</code> has been called.
*
* <p>The default implementation of this method sets the isShown field to true and calls showNotify on style elements.</p>
*/
protected void showNotify()
{
if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
}
this.isShown = true;
if (this.label != null) {
this.label.showNotify();
}
if (this.background != null) {
this.background.showNotify();
}
if (this.border != null) {
this.border.showNotify();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.showNotify();
}
//#endif
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.showNotify();
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.showNotify();
}
//#endif
//#if polish.blackberry
if (this.isFocused && this._bbField != null) {
Display.getInstance().notifyFocusSet(this);
}
//#endif
//#if polish.android
if (this._androidView != null) {
AndroidDisplay.getInstance().onShow(this._androidView, this);
}
//#endif
//#if tmp.handleEvents
//System.out.println("triggering event 'show' for " + this + " with style " + (this.style != null ? this.style.name : "<null>") + ", animations=" + (this.style != null ? "" + this.style.getAnimations() : "<null>"));
if (!this.hasBeenShownBefore) {
EventManager.fireEvent( EventManager.EVENT_SHOW_FIRST_TIME, this, null );
this.hasBeenShownBefore = true;
}
EventManager.fireEvent( EventManager.EVENT_SHOW, this, null );
//#endif
}
/**
* Called by the system to notify the item that it is now completely
* invisible, when it previously had been at least partially visible. No
* further <code>paint()</code> calls will be made on this item
* until after a <code>showNotify()</code> has been called again.
*
* <p>The default implementation of this method sets the isShown field to false and calls hideNotify on style elements.</p>
*/
protected void hideNotify()
{
this.isShown = false;
if (this.label != null) {
this.label.hideNotify();
}
if (this.background != null) {
this.background.hideNotify();
}
if (this.border != null) {
this.border.hideNotify();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.hideNotify();
}
//#endif
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.hideNotify();
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.hideNotify();
}
//#endif
if (this.isPressed) {
notifyItemPressedEnd();
}
//#if polish.android
if (this._androidView != null) {
AndroidDisplay.getInstance().onHide(this._androidView, this);
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_HIDE, this, null );
//#endif
}
/**
* Shows the screen to which item belongs to and focusses this item.
* This method is the equivalent to display.setCurrentItem( item ).
*
* @param display the display of the MIDlet.
*/
public void show( Display display ) {
Screen myScreen = getScreen();
if ( myScreen == null ) {
//#debug warn
System.out.println("Unable to show this item, since the screen is not known.");
return;
}
myScreen.focus( this );
display.setCurrent( myScreen );
}
/**
* Releases all (memory intensive) resources such as images or RGB arrays of this item.
* The default implementation releases any background resources.
*/
public void releaseResources() {
if (this.background != null) {
this.background.releaseResources();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.releaseResources();
}
//#endif
//#if polish.css.filter && polish.midp2
if (this.filters != null) {
for (int i=0; i<this.filters.length; i++) {
RgbFilter filter = this.filters[i];
filter.releaseResources();
}
}
//#endif
}
/**
* Destroy the item by removing all references to parent, screen, listeners etc.
* and calling releaseResources()
*/
public void destroy() {
releaseResources();
AnimationThread.removeAnimationItem(this);
if(null != this.itemCommandListener)
this.itemCommandListener = null;
if(null != this.itemStateListener)
this.itemStateListener = null;
if(null != this.parent)
this.parent = null;
if(null != this.screen)
this.screen = null;
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.destroy();
this.view = null;
}
//#endif
}
/**
* Sets an arbitrary attribute for this item.
*
* @param key the key for the attribute
* @param value the attribute value
*/
public void setAttribute( Object key, Object value ) {
if (this.attributes == null) {
this.attributes = new HashMap();
}
this.attributes.put( key, value );
}
/**
* Gets an previously added attribute of this item.
*
* @param key the key of the attribute
* @return the attribute value, null if none has been registered under the given key before
*/
public Object getAttribute( Object key ) {
if (this.attributes == null) {
return null;
}
return this.attributes.get( key );
}
/**
* Removes an previously added attribute of this item.
*
* @param key the key of the attribute
* @return the attribute value, null if none has been registered under the given key before
*/
public Object removeAttribute(Object key)
{
if (this.attributes == null) {
return null;
}
return this.attributes.remove( key );
}
/**
* Returns a HashMap object with all registered attributes.
*
* @return a HashMap object with all attribute key/value pairs, null if no attribute was stored before.
*/
public HashMap getAttributes() {
return this.attributes;
}
/**
* Determines if this item or one of it's children is within the specified point.
* The default implementation returns this item or this item's label when the position fits.
*
* @param relX the x position of the point relative to this item's left position
* @param relY the y position of the point relative to this item's top position
* @return this item or one of it's children, when the position fits, otherwise null is returned
*/
public Item getItemAt( int relX, int relY ) {
if ( isInItemArea(relX, relY) ) {
if (this.label != null) {
Item item = this.label.getItemAt(relX, relY);
if (item != null) {
return item;
}
}
return this;
}
return null;
}
/**
* Retrieves this item's current absolute horizontal position
*
* @return the absolute x position of this item in pixel.
*/
public int getAbsoluteX() {
int absX = this.relativeX;
// if (this.label != null && this.useSingleRow && !this.isLayoutCenter && !this.isLayoutRight) {
// // hack for left align with additional label:
// absX += this.contentX;
// }
Item item = this.parent;
if (item != null && item.label == this && item.useSingleRow) {
// this is the label of another item
absX -= item.contentX;
}
//#if polish.css.x-adjust
if (this.xAdjustment != null) {
int value = this.xAdjustment.getValue(this.itemWidth);
absX += value;
}
//#endif
while (item != null) {
absX += item.relativeX + item.contentX;
item = item.parent;
}
return absX;
}
/**
* Retrieves this item's current absolute vertical position
*
* @return the absolute y position of this item in pixel.
*/
public int getAbsoluteY() {
int absY = this.relativeY; // + this.contentY; in that case no label is included anymore
Item item = this.parent;
if (item != null && item.label == this) {
absY -= item.contentY;
}
//#if polish.css.y-adjust
if (this.yAdjustment != null) {
absY += this.yAdjustment.getValue(this.itemHeight);
}
//#endif
while (item != null) {
absY += item.relativeY + item.contentY;
if (item instanceof Container) {
absY += ((Container)item).yOffset;
}
item = item.parent;
}
return absY;
}
/**
* Sets the absolute vertical position of this item.
* Note that results may vary depending on the view-type of the root container.
*
* @param absY the absolute y position of this item in pixel.
*/
public void setAbsoluteY(int absY) {
// find out vertical offset for root container:
int currentAbsY = getAbsoluteY();
int diff = absY - currentAbsY;
//System.out.println("setting absY to " + absY + ", current=" + currentAbsY + ", diff=" + diff + " for item " + this);
Item item = this;
while (item.parent != null) {
item = item.parent;
}
if (item instanceof Container) {
Container container = (Container)item;
int offset = container.getScrollYOffset() + diff;
//System.out.println("resulting in scrollOffset=" + offset + ", currentScrollOffset=" + container.getScrollYOffset());
container.setScrollYOffset(offset, false);
}
//System.out.println("after setAbsoluteY=" + getAbsoluteY() + ", should be=" + absY);
}
/**
* Retrieves the start of the content relative to this item's absolute x position.
* @return the horizontal start of the content
* @see #getAbsoluteX()
*/
public int getContentX() {
return this.contentX;
}
/**
* Retrieves the start of the content relative to this item's absolute y position.
* @return the vertical start of the content
* @see #getAbsoluteY()
*/
public int getContentY() {
return this.contentY;
}
/**
* Retrieves the width of the content.
* @return the content width in pixels
*/
public int getContentWidth()
{
return this.contentWidth;
}
/**
* Retrieves the height of the content.
* @return the content height in pixels
*/
public int getContentHeight()
{
return this.contentHeight;
}
/**
* Retrieves the width of the content.
* @return the content width in pixels
*/
public int getAvailableContentWidth()
{
return this.availContentWidth;
}
/**
* Retrieves the height of the content.
* @return the content height in pixels
*/
public int getAvailableContentHeight()
{
return this.availContentHeight;
}
/**
* Retrieves the height of the area that this item covers.
* This can be different from the original itemHeight for items that have popups such as the POPUP ChoiceGroup
* @return the height of the item's area in pixel
*/
public int getItemAreaHeight()
{
return Math.max( this.itemHeight, this.marginTop + this.backgroundHeight + this.marginBottom );
}
/**
* Retrieves the start of the background relative to this item's origin.
*
* @return the horizontal background start in pixels.
*/
public int getBackgroundX() {
//#if polish.css.include-label
if (this.includeLabel) {
return this.marginLeft;
} else {
//#endif
return this.contentX - this.paddingLeft;
//#if polish.css.include-label
}
//#endif
}
/**
* Retrieves the start of the background relative to this item's origin.
*
* @return the horizontal background start in pixels.
*/
public int getBackgroundY() {
//#if polish.css.include-label
if (this.includeLabel) {
return this.marginTop;
} else {
//#endif
return this.contentY - this.paddingTop;
//#if polish.css.include-label
}
//#endif
}
/**
* Retrieves the width of this item's background.
* @return the width in pixels
*/
public int getBackgroundWidth() {
return this.backgroundWidth;
}
/**
* Retrieves the height of this item's background.
* @return the height in pixels
*/
public int getBackgroundHeight() {
return this.backgroundHeight;
}
/**
* Retrieves the parent of this item.
*
* @return this item's parent.
*/
public Item getParent() {
return this.parent;
}
/**
* Retrieves the parent root of this item.
*
* @return this item's super parent, either this item itself or it's last known ancestor.
*/
public Item getParentRoot() {
Item p = this;
while (p.parent != null) {
p = p.parent;
}
return p;
}
/**
* Sets a parent for this item.
* @param parent the parent of this item
*/
public void setParent(Item parent)
{
this.parent = parent;
}
//#if polish.midp
/**
* Sets a parent for this item.
* @param parent the parent of this item
*/
public void setParent(javax.microedition.lcdui.Item parent)
{
// ignore
}
//#endif
/**
* Sets the visible status of this item.
* Invisible items occupy no space on the UI screen and cannot be focused/traversed.
* Note that you can call this method ONLY when the preprocessing variable polish.supportInvisibleItems is true or when you use the CSS attribute 'visible' in your polish.css file.
* @param visible true when this item should become visible.
*/
public void setVisible( boolean visible ) {
//#if tmp.invisible
boolean invisible = !visible;
if (invisible == this.isInvisible) {
return;
}
// if (visible) {
// System.out.println("+++ SETTING VISIBLE: " + this );
// } else {
// System.out.println("--- SETTING INVISIBLE: " + this );
// }
if (this.parent instanceof Container) {
Container parentContainer = (Container) this.parent;
if (invisible && this.isFocused) {
//System.out.println("making focused item invisible: " + this);
// remove any item commands:
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
int itemIndex = parentContainer.indexOf( this );
boolean isFocusSet = parentContainer.focusClosestItemAbove( itemIndex );
this.isFocused = false;
//System.out.println("new focus set: " + isFocusSet + ", new index=" + parentContainer.focusedIndex + ", this.index=" + itemIndex );
if (isFocusSet) {
if (parentContainer.focusedIndex > itemIndex ) {
// focused has moved downwards, since the above item is now invisible,
// adjust the scrolling accordingly:
int offset = parentContainer.yOffset + this.itemHeight + parentContainer.paddingVertical;
if (offset > 0) {
offset = 0;
}
//System.out.println("setting parent scroll offset to " + offset );
parentContainer.setScrollYOffset( offset, false );
} else {
parentContainer.scroll( 0, parentContainer.focusedItem, true);
}
} else {
parentContainer.focusChild(-1);
}
if (this instanceof Container) {
((Container)this).focusChild(-1);
}
} else if (!this.isFocused && parentContainer.focusedIndex > parentContainer.indexOf(this)) {
// adjust scrolling so that the focused element of the parent container stays in the current position:
int offset;
if (invisible) {
offset = parentContainer.getScrollYOffset() + this.itemHeight;
if (offset > 0) {
offset = 0;
}
//System.out.println("invisible: adjusting yScrollOffset with itemHeight=" + this.itemHeight + " to " + (offset > 0 ? 0 : offset) );
parentContainer.setScrollYOffset( offset, false );
} else {
int height = this.invisibleItemHeight;
if (height == 0 && this.parent != null) {
//System.out.println("visible getting height for available width of " + this.parent.contentWidth );
this.isInvisible = false;
setInitialized(false);
height = getItemHeight( this.parent.contentWidth, this.parent.contentWidth, this.parent.contentHeight );
} else {
this.itemHeight = height;
}
offset = parentContainer.getScrollYOffset() - height;
//System.out.println("visible: adjusting yScrollOffset with height=" + height + " to " + offset );
parentContainer.setScrollYOffset( offset, false );
}
// adjust the internal Y position:
Item parentItem = this;
while (parentItem != null) {
if (parentItem.internalX != NO_POSITION_SET) {
if (invisible) {
parentItem.internalY -= this.itemHeight;
} else {
parentItem.internalY += this.itemHeight;
}
}
parentItem = parentItem.parent;
}
} else if (parentContainer.focusedIndex == -1)
{
if(visible)
{
//No other container is set to focused
//so it is ASSUMED that this is the only
//visisble item
this.relativeY = 0;
parentContainer.setScrollYOffset(0);
parentContainer.focusChild(parentContainer.indexOf(this));
}
}
}
if ( invisible ) {
this.invisibleAppearanceModeCache = this.appearanceMode;
this.invisibleItemHeight = this.itemHeight;
this.appearanceMode = PLAIN;
} else {
this.appearanceMode = this.invisibleAppearanceModeCache;
}
this.isInvisible = invisible;
requestInit();
//#endif
}
/**
* Gets the visible status of this item.
* Invisible items occupy no space on the UI screen and cannot be focused/traversed.
* Note that you can call this method ONLY when the preprocessing variable polish.supportInvisibleItems is true or when you use the 'visible' CSS attribute.
* @return true when this item is visible.
*/
public boolean isVisible() {
boolean result;
//#if !tmp.invisible
result = false;
//#else
result = !this.isInvisible;
//#endif
return result;
}
//#if polish.debug.error || polish.keepToString
/**
* Generates a String representation of this item.
* This method is only implemented when the logging framework is active or the preprocessing variable
* "polish.keepToString" is set to true.
* @return a String representation of this item.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
if (this.label != null && this.label.text != null) {
buffer.append( '"' ).append( this.label.text ).append("\"");
}
if (this.style != null) {
buffer.append(" [").append(this.style.name).append("]");
}
buffer.append(": ");
buffer.append( super.toString() );
return buffer.toString();
}
//#endif
/**
* Determines whether this item contains the given command.
*
* @param command the command
* @return true when this item contains this command
*/
public boolean containsCommand(Command command) {
return this.commands != null && this.commands.contains(command);
}
/**
* @return the default command
*/
public Command getDefaultCommand() {
return this.defaultCommand;
}
/**
* @return the commands associated with this item in an arraylist - might be null!
*/
public ArrayList getItemCommands() {
return this.commands;
}
/**
* Sets the initialized state of this item.
* @param initialized true when this item is deemed to be initialized, otherwise false. When setting to 'false' the item will run its init() and initContent() methods at the next option.
*/
public void setInitialized(boolean initialized)
{
this.isInitialized = initialized;
}
/**
* Determines the initialization state of this item
* @return true when it is initialized, false otherwise
*/
public boolean isInitialized()
{
return this.isInitialized;
}
/**
* Sets the item's complete height
* @param height the height in pixel
*/
public void setItemHeight( int height ) {
int diff = height - this.itemHeight;
//#debug
System.out.println("setting item height " + height + ", diff=" + diff + ", vcenter=" +isLayoutVerticalCenter() + " for " + this );
this.itemHeight = height;
this.backgroundHeight += diff;
if (isLayoutVerticalCenter()) {
this.contentY += diff/2;
} else if (isLayoutBottom()) {
this.contentY += diff;
}
}
/**
* Sets the item's complete width
* @param width the width in pixel
*/
public void setItemWidth( int width ) {
int diff = width - this.itemWidth;
//#debug
System.out.println("setting item width " + width + ", diff=" + diff + ", hcenter=" +isLayoutCenter() + " for " + this );
this.itemWidth = width;
this.backgroundWidth += diff;
if (isLayoutCenter()) {
this.contentX += diff/2;
} else if (isLayoutRight()) {
this.contentX += diff;
}
}
/**
* Retrieves the internal area's horizontal start relative to this item's content area
* @return the horizontal start in pixels, -1 if it not set
*/
public int getInternalX() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalX;
}
/**
* Retrieves the internal area's vertical start relative to this item's content area
* @return the vertical start in pixels, -1 if it not set
*/
public int getInternalY() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalY;
}
/**
* Retrieves the internal area's vertical width
* @return the vertical width in pixels, -1 if it not set
*/
public int getInternalWidth() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalWidth;
}
/**
* Retrieves the internal area's vertical height
* @return the vertical height in pixels, -1 if it not set
*/
public int getInternalHeight() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalHeight;
}
/**
* Fires an event for this item as well as its subitems like its label.
*
* @param eventName the name of the event
* @param eventData the event data
* @see EventManager#fireEvent(String, Object, Object)
*/
public void fireEvent( String eventName, Object eventData ) {
if (this.label != null) {
EventManager.fireEvent(eventName, this.label, eventData);
}
EventManager.fireEvent(eventName, this, eventData);
}
/**
* Updates the internal area on BB and similar platforms that contain native fields.
*/
public void updateInternalArea() {
// subclasses may override this.
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a right layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutRight()
{
return this.isLayoutRight;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a left layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutLeft()
{
return !(this.isLayoutRight | this.isLayoutCenter);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a center layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutCenter()
{
return this.isLayoutCenter;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a top layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutTop()
{
return (this.layout & LAYOUT_BOTTOM) == 0;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a bottom layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutBottom()
{
return ((this.layout & LAYOUT_VCENTER) == LAYOUT_BOTTOM);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vcenter layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalCenter()
{
return ((this.layout & LAYOUT_VCENTER) == LAYOUT_VCENTER);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vshrink layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalShrink() {
return ((this.layout & LAYOUT_VSHRINK) == LAYOUT_VSHRINK);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vexpand layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalExpand() {
return ((this.layout & LAYOUT_VEXPAND) == LAYOUT_VEXPAND);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a horizontal expand layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutExpand() {
return ((this.layout & LAYOUT_EXPAND) == LAYOUT_EXPAND);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a horizontal shrink layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutShrink() {
return ((this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a newwline-after layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutNewlineAfter() {
return ((this.layout & LAYOUT_NEWLINE_AFTER) == LAYOUT_NEWLINE_AFTER);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a newwline-after layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutNewlineBefore() {
return ((this.layout & LAYOUT_NEWLINE_BEFORE) == LAYOUT_NEWLINE_BEFORE);
}
public void setItemTransition( ItemTransition transition ) {
this.itemTransition = transition;
}
public Image toImage() {
Image img;
//#if polish.midp2
int[] pixels = new int[ this.itemWidth * this.itemHeight ];
img = Image.createRGBImage( pixels, this.itemWidth, this.itemHeight, true );
//#else
img = Image.createImage( this.itemWidth, this.itemHeight );
//#endif
Graphics g = img.getGraphics();
ItemTransition t = this.itemTransition;
this.itemTransition = null;
paint( 0, 0, 0, this.itemWidth, g );
this.itemTransition = t;
return img;
}
public RgbImage toRgbImage() {
return new RgbImage( toImage(), true );
}
/**
* Determines whether this item is interactive and thus can be selected.
* @return true when this item is deemed to be interactive
*/
public boolean isInteractive() {
return this.appearanceMode != PLAIN;
}
/**
* Resets the style of this item and all its children (if any).
* This is useful when you have applied changes to this Item's style or one of its elements.
* @param recursive true when all subelements of this Item should reset their style as well.
* @see Screen#resetStyle(boolean)
* @see UiAccess#resetStyle(Screen,boolean)
* @see UiAccess#resetStyle(Item,boolean)
*/
public void resetStyle(boolean recursive) {
if (this.style != null) {
setStyle(this.style);
}
if (recursive) {
if (this.label != null) {
this.label.resetStyle(recursive);
}
}
}
/**
* Notifies this item about a new screen size.
* The default implementation just checks if the design should switch to portrait or landscape-style (if those CSS attributes are used).
* The item will be re-initialized with its available dimensions using init(int,int,int) soon.
* @param screenWidth the screen width
* @param screenHeight the screen height
*/
public void onScreenSizeChanged( int screenWidth, int screenHeight ) {
//#debug
System.out.println("onScreenSizeChanged to " + screenWidth + ", " + screenHeight + " for " + this);
if (this.label != null) {
this.label.onScreenSizeChanged(screenWidth, screenHeight);
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.onScreenSizeChanged(screenWidth, screenHeight);
}
//#endif
//#if polish.css.portrait-style || polish.css.landscape-style
if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
}
Style newStyle = null;
if (screenWidth > screenHeight) {
if (this.landscapeStyle != null && this.style != this.landscapeStyle) {
newStyle = this.landscapeStyle;
}
} else if (this.portraitStyle != null && this.style != this.portraitStyle){
newStyle = this.portraitStyle;
}
Style oldStyle = null;
if (newStyle != null) {
//#debug
System.out.println("onScreenSizeChanged(): setting new style " + newStyle.name + " for " + this);
oldStyle = this.style;
setStyle( newStyle );
//#if polish.css.pressed-style
if (this.isPressed) {
this.normalStyle = newStyle;
}
//#endif
if (this.isFocused) {
if (this.parent instanceof Container) {
Container cont = (Container)this.parent;
cont.itemStyle = newStyle;
setStyle( getFocusedStyle() );
}
} else if (oldStyle != null && this.parent instanceof Container) {
Container cont = (Container)this.parent;
if (cont.itemStyle == oldStyle) {
cont.itemStyle = newStyle;
}
}
}
//#endif
}
/**
* Retrieves the available width for this item.
* @return the available width in pixel, can be 0 when this item has not yet been initialized
*/
public int getAvailableWidth() {
return this.availableWidth;
}
/**
* Retrieves the available height for this item.
* @return the available height in pixel, can be 0 when this item has not yet been initialized
*/
public int getAvailableHeight() {
return this.availableHeight;
}
/**
* Sets an UiEventListener for the this item and its children.
* @param listener the listener, use null to remove a listener
*/
public void setUiEventListener(UiEventListener listener) {
this.uiEventListener = listener;
}
/**
* Retrieves the UiEventListener for this item or for one of its parents.
* @return the listener or null, if none has been registered
*/
public UiEventListener getUiEventListener() {
UiEventListener listener = this.uiEventListener;
if (listener == null) {
Item parentItem = this.parent;
while (parentItem != null && listener == null) {
listener = parentItem.uiEventListener;
parentItem = parentItem.parent;
}
if (listener == null) {
listener = getScreen().getUiEventListener();
}
}
return listener;
}
/**
* Retrieves the RGB data of this item.
* This method only works on MIDP 2.0+ devices.
*
* @return the RGB data as an int array.
*/
public int[] getRgbData() {
return getRgbData( true, 255 );
}
/**
* Retrieves the RGB data of this item.
* This method only works on MIDP 2.0+ devices.
*
* @param supportTranslucency true when not only transparent but also translucent parts of the item should be rendered correctly
* @param rgbOpacity The opacity of the item between 0 (fully transparent) and 255 (fully opaque)
* @return the RGB data as an int array.
*/
public int[] getRgbData( boolean supportTranslucency, int rgbOpacity ) {
int[] result = new int[0];
//#if polish.midp2
if (this.itemWidth < 1 || this.itemHeight < 1) {
//#debug error
System.out.println("Unable to retrieve RGB data for item with a dimension of " + this.itemWidth + "x" + this.itemHeight + " for " + this );
return new int[0];
}
Image image = Image.createImage( this.itemWidth, this.itemHeight );
if (supportTranslucency) {
// we use a two-pass painting for determing translucent pixels as well:
// in the first run we paint it on a black background (dataBlack),
// in the second we use a white background (dataWhite).
// We then compare the pixels in dataBlack and dataWhite:
// a) when a pixel is black in dataBlack and white and dataWhite it is fully transparent
// b) when a pixel has the same value in dataBlack and in dataWhite it is fully opaque
// c) when the pixel has different values it contains translucency - we can extract the original value from the difference between data1 and data2.
// The solution is based on this formula for determining the final green component value when adding a pixel with alpha value on another opaque pixel:
// final_green_value = ( pixel1_green * alpha + pixel2_green * ( 255 - alpha ) ) / 255
// When can work our way backwards to determine the original green and alpha values.
Graphics g = image.getGraphics();
int bgColorBlack = 0x0;
g.setColor(bgColorBlack);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
int[] transparentColorRgb = new int[1];
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
bgColorBlack = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] dataBlack = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(dataBlack, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
int bgColorWhite = 0xffffff;
g.setColor(bgColorWhite);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
bgColorWhite = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] dataWhite = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(dataWhite, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
rgbOpacity = (rgbOpacity << 24) | (0x00ffffff);
result = new int[ dataBlack.length ];
int lastPixelWhite = 0;
int lastPixelBlack = 0;
int lastPixelResult = 0;
// ensure transparent parts are indeed transparent
for (int i = 0; i < dataBlack.length; i++) {
int pixelBlack = dataBlack[i];
int pixelWhite = dataWhite[i];
if (pixelBlack == pixelWhite) {
result[i] = pixelBlack & rgbOpacity;
} else if (pixelBlack != bgColorBlack || pixelWhite != bgColorWhite ) {
if (pixelBlack == lastPixelBlack && pixelWhite == lastPixelWhite) {
result[i] = lastPixelResult;
} else {
// this pixel contains translucency:
int redBlack = (pixelBlack & 0xff0000) >> 16;
int greenBlack = (pixelBlack & 0xff00) >> 8;
int blueBlack = (pixelBlack & 0xff);
int redWhite = (pixelWhite & 0xff0000) >> 16;
int greenWhite = (pixelWhite & 0xff00) >> 8;
int blueWhite = (pixelWhite & 0xff);
int originalAlpha = 0;
int originalRed;
if (redBlack == 0 && redWhite == 255) {
originalRed = 0;
} else {
if (redBlack == 0) {
redBlack = 1;
} else if (redWhite == 255) {
redWhite = 254;
}
originalRed = (255 * redBlack) / (redBlack - redWhite + 255);
originalAlpha = redBlack - redWhite + 255;
}
int originalGreen;
if (greenBlack == 0 && greenWhite == 255) {
originalGreen = 0;
} else {
if (greenBlack == 0) {
greenBlack = 1;
} else if (greenWhite == 255) {
greenWhite = 254;
}
originalGreen = (255 * greenBlack) / (greenBlack - greenWhite + 255);
originalAlpha = greenBlack - greenWhite + 255;
}
int originalBlue;
if (blueBlack == 0 && blueWhite == 255) {
originalBlue = 0;
} else {
if (blueBlack == 0) {
blueBlack = 1;
} else if (blueWhite == 255) {
blueWhite = 254;
}
originalBlue = (255 * blueBlack) / (blueBlack - blueWhite + 255);
originalAlpha = blueBlack - blueWhite + 255;
}
+ if ( originalAlpha > 255 ) {
+ originalAlpha = 255;
+ }
lastPixelWhite = pixelWhite;
lastPixelBlack = pixelBlack;
lastPixelResult = ((originalAlpha << 24) | (originalRed << 16) | (originalGreen << 8) | originalBlue) & rgbOpacity;
result[i] = lastPixelResult;
}
}
}
} else {
int transparentColor = 0x12345678;
Graphics g = image.getGraphics();
g.setColor(transparentColor);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
int[] transparentColorRgb = new int[1];
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
transparentColor = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] itemRgbData = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(itemRgbData, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
boolean addOpacity = (rgbOpacity != 255);
rgbOpacity = (rgbOpacity << 24) | (0x00ffffff);
// ensure transparent parts are indeed transparent
for (int i = 0; i < itemRgbData.length; i++) {
int data = itemRgbData[i];
if( data == transparentColor ) {
itemRgbData[i] = 0;
} else if (addOpacity) {
itemRgbData[i] = data & rgbOpacity;
}
}
}
//#endif
return result;
}
/**
* Fires a cycle event.
* The default implementation forwards the event to the cycle listener if one is registered, otherwise it will be forwarded to the parent item.
* When there is neither a parent item or a cycle listener, this method will return true.
*
* @param direction the direction, e.g. CycleListener.DIRECTION_BOTTOM_TO_TOP
* @return true when the cycling process can continue, false when the cycle event should be aborted
* @see CycleListener#DIRECTION_BOTTOM_TO_TOP
* @see CycleListener#DIRECTION_TOP_TO_BOTTOM
* @see CycleListener#DIRECTION_LEFT_TO_RIGHT
* @see CycleListener#DIRECTION_RIGHT_TO_LEFT
* @see #setCycleListener(CycleListener)
* @see #getCycleListener()
*/
public boolean fireContinueCycle( int direction ) {
if (this.cycleListener != null) {
return this.cycleListener.onCycle(this, direction);
}
if (this.parent != null) {
return this.parent.fireContinueCycle(direction);
}
return true;
}
/**
* Allows to specify a cycle listener
* @param listener the listener, use null to deregister the listener
* @see #getCycleListener()
*/
public void setCycleListener( CycleListener listener ) {
this.cycleListener = listener;
}
/**
* Retrieves the cycle listener
* @return the currently registered cycle listener
* @see #setCycleListener(CycleListener)
*/
public CycleListener getCycleListener() {
return this.cycleListener;
}
//#if polish.useNativeGui
/**
* Species a native implementation for this item.
* This method is only available when the preprocessing variable polish.useNativeGui is set to true.
* @param nativeItem the native implementation
*/
public void setNativeItem( NativeItem nativeItem ) {
this.nativeItem = nativeItem;
}
//#endif
//#if polish.useNativeGui
/**
* Species a native implementation for this item.
* This method is only available when the preprocessing variable polish.useNativeGui is set to true.
* @return the native implementation, can be null
*/
public NativeItem getNativeItem() {
return this.nativeItem;
}
//#endif
//#ifdef polish.Item.additionalMethods:defined
//#include ${polish.Item.additionalMethods}
//#endif
}
| true | true | public boolean isInItemArea( int relX, int relY ) {
if (relY < 0 || relY > this.itemHeight || relX < 0 || relX > this.itemWidth) { //Math.max(this.itemWidth, this.contentX + this.contentWidth)) {
//#debug
System.out.println("isInItemArea(" + relX + "," + relY + ") = false: itemWidth=" + this.itemWidth + ", itemHeight=" + this.itemHeight + " (" + this + ")");
return false;
}
//#debug
System.out.println("isInItemArea(" + relX + "," + relY + ") = true: itemWidth=" + this.itemWidth + ", itemHeight=" + this.itemHeight + " (" + this + ")");
return true;
}
/**
* Determines whether the given relative x/y position is inside of the specified child item's area including paddings, margins and label.
* Subclasses which extend their area over the declared/official content area, which is determined
* in the initContent() method (like popup items), might want to override this method.
* It is assumed that the item has been initialized before.
*
* @param relX the x position relative to this item's left content position
* @param relY the y position relative to this item's top content position
* @param child the child
* @return true when the relX/relY coordinate is within the child item's area.
*/
public boolean isInItemArea( int relX, int relY, Item child ) {
if (child != null) {
return child.isInItemArea(relX - child.relativeX, relY - child.relativeY);
}
return false;
}
/**
* Handles the event when a pointer has been pressed at the specified position.
* The default method discards this event when relX/relY is outside of the item's area.
* When the event took place inside of the content area, the pointer-event is translated into an artificial
* FIRE game-action keyPressed event, which is subsequently handled
* by the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the pressing of the pointer was actually handled by this item.
* @see #isInItemArea(int, int) this method is used for determining whether the event belongs to this item
* @see #isInContentArea(int, int) for a helper method for determining whether the event took place into the actual content area
* @see #handleKeyPressed(int, int)
* @see #contentX for calculating the horizontal position relative to the content (relX - contentX)
* @see #contentY for calculating the vertical position relative to the content (relY - contentY)
*/
protected boolean handlePointerPressed( int relX, int relY ) {
//#ifdef polish.hasPointerEvents
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
Container cmdCont = this.commandsContainer;
if (cmdCont != null && cmdCont.handlePointerPressed(relX - cmdCont.relativeX, relY - cmdCont.relativeY)) {
return true;
}
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerPressed(relX, relY)) {
return true;
}
//#endif
if ( isInItemArea(relX, relY) ) {
//#if tmp.supportTouchGestures
this.gestureStartTime = System.currentTimeMillis();
this.gestureStartX = relX;
this.gestureStartY = relY;
//#endif
return handleKeyPressed( 0, Canvas.FIRE );
}
//#if polish.Item.ShowCommandsOnHold
else {
this.gestureStartTime = 0;
if (this.isShowCommands) {
this.isShowCommands = false;
return true;
}
}
//#endif
//#endif
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handlePointerPressed(relX, relY);
}
//#endif
return false;
}
/**
* Handles the event when a pointer has been released at the specified position.
* The default method discards this event when relX/relY is outside of the item's area.
* When the event took place inside of the content area, the pointer-event is translated into an artificial
* FIRE game-action keyReleased event, which is subsequently handled
* bu the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the pressing of the pointer was actually handled by this item.
* @see #isInItemArea(int, int) this method is used for determining whether the event belongs to this item
* @see #isInContentArea(int, int) for a helper method for determining whether the event took place into the actual content area
* @see #handleKeyPressed(int, int)
* @see #contentX for calculating the horizontal position relative to the content (relX - contentX)
* @see #contentY for calculating the vertical position relative to the content (relY - contentY)
*/
protected boolean handlePointerReleased( int relX, int relY ) {
//#ifdef polish.hasPointerEvents
//#debug
System.out.println("handlePointerReleased " + relX + ", " + relY + " for item " + this + " isPressed=" + this.isPressed);
// handle keyboard behaviour only if this not a container,
// its handled in the overwritten version
if (this.isJustFocused) {
this.isJustFocused = false;
handleOnFocusSoftKeyboardDisplayBehavior();
}
//#if tmp.supportTouchGestures
if (this.isIgnorePointerReleaseForGesture) {
this.isIgnorePointerReleaseForGesture = false;
return true;
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
this.commandsContainer.handlePointerReleased(relX - this.commandsContainer.relativeX, relY - this.commandsContainer.relativeY);
this.isShowCommands = false;
notifyItemPressedEnd();
return true;
}
//#endif
//#if tmp.supportTouchGestures
int verticalDiff = Math.abs( relY - this.gestureStartY );
if (verticalDiff < 20) {
int horizontalDiff = relX - this.gestureStartX;
if (horizontalDiff > this.itemWidth/2) {
if (handleGesture(GestureEvent.GESTURE_SWIPE_RIGHT, relX, relY)) {
return true;
}
} else if (horizontalDiff < -this.itemWidth/2) {
if (handleGesture(GestureEvent.GESTURE_SWIPE_LEFT, relX, relY)) {
return true;
}
}
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerReleased(relX, relY)) {
return true;
}
//#endif
if ( isInItemArea(relX, relY) ) {
return handleKeyReleased( 0, Canvas.FIRE );
} else if (this.isPressed) {
notifyItemPressedEnd();
return true;
}
//#endif
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handlePointerReleased(relX, relY);
}
//#endif
return false;
}
/**
* Handles the dragging/movement of a pointer.
* This method should be overwritten only when the polish.hasPointerEvents
* preprocessing symbol is defined.
* The default implementation returns false.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the dragging of the pointer was actually handled by this item.
*/
protected boolean handlePointerDragged(int relX, int relY, ClippingRegion repaintRegion)
{
boolean handled = false;
//#ifdef polish.hasPointerEvents
//#if tmp.supportTouchGestures
if (this.gestureStartTime != 0 && Math.abs( relX - this.gestureStartX) > 30 || Math.abs( relY - this.gestureStartY) > 30) {
// abort (hold) gesture after moving out for too much:
this.gestureStartTime = 0;
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands && this.commandsContainer.handlePointerDragged(relX - this.commandsContainer.relativeX, relY - this.commandsContainer.relativeY, repaintRegion)) {
handled = true;
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerDragged(relX, relY, repaintRegion)) {
handled = true;
}
//#endif
//#endif
if (handlePointerDragged(relX, relY)) {
addRepaintArea(repaintRegion);
handled = true;
}
return handled;
}
/**
* Handles the dragging/movement of a pointer.
* This method should be overwritten only when the polish.hasPointerEvents
* preprocessing symbol is defined.
* The default implementation returns false.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the dragging of the pointer was actually handled by this item.
*/
protected boolean handlePointerDragged(int relX, int relY)
{
return false;
}
/**
* Handles a touch down/press event.
* This is similar to a pointerPressed event, however it is only available on devices with screens that differentiate
* between press and touch events (read: BlackBerry Storm).
*
* @param x the horizontal pixel position of the touch event relative to this item's left position
* @param y the vertical pixel position of the touch event relative to this item's top position
* @return true when the event was handled
*/
public boolean handlePointerTouchDown( int x, int y ) {
//#if polish.hasTouchEvents && polish.css.view-type
if (this.view != null && this.view.handlePointerTouchDown(x, y)) {
return true;
}
//#endif
return false;
}
/**
* Handles a touch up/release event.
* This is similar to a pointerReleased event, however it is only available on devices with screens that differentiate
* between press and touch events (read: BlackBerry Storm).
*
* @param x the horizontal pixel position of the touch event relative to this item's left position
* @param y the vertical pixel position of the touch event relative to this item's top position
* @return true when the event was handled
*/
public boolean handlePointerTouchUp( int x, int y ) {
//#if polish.hasTouchEvents && polish.css.view-type
if (this.view != null && this.view.handlePointerTouchUp(x, y)) {
return true;
}
//#endif
return false;
}
/**
* Handles a touch gestures.
* Note that touch gesture support needs to be activated using the preprocessing variable polish.supportGestures.
* The default implementation calls handleGestureHold() in case GESTURE_HOLD is specified.
* @param gesture the gesture identifier, e.g. GESTURE_HOLD
* @return true when this gesture was handled
* @see #handleGestureHold(int, int)
*/
protected boolean handleGesture(int gesture, int x, int y) {
boolean handled = false;
switch (gesture) {
case GestureEvent.GESTURE_HOLD:
handled = handleGestureHold(x, y);
break;
case GestureEvent.GESTURE_SWIPE_LEFT:
handled = handleGestureSwipeLeft(x, y);
break;
case GestureEvent.GESTURE_SWIPE_RIGHT:
handled = handleGestureSwipeRight(x, y);
}
if (!handled) {
GestureEvent event = GestureEvent.getInstance();
event.reset( gesture, x, y );
UiEventListener listener = getUiEventListener();
if (listener != null) {
listener.handleUiEvent(event, this);
handled = event.isHandled();
}
//#if tmp.handleEvents
if (!handled) {
EventManager.fireEvent(event.getGestureName(), this, event );
handled = event.isHandled();
}
//#endif
}
return handled;
}
/**
* Handles the hold touch gestures.
* Note that touch gesture support needs to be activated using the preprocessing variable polish.supportGestures
* The default implementation shows the commands of this item, but only when the preprocessing variable
* polish.Item.ShowCommandsOnHold is set to true.
*
* @return true when this gesture was handled
*/
protected boolean handleGestureHold(int x, int y) {
//#if polish.Item.ShowCommandsOnHold
if (this.commands != null && !this.isShowCommands && this.commands.size() > 1) {
this.isShowCommands = true;
if (this.commandsContainer != null) {
this.commandsContainer.focusChild(-1);
}
return true;
}
//#endif
return false;
}
/**
* Handles the swipe left gesture.
* @return true when the gesture was handled
*/
protected boolean handleGestureSwipeLeft(int x, int y) {
return false;
}
/**
* Handles the swipe right gesture.
* @return true when the gesture was handled
*/
protected boolean handleGestureSwipeRight(int x, int y) {
return false;
}
/**
* Adds a repaint request for this item's space.
* @param repaintRegion the clipping rectangle to which the repaint area should be added
*/
public void addRepaintArea( ClippingRegion repaintRegion ) {
int absX = getAbsoluteX();
int absY = getAbsoluteY();
int w = this.itemWidth;
int h = this.itemHeight + 1;
//#if polish.css.filter
RgbImage img = this.filterProcessedRgbImage;
if (img != null && (img.getHeight() > h || img.getWidth() > w)) {
int lo = this.layout;
int wFilter = img.getWidth();
int hFilter = img.getHeight();
int horDiff = wFilter - w;
int verDiff = hFilter - h;
if ((lo & LAYOUT_CENTER) == LAYOUT_CENTER) {
absX -= horDiff / 2;
w += horDiff;
} else if ((lo & LAYOUT_CENTER) == LAYOUT_RIGHT) {
absX -= horDiff;
} else {
w += horDiff;
}
if ((lo & LAYOUT_VCENTER) == LAYOUT_VCENTER) {
absY -= verDiff / 2;
h += verDiff;
} else if ((lo & LAYOUT_VCENTER) == LAYOUT_TOP) {
absY -= verDiff;
} else {
h += verDiff;
}
}
//#endif
//System.out.println("adding repaint area x=" + getAbsoluteX() + ", width=" + this.itemWidth + ", y=" + getAbsoluteY() + " for " + this);
repaintRegion.addRegion(
absX,
absY,
w,
h );
}
/**
* Adds a region relative to this item's content x/y start position.
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's content position
* @param y vertical start relative to this item's content position
* @param width width
* @param height height
* @see #getContentWidth()
* @see #getContentHeight()
*/
public void addRelativeToContentRegion(ClippingRegion repaintRegion, int x, int y, int width, int height) {
repaintRegion.addRegion(
getAbsoluteX() + this.contentX + x,
getAbsoluteY() + this.contentY + y,
width,
height
);
}
/**
* Adds a region relative to this item's background x/y start position.
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's background position
* @param y vertical start relative to this item's background position
* @param width width
* @param height height
* @see #getBackgroundWidth()
* @see #getBackgroundHeight()
*/
public void addRelativeToBackgroundRegion( ClippingRegion repaintRegion, int x, int y, int width, int height) {
repaintRegion.addRegion(
getAbsoluteX() + getBackgroundX() + x - 1,
getAbsoluteY() + getBackgroundY() + y - 1,
width + 2,
height + 2
);
}
/**
* Adds a region relative to this item's background x/y start position.
*
* @param animatedBackground the background that requests the repaint (could be a complete-background), can be null
* @param animatedBorder the border that requests the repaint (could be a complete-border), can be null
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's background position
* @param y vertical start relative to this item's background position
* @param width width
* @param height height
* @see #getBackgroundWidth()
* @see #getBackgroundHeight()
*/
public void addRelativeToBackgroundRegion( Background animatedBackground, Border animatedBorder, ClippingRegion repaintRegion, int x, int y, int width, int height) {
//#if polish.css.complete-background || polish.css.complete-border
boolean addAbsolute = false;
//#if polish.css.complete-background
addAbsolute = (this.completeBackground != null && animatedBackground == this.completeBackground);
//#endif
//#if polish.css.complete-border
addAbsolute |= (this.completeBorder != null && animatedBorder == this.completeBorder);
//#endif
if (addAbsolute) {
//System.out.println("adding absolute repaint: bgX=" + getBackgroundX() + ", bgY=" + getBackgroundY() + ", itemHeight-bgHeight=" + (this.itemHeight - this.backgroundHeight) + ", itemWidth-bgWidth=" + (this.itemWidth - this.backgroundWidth));
int padding = this.completeBackgroundPadding.getValue(this.availContentWidth);
repaintRegion.addRegion(
getAbsoluteX() + x - 1 - padding,
getAbsoluteY() + y - 1 - padding,
width + 2 + (padding << 1),
height + 2 + (this.itemHeight - this.backgroundHeight) + (padding << 1)
);
} else {
//#endif
repaintRegion.addRegion(
getAbsoluteX() + getBackgroundX() + x - 1,
getAbsoluteY() + getBackgroundY() + y - 1,
width + 2,
height + 2
);
//#if polish.css.complete-background || polish.css.complete-border
}
//#endif
}
/**
* Animates this item.
* Subclasses can override this method to create animations.
* The default implementation animates the background and the item view if present.
*
* @param currentTime the current time in milliseconds
* @param repaintRegion the repaint area that needs to be updated when this item is animated
* @see #addRelativeToContentRegion(ClippingRegion, int, int, int, int)
*/
public void animate( long currentTime, ClippingRegion repaintRegion) {
if (this.label != null) {
this.label.animate( currentTime, repaintRegion );
}
if (this.background != null) {
this.background.animate( this.screen, this, currentTime, repaintRegion );
}
if (this.border != null) {
this.border.animate( this.screen, this, currentTime, repaintRegion );
}
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.animate( this.screen, this, currentTime, repaintRegion );
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.animate( this.screen, this, currentTime, repaintRegion );
}
//#endif
if (animate()) {
addRepaintArea(repaintRegion);
}
//#if polish.css.view-type
if (this.view != null) {
this.view.animate(currentTime, repaintRegion);
}
//#endif
//#if tmp.supportTouchGestures
if (this.isPressed && (this.gestureStartTime != 0) && (currentTime - this.gestureStartTime > 500)) {
boolean handled = handleGesture( GestureEvent.GESTURE_HOLD, this.gestureStartX, this.gestureStartY );
if (handled) {
this.isIgnorePointerReleaseForGesture = true;
notifyItemPressedEnd();
this.gestureStartTime = 0;
Screen scr = getScreen();
repaintRegion.addRegion( scr.contentX, scr.contentY, scr.contentWidth, scr.contentHeight );
} else {
this.gestureStartTime = 0;
}
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands && this.commandsContainer != null) {
this.commandsContainer.animate(currentTime, repaintRegion);
}
//#endif
}
/**
* Animates this item.
* Subclasses can override this method to create animations.
* The default implementation returns false
*
* @return true when this item has been animated.
* @see #animate(long, ClippingRegion)
*/
public boolean animate() {
return false;
}
/**
* Retrieves the approriate style for focusing this item.
* This is either a item specific one or one inherit by its parents.
* When no parent has a specific focus style, the StyleSheet.focusedStyle is used.
*
* @return the style used for focussing this item.
*/
public Style getFocusedStyle() {
if (!this.isStyleInitialised) {
if (this.style != null) {
setStyle( this.style );
}
//#ifdef polish.useDynamicStyles
else {
initStyle();
}
//#endif
}
Style focStyle;
if (this.focusedStyle != null) {
focStyle = this.focusedStyle;
} else if (this.parent != null) {
focStyle = this.parent.getFocusedStyle();
} else {
focStyle= StyleSheet.focusedStyle;
}
//#if polish.css.visited-style
if (this.hasBeenVisited && focStyle != null) {
Style visitedStyle = (Style) focStyle.getObjectProperty("visited-style");
//#debug
System.out.println("found visited style " + (visitedStyle != null ? visitedStyle.name : "<none>") + " in " + focStyle.name);
if (visitedStyle != null) {
focStyle = visitedStyle;
}
}
//#endif
return focStyle;
}
//#if polish.hasPointerEvents
/**
* Handles the behavior of the virtual keyboard when the item is focused.
* By default, the virtual keyboard is hidden. Components which need to have the virtual keyboard
* shown when they are focused can override this method.
*/
public void handleOnFocusSoftKeyboardDisplayBehavior() {
DeviceControl.hideSoftKeyboard();
}
//#endif
/**
* Focuses this item.
*
* @param newStyle the style which is used to indicate the focused state
* @param direction the direction from which this item is focused,
* either Canvas.UP, Canvas.DOWN, Canvas.LEFT, Canvas.RIGHT or 0.
* When 0 is given, the direction is unknown.
* @return the current style of this item
*/
protected Style focus( Style newStyle, int direction ) {
//#debug
System.out.println("focus " + this);
Style oldStyle = this.style;
if ((!this.isFocused) || (newStyle != this.style && newStyle != null)) {
if (!this.isStyleInitialised && oldStyle != null) {
setStyle( oldStyle );
}
if (newStyle == null) {
newStyle = getFocusedStyle();
}
//#if polish.css.view-type
this.preserveViewType = true;
//#endif
this.isFocused = true;
this.isJustFocused = true;
setStyle( newStyle );
//#if polish.css.pressed-style
if (this.isPressed) {
this.normalStyle = newStyle;
}
//#endif
//#if polish.css.view-type
this.preserveViewType = false;
//#endif
// now set any commands of this item:
if (this.commands != null) {
showCommands();
}
if (oldStyle == null) {
oldStyle = StyleSheet.defaultStyle;
}
//#if polish.android
if (this._androidView != null) {
this._androidView.requestFocus();
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_FOCUS, this, new Integer(direction));
//#endif
}
return oldStyle;
}
/**
* Removes the focus from this item.
*
* @param originalStyle the original style which will be restored.
*/
protected void defocus( Style originalStyle ) {
//#debug
System.out.println("defocus " + this + " with style " + (originalStyle != null ? originalStyle.name : "<no style>"));
if (this.isPressed) {
notifyItemPressedEnd();
}
this.backgroundYOffset = 0;
this.isFocused = false;
if (originalStyle != null) {
setStyle( originalStyle );
if (this.label != null) {
Style prevLabelStyle = this.label.style;
//#if polish.css.label-style
prevLabelStyle = (Style) originalStyle.getObjectProperty("label-style");
if (prevLabelStyle == null) {
prevLabelStyle = this.label.style;
}
//#endif
this.label.defocus(prevLabelStyle);
}
} else {
this.background = null;
this.border = null;
this.style = null;
}
// now remove any commands which are associated with this item:
if (this.commands != null) {
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
}
//#if polish.Item.ShowCommandsOnHold
this.isShowCommands = false;
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_DEFOCUS, this, null);
//#endif
}
/**
* Shows the commands on the screen.
*/
public void showCommands() {
COMMANDS.clear();
addCommands( COMMANDS );
Screen scr = getScreen();
if (scr != null) {
scr.setItemCommands( COMMANDS, this );
}
}
// /**
// * Shows the commands on the screen.
// *
// * @param commandsList an ArrayList with the commands from this item.
// */
// protected void showCommands(ArrayList commandsList) {
// addCommands(commandsList);
// if (this.commands != null) {
// commandsList.addAll( this.commands );
// }
// if (this.parent != null) {
// this.parent.showCommands(commandsList);
// } else {
// Screen scr = getScreen();
// if (scr != null) {
// scr.setItemCommands( commandsList, this );
// }
// }
// }
/**
* Adds all commands to the specified list.
*
* @param commandsList an ArrayList into which the commands from this item should be added.
*/
protected void addCommands( ArrayList commandsList) {
if (this.commands != null) {
commandsList.addAll( this.commands );
}
if (this.parent != null) {
this.parent.addCommands(commandsList);
}
}
/**
* Tries to handle the specified command.
* The item checks if the command belongs to this item and if it has an associated ItemCommandListener.
* Only then it handles the command.
* @param cmd the command
* @return true when the command has been handled by this item
*/
protected boolean handleCommand( Command cmd ) {
if (cmd == this.defaultCommand) {
notifyVisited();
}
if (cmd.commandAction(this, null)) {
return true;
}
ItemCommandListener listener = this.itemCommandListener;
if (this.commands == null || listener == null || !this.commands.contains(cmd) ) {
//#if polish.Item.suppressDefaultCommand
if (listener == null || cmd != this.defaultCommand) {
//#endif
return false;
//#if polish.Item.suppressDefaultCommand
}
//#endif
}
try {
listener.commandAction( cmd, this );
return true;
} catch (Exception e) {
//#debug error
System.out.println("Unable to handle command " + cmd.getLabel() + e );
}
return false;
}
//#if polish.LibraryBuild
/**
* Tries to handle the specified command.
* The item checks if the command belongs to this item and if it has an associated ItemCommandListener.
* Only then it handles the command.
* @param cmd the command
* @return true when the command has been handled by this item
*/
protected boolean handleCommand( javax.microedition.lcdui.Command cmd ) {
return false;
}
//#endif
/**
* Called by the system to notify the item that it is now at least
* partially visible, when it previously had been completely invisible.
* The item may receive <code>paint()</code> calls after
* <code>showNotify()</code> has been called.
*
* <p>The default implementation of this method sets the isShown field to true and calls showNotify on style elements.</p>
*/
protected void showNotify()
{
if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
}
this.isShown = true;
if (this.label != null) {
this.label.showNotify();
}
if (this.background != null) {
this.background.showNotify();
}
if (this.border != null) {
this.border.showNotify();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.showNotify();
}
//#endif
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.showNotify();
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.showNotify();
}
//#endif
//#if polish.blackberry
if (this.isFocused && this._bbField != null) {
Display.getInstance().notifyFocusSet(this);
}
//#endif
//#if polish.android
if (this._androidView != null) {
AndroidDisplay.getInstance().onShow(this._androidView, this);
}
//#endif
//#if tmp.handleEvents
//System.out.println("triggering event 'show' for " + this + " with style " + (this.style != null ? this.style.name : "<null>") + ", animations=" + (this.style != null ? "" + this.style.getAnimations() : "<null>"));
if (!this.hasBeenShownBefore) {
EventManager.fireEvent( EventManager.EVENT_SHOW_FIRST_TIME, this, null );
this.hasBeenShownBefore = true;
}
EventManager.fireEvent( EventManager.EVENT_SHOW, this, null );
//#endif
}
/**
* Called by the system to notify the item that it is now completely
* invisible, when it previously had been at least partially visible. No
* further <code>paint()</code> calls will be made on this item
* until after a <code>showNotify()</code> has been called again.
*
* <p>The default implementation of this method sets the isShown field to false and calls hideNotify on style elements.</p>
*/
protected void hideNotify()
{
this.isShown = false;
if (this.label != null) {
this.label.hideNotify();
}
if (this.background != null) {
this.background.hideNotify();
}
if (this.border != null) {
this.border.hideNotify();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.hideNotify();
}
//#endif
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.hideNotify();
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.hideNotify();
}
//#endif
if (this.isPressed) {
notifyItemPressedEnd();
}
//#if polish.android
if (this._androidView != null) {
AndroidDisplay.getInstance().onHide(this._androidView, this);
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_HIDE, this, null );
//#endif
}
/**
* Shows the screen to which item belongs to and focusses this item.
* This method is the equivalent to display.setCurrentItem( item ).
*
* @param display the display of the MIDlet.
*/
public void show( Display display ) {
Screen myScreen = getScreen();
if ( myScreen == null ) {
//#debug warn
System.out.println("Unable to show this item, since the screen is not known.");
return;
}
myScreen.focus( this );
display.setCurrent( myScreen );
}
/**
* Releases all (memory intensive) resources such as images or RGB arrays of this item.
* The default implementation releases any background resources.
*/
public void releaseResources() {
if (this.background != null) {
this.background.releaseResources();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.releaseResources();
}
//#endif
//#if polish.css.filter && polish.midp2
if (this.filters != null) {
for (int i=0; i<this.filters.length; i++) {
RgbFilter filter = this.filters[i];
filter.releaseResources();
}
}
//#endif
}
/**
* Destroy the item by removing all references to parent, screen, listeners etc.
* and calling releaseResources()
*/
public void destroy() {
releaseResources();
AnimationThread.removeAnimationItem(this);
if(null != this.itemCommandListener)
this.itemCommandListener = null;
if(null != this.itemStateListener)
this.itemStateListener = null;
if(null != this.parent)
this.parent = null;
if(null != this.screen)
this.screen = null;
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.destroy();
this.view = null;
}
//#endif
}
/**
* Sets an arbitrary attribute for this item.
*
* @param key the key for the attribute
* @param value the attribute value
*/
public void setAttribute( Object key, Object value ) {
if (this.attributes == null) {
this.attributes = new HashMap();
}
this.attributes.put( key, value );
}
/**
* Gets an previously added attribute of this item.
*
* @param key the key of the attribute
* @return the attribute value, null if none has been registered under the given key before
*/
public Object getAttribute( Object key ) {
if (this.attributes == null) {
return null;
}
return this.attributes.get( key );
}
/**
* Removes an previously added attribute of this item.
*
* @param key the key of the attribute
* @return the attribute value, null if none has been registered under the given key before
*/
public Object removeAttribute(Object key)
{
if (this.attributes == null) {
return null;
}
return this.attributes.remove( key );
}
/**
* Returns a HashMap object with all registered attributes.
*
* @return a HashMap object with all attribute key/value pairs, null if no attribute was stored before.
*/
public HashMap getAttributes() {
return this.attributes;
}
/**
* Determines if this item or one of it's children is within the specified point.
* The default implementation returns this item or this item's label when the position fits.
*
* @param relX the x position of the point relative to this item's left position
* @param relY the y position of the point relative to this item's top position
* @return this item or one of it's children, when the position fits, otherwise null is returned
*/
public Item getItemAt( int relX, int relY ) {
if ( isInItemArea(relX, relY) ) {
if (this.label != null) {
Item item = this.label.getItemAt(relX, relY);
if (item != null) {
return item;
}
}
return this;
}
return null;
}
/**
* Retrieves this item's current absolute horizontal position
*
* @return the absolute x position of this item in pixel.
*/
public int getAbsoluteX() {
int absX = this.relativeX;
// if (this.label != null && this.useSingleRow && !this.isLayoutCenter && !this.isLayoutRight) {
// // hack for left align with additional label:
// absX += this.contentX;
// }
Item item = this.parent;
if (item != null && item.label == this && item.useSingleRow) {
// this is the label of another item
absX -= item.contentX;
}
//#if polish.css.x-adjust
if (this.xAdjustment != null) {
int value = this.xAdjustment.getValue(this.itemWidth);
absX += value;
}
//#endif
while (item != null) {
absX += item.relativeX + item.contentX;
item = item.parent;
}
return absX;
}
/**
* Retrieves this item's current absolute vertical position
*
* @return the absolute y position of this item in pixel.
*/
public int getAbsoluteY() {
int absY = this.relativeY; // + this.contentY; in that case no label is included anymore
Item item = this.parent;
if (item != null && item.label == this) {
absY -= item.contentY;
}
//#if polish.css.y-adjust
if (this.yAdjustment != null) {
absY += this.yAdjustment.getValue(this.itemHeight);
}
//#endif
while (item != null) {
absY += item.relativeY + item.contentY;
if (item instanceof Container) {
absY += ((Container)item).yOffset;
}
item = item.parent;
}
return absY;
}
/**
* Sets the absolute vertical position of this item.
* Note that results may vary depending on the view-type of the root container.
*
* @param absY the absolute y position of this item in pixel.
*/
public void setAbsoluteY(int absY) {
// find out vertical offset for root container:
int currentAbsY = getAbsoluteY();
int diff = absY - currentAbsY;
//System.out.println("setting absY to " + absY + ", current=" + currentAbsY + ", diff=" + diff + " for item " + this);
Item item = this;
while (item.parent != null) {
item = item.parent;
}
if (item instanceof Container) {
Container container = (Container)item;
int offset = container.getScrollYOffset() + diff;
//System.out.println("resulting in scrollOffset=" + offset + ", currentScrollOffset=" + container.getScrollYOffset());
container.setScrollYOffset(offset, false);
}
//System.out.println("after setAbsoluteY=" + getAbsoluteY() + ", should be=" + absY);
}
/**
* Retrieves the start of the content relative to this item's absolute x position.
* @return the horizontal start of the content
* @see #getAbsoluteX()
*/
public int getContentX() {
return this.contentX;
}
/**
* Retrieves the start of the content relative to this item's absolute y position.
* @return the vertical start of the content
* @see #getAbsoluteY()
*/
public int getContentY() {
return this.contentY;
}
/**
* Retrieves the width of the content.
* @return the content width in pixels
*/
public int getContentWidth()
{
return this.contentWidth;
}
/**
* Retrieves the height of the content.
* @return the content height in pixels
*/
public int getContentHeight()
{
return this.contentHeight;
}
/**
* Retrieves the width of the content.
* @return the content width in pixels
*/
public int getAvailableContentWidth()
{
return this.availContentWidth;
}
/**
* Retrieves the height of the content.
* @return the content height in pixels
*/
public int getAvailableContentHeight()
{
return this.availContentHeight;
}
/**
* Retrieves the height of the area that this item covers.
* This can be different from the original itemHeight for items that have popups such as the POPUP ChoiceGroup
* @return the height of the item's area in pixel
*/
public int getItemAreaHeight()
{
return Math.max( this.itemHeight, this.marginTop + this.backgroundHeight + this.marginBottom );
}
/**
* Retrieves the start of the background relative to this item's origin.
*
* @return the horizontal background start in pixels.
*/
public int getBackgroundX() {
//#if polish.css.include-label
if (this.includeLabel) {
return this.marginLeft;
} else {
//#endif
return this.contentX - this.paddingLeft;
//#if polish.css.include-label
}
//#endif
}
/**
* Retrieves the start of the background relative to this item's origin.
*
* @return the horizontal background start in pixels.
*/
public int getBackgroundY() {
//#if polish.css.include-label
if (this.includeLabel) {
return this.marginTop;
} else {
//#endif
return this.contentY - this.paddingTop;
//#if polish.css.include-label
}
//#endif
}
/**
* Retrieves the width of this item's background.
* @return the width in pixels
*/
public int getBackgroundWidth() {
return this.backgroundWidth;
}
/**
* Retrieves the height of this item's background.
* @return the height in pixels
*/
public int getBackgroundHeight() {
return this.backgroundHeight;
}
/**
* Retrieves the parent of this item.
*
* @return this item's parent.
*/
public Item getParent() {
return this.parent;
}
/**
* Retrieves the parent root of this item.
*
* @return this item's super parent, either this item itself or it's last known ancestor.
*/
public Item getParentRoot() {
Item p = this;
while (p.parent != null) {
p = p.parent;
}
return p;
}
/**
* Sets a parent for this item.
* @param parent the parent of this item
*/
public void setParent(Item parent)
{
this.parent = parent;
}
//#if polish.midp
/**
* Sets a parent for this item.
* @param parent the parent of this item
*/
public void setParent(javax.microedition.lcdui.Item parent)
{
// ignore
}
//#endif
/**
* Sets the visible status of this item.
* Invisible items occupy no space on the UI screen and cannot be focused/traversed.
* Note that you can call this method ONLY when the preprocessing variable polish.supportInvisibleItems is true or when you use the CSS attribute 'visible' in your polish.css file.
* @param visible true when this item should become visible.
*/
public void setVisible( boolean visible ) {
//#if tmp.invisible
boolean invisible = !visible;
if (invisible == this.isInvisible) {
return;
}
// if (visible) {
// System.out.println("+++ SETTING VISIBLE: " + this );
// } else {
// System.out.println("--- SETTING INVISIBLE: " + this );
// }
if (this.parent instanceof Container) {
Container parentContainer = (Container) this.parent;
if (invisible && this.isFocused) {
//System.out.println("making focused item invisible: " + this);
// remove any item commands:
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
int itemIndex = parentContainer.indexOf( this );
boolean isFocusSet = parentContainer.focusClosestItemAbove( itemIndex );
this.isFocused = false;
//System.out.println("new focus set: " + isFocusSet + ", new index=" + parentContainer.focusedIndex + ", this.index=" + itemIndex );
if (isFocusSet) {
if (parentContainer.focusedIndex > itemIndex ) {
// focused has moved downwards, since the above item is now invisible,
// adjust the scrolling accordingly:
int offset = parentContainer.yOffset + this.itemHeight + parentContainer.paddingVertical;
if (offset > 0) {
offset = 0;
}
//System.out.println("setting parent scroll offset to " + offset );
parentContainer.setScrollYOffset( offset, false );
} else {
parentContainer.scroll( 0, parentContainer.focusedItem, true);
}
} else {
parentContainer.focusChild(-1);
}
if (this instanceof Container) {
((Container)this).focusChild(-1);
}
} else if (!this.isFocused && parentContainer.focusedIndex > parentContainer.indexOf(this)) {
// adjust scrolling so that the focused element of the parent container stays in the current position:
int offset;
if (invisible) {
offset = parentContainer.getScrollYOffset() + this.itemHeight;
if (offset > 0) {
offset = 0;
}
//System.out.println("invisible: adjusting yScrollOffset with itemHeight=" + this.itemHeight + " to " + (offset > 0 ? 0 : offset) );
parentContainer.setScrollYOffset( offset, false );
} else {
int height = this.invisibleItemHeight;
if (height == 0 && this.parent != null) {
//System.out.println("visible getting height for available width of " + this.parent.contentWidth );
this.isInvisible = false;
setInitialized(false);
height = getItemHeight( this.parent.contentWidth, this.parent.contentWidth, this.parent.contentHeight );
} else {
this.itemHeight = height;
}
offset = parentContainer.getScrollYOffset() - height;
//System.out.println("visible: adjusting yScrollOffset with height=" + height + " to " + offset );
parentContainer.setScrollYOffset( offset, false );
}
// adjust the internal Y position:
Item parentItem = this;
while (parentItem != null) {
if (parentItem.internalX != NO_POSITION_SET) {
if (invisible) {
parentItem.internalY -= this.itemHeight;
} else {
parentItem.internalY += this.itemHeight;
}
}
parentItem = parentItem.parent;
}
} else if (parentContainer.focusedIndex == -1)
{
if(visible)
{
//No other container is set to focused
//so it is ASSUMED that this is the only
//visisble item
this.relativeY = 0;
parentContainer.setScrollYOffset(0);
parentContainer.focusChild(parentContainer.indexOf(this));
}
}
}
if ( invisible ) {
this.invisibleAppearanceModeCache = this.appearanceMode;
this.invisibleItemHeight = this.itemHeight;
this.appearanceMode = PLAIN;
} else {
this.appearanceMode = this.invisibleAppearanceModeCache;
}
this.isInvisible = invisible;
requestInit();
//#endif
}
/**
* Gets the visible status of this item.
* Invisible items occupy no space on the UI screen and cannot be focused/traversed.
* Note that you can call this method ONLY when the preprocessing variable polish.supportInvisibleItems is true or when you use the 'visible' CSS attribute.
* @return true when this item is visible.
*/
public boolean isVisible() {
boolean result;
//#if !tmp.invisible
result = false;
//#else
result = !this.isInvisible;
//#endif
return result;
}
//#if polish.debug.error || polish.keepToString
/**
* Generates a String representation of this item.
* This method is only implemented when the logging framework is active or the preprocessing variable
* "polish.keepToString" is set to true.
* @return a String representation of this item.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
if (this.label != null && this.label.text != null) {
buffer.append( '"' ).append( this.label.text ).append("\"");
}
if (this.style != null) {
buffer.append(" [").append(this.style.name).append("]");
}
buffer.append(": ");
buffer.append( super.toString() );
return buffer.toString();
}
//#endif
/**
* Determines whether this item contains the given command.
*
* @param command the command
* @return true when this item contains this command
*/
public boolean containsCommand(Command command) {
return this.commands != null && this.commands.contains(command);
}
/**
* @return the default command
*/
public Command getDefaultCommand() {
return this.defaultCommand;
}
/**
* @return the commands associated with this item in an arraylist - might be null!
*/
public ArrayList getItemCommands() {
return this.commands;
}
/**
* Sets the initialized state of this item.
* @param initialized true when this item is deemed to be initialized, otherwise false. When setting to 'false' the item will run its init() and initContent() methods at the next option.
*/
public void setInitialized(boolean initialized)
{
this.isInitialized = initialized;
}
/**
* Determines the initialization state of this item
* @return true when it is initialized, false otherwise
*/
public boolean isInitialized()
{
return this.isInitialized;
}
/**
* Sets the item's complete height
* @param height the height in pixel
*/
public void setItemHeight( int height ) {
int diff = height - this.itemHeight;
//#debug
System.out.println("setting item height " + height + ", diff=" + diff + ", vcenter=" +isLayoutVerticalCenter() + " for " + this );
this.itemHeight = height;
this.backgroundHeight += diff;
if (isLayoutVerticalCenter()) {
this.contentY += diff/2;
} else if (isLayoutBottom()) {
this.contentY += diff;
}
}
/**
* Sets the item's complete width
* @param width the width in pixel
*/
public void setItemWidth( int width ) {
int diff = width - this.itemWidth;
//#debug
System.out.println("setting item width " + width + ", diff=" + diff + ", hcenter=" +isLayoutCenter() + " for " + this );
this.itemWidth = width;
this.backgroundWidth += diff;
if (isLayoutCenter()) {
this.contentX += diff/2;
} else if (isLayoutRight()) {
this.contentX += diff;
}
}
/**
* Retrieves the internal area's horizontal start relative to this item's content area
* @return the horizontal start in pixels, -1 if it not set
*/
public int getInternalX() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalX;
}
/**
* Retrieves the internal area's vertical start relative to this item's content area
* @return the vertical start in pixels, -1 if it not set
*/
public int getInternalY() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalY;
}
/**
* Retrieves the internal area's vertical width
* @return the vertical width in pixels, -1 if it not set
*/
public int getInternalWidth() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalWidth;
}
/**
* Retrieves the internal area's vertical height
* @return the vertical height in pixels, -1 if it not set
*/
public int getInternalHeight() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalHeight;
}
/**
* Fires an event for this item as well as its subitems like its label.
*
* @param eventName the name of the event
* @param eventData the event data
* @see EventManager#fireEvent(String, Object, Object)
*/
public void fireEvent( String eventName, Object eventData ) {
if (this.label != null) {
EventManager.fireEvent(eventName, this.label, eventData);
}
EventManager.fireEvent(eventName, this, eventData);
}
/**
* Updates the internal area on BB and similar platforms that contain native fields.
*/
public void updateInternalArea() {
// subclasses may override this.
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a right layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutRight()
{
return this.isLayoutRight;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a left layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutLeft()
{
return !(this.isLayoutRight | this.isLayoutCenter);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a center layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutCenter()
{
return this.isLayoutCenter;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a top layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutTop()
{
return (this.layout & LAYOUT_BOTTOM) == 0;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a bottom layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutBottom()
{
return ((this.layout & LAYOUT_VCENTER) == LAYOUT_BOTTOM);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vcenter layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalCenter()
{
return ((this.layout & LAYOUT_VCENTER) == LAYOUT_VCENTER);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vshrink layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalShrink() {
return ((this.layout & LAYOUT_VSHRINK) == LAYOUT_VSHRINK);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vexpand layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalExpand() {
return ((this.layout & LAYOUT_VEXPAND) == LAYOUT_VEXPAND);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a horizontal expand layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutExpand() {
return ((this.layout & LAYOUT_EXPAND) == LAYOUT_EXPAND);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a horizontal shrink layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutShrink() {
return ((this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a newwline-after layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutNewlineAfter() {
return ((this.layout & LAYOUT_NEWLINE_AFTER) == LAYOUT_NEWLINE_AFTER);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a newwline-after layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutNewlineBefore() {
return ((this.layout & LAYOUT_NEWLINE_BEFORE) == LAYOUT_NEWLINE_BEFORE);
}
public void setItemTransition( ItemTransition transition ) {
this.itemTransition = transition;
}
public Image toImage() {
Image img;
//#if polish.midp2
int[] pixels = new int[ this.itemWidth * this.itemHeight ];
img = Image.createRGBImage( pixels, this.itemWidth, this.itemHeight, true );
//#else
img = Image.createImage( this.itemWidth, this.itemHeight );
//#endif
Graphics g = img.getGraphics();
ItemTransition t = this.itemTransition;
this.itemTransition = null;
paint( 0, 0, 0, this.itemWidth, g );
this.itemTransition = t;
return img;
}
public RgbImage toRgbImage() {
return new RgbImage( toImage(), true );
}
/**
* Determines whether this item is interactive and thus can be selected.
* @return true when this item is deemed to be interactive
*/
public boolean isInteractive() {
return this.appearanceMode != PLAIN;
}
/**
* Resets the style of this item and all its children (if any).
* This is useful when you have applied changes to this Item's style or one of its elements.
* @param recursive true when all subelements of this Item should reset their style as well.
* @see Screen#resetStyle(boolean)
* @see UiAccess#resetStyle(Screen,boolean)
* @see UiAccess#resetStyle(Item,boolean)
*/
public void resetStyle(boolean recursive) {
if (this.style != null) {
setStyle(this.style);
}
if (recursive) {
if (this.label != null) {
this.label.resetStyle(recursive);
}
}
}
/**
* Notifies this item about a new screen size.
* The default implementation just checks if the design should switch to portrait or landscape-style (if those CSS attributes are used).
* The item will be re-initialized with its available dimensions using init(int,int,int) soon.
* @param screenWidth the screen width
* @param screenHeight the screen height
*/
public void onScreenSizeChanged( int screenWidth, int screenHeight ) {
//#debug
System.out.println("onScreenSizeChanged to " + screenWidth + ", " + screenHeight + " for " + this);
if (this.label != null) {
this.label.onScreenSizeChanged(screenWidth, screenHeight);
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.onScreenSizeChanged(screenWidth, screenHeight);
}
//#endif
//#if polish.css.portrait-style || polish.css.landscape-style
if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
}
Style newStyle = null;
if (screenWidth > screenHeight) {
if (this.landscapeStyle != null && this.style != this.landscapeStyle) {
newStyle = this.landscapeStyle;
}
} else if (this.portraitStyle != null && this.style != this.portraitStyle){
newStyle = this.portraitStyle;
}
Style oldStyle = null;
if (newStyle != null) {
//#debug
System.out.println("onScreenSizeChanged(): setting new style " + newStyle.name + " for " + this);
oldStyle = this.style;
setStyle( newStyle );
//#if polish.css.pressed-style
if (this.isPressed) {
this.normalStyle = newStyle;
}
//#endif
if (this.isFocused) {
if (this.parent instanceof Container) {
Container cont = (Container)this.parent;
cont.itemStyle = newStyle;
setStyle( getFocusedStyle() );
}
} else if (oldStyle != null && this.parent instanceof Container) {
Container cont = (Container)this.parent;
if (cont.itemStyle == oldStyle) {
cont.itemStyle = newStyle;
}
}
}
//#endif
}
/**
* Retrieves the available width for this item.
* @return the available width in pixel, can be 0 when this item has not yet been initialized
*/
public int getAvailableWidth() {
return this.availableWidth;
}
/**
* Retrieves the available height for this item.
* @return the available height in pixel, can be 0 when this item has not yet been initialized
*/
public int getAvailableHeight() {
return this.availableHeight;
}
/**
* Sets an UiEventListener for the this item and its children.
* @param listener the listener, use null to remove a listener
*/
public void setUiEventListener(UiEventListener listener) {
this.uiEventListener = listener;
}
/**
* Retrieves the UiEventListener for this item or for one of its parents.
* @return the listener or null, if none has been registered
*/
public UiEventListener getUiEventListener() {
UiEventListener listener = this.uiEventListener;
if (listener == null) {
Item parentItem = this.parent;
while (parentItem != null && listener == null) {
listener = parentItem.uiEventListener;
parentItem = parentItem.parent;
}
if (listener == null) {
listener = getScreen().getUiEventListener();
}
}
return listener;
}
/**
* Retrieves the RGB data of this item.
* This method only works on MIDP 2.0+ devices.
*
* @return the RGB data as an int array.
*/
public int[] getRgbData() {
return getRgbData( true, 255 );
}
/**
* Retrieves the RGB data of this item.
* This method only works on MIDP 2.0+ devices.
*
* @param supportTranslucency true when not only transparent but also translucent parts of the item should be rendered correctly
* @param rgbOpacity The opacity of the item between 0 (fully transparent) and 255 (fully opaque)
* @return the RGB data as an int array.
*/
public int[] getRgbData( boolean supportTranslucency, int rgbOpacity ) {
int[] result = new int[0];
//#if polish.midp2
if (this.itemWidth < 1 || this.itemHeight < 1) {
//#debug error
System.out.println("Unable to retrieve RGB data for item with a dimension of " + this.itemWidth + "x" + this.itemHeight + " for " + this );
return new int[0];
}
Image image = Image.createImage( this.itemWidth, this.itemHeight );
if (supportTranslucency) {
// we use a two-pass painting for determing translucent pixels as well:
// in the first run we paint it on a black background (dataBlack),
// in the second we use a white background (dataWhite).
// We then compare the pixels in dataBlack and dataWhite:
// a) when a pixel is black in dataBlack and white and dataWhite it is fully transparent
// b) when a pixel has the same value in dataBlack and in dataWhite it is fully opaque
// c) when the pixel has different values it contains translucency - we can extract the original value from the difference between data1 and data2.
// The solution is based on this formula for determining the final green component value when adding a pixel with alpha value on another opaque pixel:
// final_green_value = ( pixel1_green * alpha + pixel2_green * ( 255 - alpha ) ) / 255
// When can work our way backwards to determine the original green and alpha values.
Graphics g = image.getGraphics();
int bgColorBlack = 0x0;
g.setColor(bgColorBlack);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
int[] transparentColorRgb = new int[1];
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
bgColorBlack = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] dataBlack = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(dataBlack, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
int bgColorWhite = 0xffffff;
g.setColor(bgColorWhite);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
bgColorWhite = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] dataWhite = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(dataWhite, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
rgbOpacity = (rgbOpacity << 24) | (0x00ffffff);
result = new int[ dataBlack.length ];
int lastPixelWhite = 0;
int lastPixelBlack = 0;
int lastPixelResult = 0;
// ensure transparent parts are indeed transparent
for (int i = 0; i < dataBlack.length; i++) {
int pixelBlack = dataBlack[i];
int pixelWhite = dataWhite[i];
if (pixelBlack == pixelWhite) {
result[i] = pixelBlack & rgbOpacity;
} else if (pixelBlack != bgColorBlack || pixelWhite != bgColorWhite ) {
if (pixelBlack == lastPixelBlack && pixelWhite == lastPixelWhite) {
result[i] = lastPixelResult;
} else {
// this pixel contains translucency:
int redBlack = (pixelBlack & 0xff0000) >> 16;
int greenBlack = (pixelBlack & 0xff00) >> 8;
int blueBlack = (pixelBlack & 0xff);
int redWhite = (pixelWhite & 0xff0000) >> 16;
int greenWhite = (pixelWhite & 0xff00) >> 8;
int blueWhite = (pixelWhite & 0xff);
int originalAlpha = 0;
int originalRed;
if (redBlack == 0 && redWhite == 255) {
originalRed = 0;
} else {
if (redBlack == 0) {
redBlack = 1;
} else if (redWhite == 255) {
redWhite = 254;
}
originalRed = (255 * redBlack) / (redBlack - redWhite + 255);
originalAlpha = redBlack - redWhite + 255;
}
int originalGreen;
if (greenBlack == 0 && greenWhite == 255) {
originalGreen = 0;
} else {
if (greenBlack == 0) {
greenBlack = 1;
} else if (greenWhite == 255) {
greenWhite = 254;
}
originalGreen = (255 * greenBlack) / (greenBlack - greenWhite + 255);
originalAlpha = greenBlack - greenWhite + 255;
}
int originalBlue;
if (blueBlack == 0 && blueWhite == 255) {
originalBlue = 0;
} else {
if (blueBlack == 0) {
blueBlack = 1;
} else if (blueWhite == 255) {
blueWhite = 254;
}
originalBlue = (255 * blueBlack) / (blueBlack - blueWhite + 255);
originalAlpha = blueBlack - blueWhite + 255;
}
lastPixelWhite = pixelWhite;
lastPixelBlack = pixelBlack;
lastPixelResult = ((originalAlpha << 24) | (originalRed << 16) | (originalGreen << 8) | originalBlue) & rgbOpacity;
result[i] = lastPixelResult;
}
}
}
} else {
int transparentColor = 0x12345678;
Graphics g = image.getGraphics();
g.setColor(transparentColor);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
int[] transparentColorRgb = new int[1];
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
transparentColor = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] itemRgbData = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(itemRgbData, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
boolean addOpacity = (rgbOpacity != 255);
rgbOpacity = (rgbOpacity << 24) | (0x00ffffff);
// ensure transparent parts are indeed transparent
for (int i = 0; i < itemRgbData.length; i++) {
int data = itemRgbData[i];
if( data == transparentColor ) {
itemRgbData[i] = 0;
} else if (addOpacity) {
itemRgbData[i] = data & rgbOpacity;
}
}
}
//#endif
return result;
}
/**
* Fires a cycle event.
* The default implementation forwards the event to the cycle listener if one is registered, otherwise it will be forwarded to the parent item.
* When there is neither a parent item or a cycle listener, this method will return true.
*
* @param direction the direction, e.g. CycleListener.DIRECTION_BOTTOM_TO_TOP
* @return true when the cycling process can continue, false when the cycle event should be aborted
* @see CycleListener#DIRECTION_BOTTOM_TO_TOP
* @see CycleListener#DIRECTION_TOP_TO_BOTTOM
* @see CycleListener#DIRECTION_LEFT_TO_RIGHT
* @see CycleListener#DIRECTION_RIGHT_TO_LEFT
* @see #setCycleListener(CycleListener)
* @see #getCycleListener()
*/
public boolean fireContinueCycle( int direction ) {
if (this.cycleListener != null) {
return this.cycleListener.onCycle(this, direction);
}
if (this.parent != null) {
return this.parent.fireContinueCycle(direction);
}
return true;
}
/**
* Allows to specify a cycle listener
* @param listener the listener, use null to deregister the listener
* @see #getCycleListener()
*/
public void setCycleListener( CycleListener listener ) {
this.cycleListener = listener;
}
/**
* Retrieves the cycle listener
* @return the currently registered cycle listener
* @see #setCycleListener(CycleListener)
*/
public CycleListener getCycleListener() {
return this.cycleListener;
}
//#if polish.useNativeGui
/**
* Species a native implementation for this item.
* This method is only available when the preprocessing variable polish.useNativeGui is set to true.
* @param nativeItem the native implementation
*/
public void setNativeItem( NativeItem nativeItem ) {
this.nativeItem = nativeItem;
}
//#endif
//#if polish.useNativeGui
/**
* Species a native implementation for this item.
* This method is only available when the preprocessing variable polish.useNativeGui is set to true.
* @return the native implementation, can be null
*/
public NativeItem getNativeItem() {
return this.nativeItem;
}
//#endif
//#ifdef polish.Item.additionalMethods:defined
//#include ${polish.Item.additionalMethods}
//#endif
}
| public boolean isInItemArea( int relX, int relY ) {
if (relY < 0 || relY > this.itemHeight || relX < 0 || relX > this.itemWidth) { //Math.max(this.itemWidth, this.contentX + this.contentWidth)) {
//#debug
System.out.println("isInItemArea(" + relX + "," + relY + ") = false: itemWidth=" + this.itemWidth + ", itemHeight=" + this.itemHeight + " (" + this + ")");
return false;
}
//#debug
System.out.println("isInItemArea(" + relX + "," + relY + ") = true: itemWidth=" + this.itemWidth + ", itemHeight=" + this.itemHeight + " (" + this + ")");
return true;
}
/**
* Determines whether the given relative x/y position is inside of the specified child item's area including paddings, margins and label.
* Subclasses which extend their area over the declared/official content area, which is determined
* in the initContent() method (like popup items), might want to override this method.
* It is assumed that the item has been initialized before.
*
* @param relX the x position relative to this item's left content position
* @param relY the y position relative to this item's top content position
* @param child the child
* @return true when the relX/relY coordinate is within the child item's area.
*/
public boolean isInItemArea( int relX, int relY, Item child ) {
if (child != null) {
return child.isInItemArea(relX - child.relativeX, relY - child.relativeY);
}
return false;
}
/**
* Handles the event when a pointer has been pressed at the specified position.
* The default method discards this event when relX/relY is outside of the item's area.
* When the event took place inside of the content area, the pointer-event is translated into an artificial
* FIRE game-action keyPressed event, which is subsequently handled
* by the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the pressing of the pointer was actually handled by this item.
* @see #isInItemArea(int, int) this method is used for determining whether the event belongs to this item
* @see #isInContentArea(int, int) for a helper method for determining whether the event took place into the actual content area
* @see #handleKeyPressed(int, int)
* @see #contentX for calculating the horizontal position relative to the content (relX - contentX)
* @see #contentY for calculating the vertical position relative to the content (relY - contentY)
*/
protected boolean handlePointerPressed( int relX, int relY ) {
//#ifdef polish.hasPointerEvents
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
Container cmdCont = this.commandsContainer;
if (cmdCont != null && cmdCont.handlePointerPressed(relX - cmdCont.relativeX, relY - cmdCont.relativeY)) {
return true;
}
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerPressed(relX, relY)) {
return true;
}
//#endif
if ( isInItemArea(relX, relY) ) {
//#if tmp.supportTouchGestures
this.gestureStartTime = System.currentTimeMillis();
this.gestureStartX = relX;
this.gestureStartY = relY;
//#endif
return handleKeyPressed( 0, Canvas.FIRE );
}
//#if polish.Item.ShowCommandsOnHold
else {
this.gestureStartTime = 0;
if (this.isShowCommands) {
this.isShowCommands = false;
return true;
}
}
//#endif
//#endif
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handlePointerPressed(relX, relY);
}
//#endif
return false;
}
/**
* Handles the event when a pointer has been released at the specified position.
* The default method discards this event when relX/relY is outside of the item's area.
* When the event took place inside of the content area, the pointer-event is translated into an artificial
* FIRE game-action keyReleased event, which is subsequently handled
* bu the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the pressing of the pointer was actually handled by this item.
* @see #isInItemArea(int, int) this method is used for determining whether the event belongs to this item
* @see #isInContentArea(int, int) for a helper method for determining whether the event took place into the actual content area
* @see #handleKeyPressed(int, int)
* @see #contentX for calculating the horizontal position relative to the content (relX - contentX)
* @see #contentY for calculating the vertical position relative to the content (relY - contentY)
*/
protected boolean handlePointerReleased( int relX, int relY ) {
//#ifdef polish.hasPointerEvents
//#debug
System.out.println("handlePointerReleased " + relX + ", " + relY + " for item " + this + " isPressed=" + this.isPressed);
// handle keyboard behaviour only if this not a container,
// its handled in the overwritten version
if (this.isJustFocused) {
this.isJustFocused = false;
handleOnFocusSoftKeyboardDisplayBehavior();
}
//#if tmp.supportTouchGestures
if (this.isIgnorePointerReleaseForGesture) {
this.isIgnorePointerReleaseForGesture = false;
return true;
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands) {
this.commandsContainer.handlePointerReleased(relX - this.commandsContainer.relativeX, relY - this.commandsContainer.relativeY);
this.isShowCommands = false;
notifyItemPressedEnd();
return true;
}
//#endif
//#if tmp.supportTouchGestures
int verticalDiff = Math.abs( relY - this.gestureStartY );
if (verticalDiff < 20) {
int horizontalDiff = relX - this.gestureStartX;
if (horizontalDiff > this.itemWidth/2) {
if (handleGesture(GestureEvent.GESTURE_SWIPE_RIGHT, relX, relY)) {
return true;
}
} else if (horizontalDiff < -this.itemWidth/2) {
if (handleGesture(GestureEvent.GESTURE_SWIPE_LEFT, relX, relY)) {
return true;
}
}
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerReleased(relX, relY)) {
return true;
}
//#endif
if ( isInItemArea(relX, relY) ) {
return handleKeyReleased( 0, Canvas.FIRE );
} else if (this.isPressed) {
notifyItemPressedEnd();
return true;
}
//#endif
//#ifdef polish.css.view-type
if(this.view != null) {
return this.view.handlePointerReleased(relX, relY);
}
//#endif
return false;
}
/**
* Handles the dragging/movement of a pointer.
* This method should be overwritten only when the polish.hasPointerEvents
* preprocessing symbol is defined.
* The default implementation returns false.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the dragging of the pointer was actually handled by this item.
*/
protected boolean handlePointerDragged(int relX, int relY, ClippingRegion repaintRegion)
{
boolean handled = false;
//#ifdef polish.hasPointerEvents
//#if tmp.supportTouchGestures
if (this.gestureStartTime != 0 && Math.abs( relX - this.gestureStartX) > 30 || Math.abs( relY - this.gestureStartY) > 30) {
// abort (hold) gesture after moving out for too much:
this.gestureStartTime = 0;
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands && this.commandsContainer.handlePointerDragged(relX - this.commandsContainer.relativeX, relY - this.commandsContainer.relativeY, repaintRegion)) {
handled = true;
}
//#endif
//#ifdef polish.css.view-type
if (this.view != null && this.view.handlePointerDragged(relX, relY, repaintRegion)) {
handled = true;
}
//#endif
//#endif
if (handlePointerDragged(relX, relY)) {
addRepaintArea(repaintRegion);
handled = true;
}
return handled;
}
/**
* Handles the dragging/movement of a pointer.
* This method should be overwritten only when the polish.hasPointerEvents
* preprocessing symbol is defined.
* The default implementation returns false.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
* @return true when the dragging of the pointer was actually handled by this item.
*/
protected boolean handlePointerDragged(int relX, int relY)
{
return false;
}
/**
* Handles a touch down/press event.
* This is similar to a pointerPressed event, however it is only available on devices with screens that differentiate
* between press and touch events (read: BlackBerry Storm).
*
* @param x the horizontal pixel position of the touch event relative to this item's left position
* @param y the vertical pixel position of the touch event relative to this item's top position
* @return true when the event was handled
*/
public boolean handlePointerTouchDown( int x, int y ) {
//#if polish.hasTouchEvents && polish.css.view-type
if (this.view != null && this.view.handlePointerTouchDown(x, y)) {
return true;
}
//#endif
return false;
}
/**
* Handles a touch up/release event.
* This is similar to a pointerReleased event, however it is only available on devices with screens that differentiate
* between press and touch events (read: BlackBerry Storm).
*
* @param x the horizontal pixel position of the touch event relative to this item's left position
* @param y the vertical pixel position of the touch event relative to this item's top position
* @return true when the event was handled
*/
public boolean handlePointerTouchUp( int x, int y ) {
//#if polish.hasTouchEvents && polish.css.view-type
if (this.view != null && this.view.handlePointerTouchUp(x, y)) {
return true;
}
//#endif
return false;
}
/**
* Handles a touch gestures.
* Note that touch gesture support needs to be activated using the preprocessing variable polish.supportGestures.
* The default implementation calls handleGestureHold() in case GESTURE_HOLD is specified.
* @param gesture the gesture identifier, e.g. GESTURE_HOLD
* @return true when this gesture was handled
* @see #handleGestureHold(int, int)
*/
protected boolean handleGesture(int gesture, int x, int y) {
boolean handled = false;
switch (gesture) {
case GestureEvent.GESTURE_HOLD:
handled = handleGestureHold(x, y);
break;
case GestureEvent.GESTURE_SWIPE_LEFT:
handled = handleGestureSwipeLeft(x, y);
break;
case GestureEvent.GESTURE_SWIPE_RIGHT:
handled = handleGestureSwipeRight(x, y);
}
if (!handled) {
GestureEvent event = GestureEvent.getInstance();
event.reset( gesture, x, y );
UiEventListener listener = getUiEventListener();
if (listener != null) {
listener.handleUiEvent(event, this);
handled = event.isHandled();
}
//#if tmp.handleEvents
if (!handled) {
EventManager.fireEvent(event.getGestureName(), this, event );
handled = event.isHandled();
}
//#endif
}
return handled;
}
/**
* Handles the hold touch gestures.
* Note that touch gesture support needs to be activated using the preprocessing variable polish.supportGestures
* The default implementation shows the commands of this item, but only when the preprocessing variable
* polish.Item.ShowCommandsOnHold is set to true.
*
* @return true when this gesture was handled
*/
protected boolean handleGestureHold(int x, int y) {
//#if polish.Item.ShowCommandsOnHold
if (this.commands != null && !this.isShowCommands && this.commands.size() > 1) {
this.isShowCommands = true;
if (this.commandsContainer != null) {
this.commandsContainer.focusChild(-1);
}
return true;
}
//#endif
return false;
}
/**
* Handles the swipe left gesture.
* @return true when the gesture was handled
*/
protected boolean handleGestureSwipeLeft(int x, int y) {
return false;
}
/**
* Handles the swipe right gesture.
* @return true when the gesture was handled
*/
protected boolean handleGestureSwipeRight(int x, int y) {
return false;
}
/**
* Adds a repaint request for this item's space.
* @param repaintRegion the clipping rectangle to which the repaint area should be added
*/
public void addRepaintArea( ClippingRegion repaintRegion ) {
int absX = getAbsoluteX();
int absY = getAbsoluteY();
int w = this.itemWidth;
int h = this.itemHeight + 1;
//#if polish.css.filter
RgbImage img = this.filterProcessedRgbImage;
if (img != null && (img.getHeight() > h || img.getWidth() > w)) {
int lo = this.layout;
int wFilter = img.getWidth();
int hFilter = img.getHeight();
int horDiff = wFilter - w;
int verDiff = hFilter - h;
if ((lo & LAYOUT_CENTER) == LAYOUT_CENTER) {
absX -= horDiff / 2;
w += horDiff;
} else if ((lo & LAYOUT_CENTER) == LAYOUT_RIGHT) {
absX -= horDiff;
} else {
w += horDiff;
}
if ((lo & LAYOUT_VCENTER) == LAYOUT_VCENTER) {
absY -= verDiff / 2;
h += verDiff;
} else if ((lo & LAYOUT_VCENTER) == LAYOUT_TOP) {
absY -= verDiff;
} else {
h += verDiff;
}
}
//#endif
//System.out.println("adding repaint area x=" + getAbsoluteX() + ", width=" + this.itemWidth + ", y=" + getAbsoluteY() + " for " + this);
repaintRegion.addRegion(
absX,
absY,
w,
h );
}
/**
* Adds a region relative to this item's content x/y start position.
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's content position
* @param y vertical start relative to this item's content position
* @param width width
* @param height height
* @see #getContentWidth()
* @see #getContentHeight()
*/
public void addRelativeToContentRegion(ClippingRegion repaintRegion, int x, int y, int width, int height) {
repaintRegion.addRegion(
getAbsoluteX() + this.contentX + x,
getAbsoluteY() + this.contentY + y,
width,
height
);
}
/**
* Adds a region relative to this item's background x/y start position.
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's background position
* @param y vertical start relative to this item's background position
* @param width width
* @param height height
* @see #getBackgroundWidth()
* @see #getBackgroundHeight()
*/
public void addRelativeToBackgroundRegion( ClippingRegion repaintRegion, int x, int y, int width, int height) {
repaintRegion.addRegion(
getAbsoluteX() + getBackgroundX() + x - 1,
getAbsoluteY() + getBackgroundY() + y - 1,
width + 2,
height + 2
);
}
/**
* Adds a region relative to this item's background x/y start position.
*
* @param animatedBackground the background that requests the repaint (could be a complete-background), can be null
* @param animatedBorder the border that requests the repaint (could be a complete-border), can be null
* @param repaintRegion the clipping region
* @param x horizontal start relative to this item's background position
* @param y vertical start relative to this item's background position
* @param width width
* @param height height
* @see #getBackgroundWidth()
* @see #getBackgroundHeight()
*/
public void addRelativeToBackgroundRegion( Background animatedBackground, Border animatedBorder, ClippingRegion repaintRegion, int x, int y, int width, int height) {
//#if polish.css.complete-background || polish.css.complete-border
boolean addAbsolute = false;
//#if polish.css.complete-background
addAbsolute = (this.completeBackground != null && animatedBackground == this.completeBackground);
//#endif
//#if polish.css.complete-border
addAbsolute |= (this.completeBorder != null && animatedBorder == this.completeBorder);
//#endif
if (addAbsolute) {
//System.out.println("adding absolute repaint: bgX=" + getBackgroundX() + ", bgY=" + getBackgroundY() + ", itemHeight-bgHeight=" + (this.itemHeight - this.backgroundHeight) + ", itemWidth-bgWidth=" + (this.itemWidth - this.backgroundWidth));
int padding = this.completeBackgroundPadding.getValue(this.availContentWidth);
repaintRegion.addRegion(
getAbsoluteX() + x - 1 - padding,
getAbsoluteY() + y - 1 - padding,
width + 2 + (padding << 1),
height + 2 + (this.itemHeight - this.backgroundHeight) + (padding << 1)
);
} else {
//#endif
repaintRegion.addRegion(
getAbsoluteX() + getBackgroundX() + x - 1,
getAbsoluteY() + getBackgroundY() + y - 1,
width + 2,
height + 2
);
//#if polish.css.complete-background || polish.css.complete-border
}
//#endif
}
/**
* Animates this item.
* Subclasses can override this method to create animations.
* The default implementation animates the background and the item view if present.
*
* @param currentTime the current time in milliseconds
* @param repaintRegion the repaint area that needs to be updated when this item is animated
* @see #addRelativeToContentRegion(ClippingRegion, int, int, int, int)
*/
public void animate( long currentTime, ClippingRegion repaintRegion) {
if (this.label != null) {
this.label.animate( currentTime, repaintRegion );
}
if (this.background != null) {
this.background.animate( this.screen, this, currentTime, repaintRegion );
}
if (this.border != null) {
this.border.animate( this.screen, this, currentTime, repaintRegion );
}
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.animate( this.screen, this, currentTime, repaintRegion );
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.animate( this.screen, this, currentTime, repaintRegion );
}
//#endif
if (animate()) {
addRepaintArea(repaintRegion);
}
//#if polish.css.view-type
if (this.view != null) {
this.view.animate(currentTime, repaintRegion);
}
//#endif
//#if tmp.supportTouchGestures
if (this.isPressed && (this.gestureStartTime != 0) && (currentTime - this.gestureStartTime > 500)) {
boolean handled = handleGesture( GestureEvent.GESTURE_HOLD, this.gestureStartX, this.gestureStartY );
if (handled) {
this.isIgnorePointerReleaseForGesture = true;
notifyItemPressedEnd();
this.gestureStartTime = 0;
Screen scr = getScreen();
repaintRegion.addRegion( scr.contentX, scr.contentY, scr.contentWidth, scr.contentHeight );
} else {
this.gestureStartTime = 0;
}
}
//#endif
//#if polish.Item.ShowCommandsOnHold
if (this.isShowCommands && this.commandsContainer != null) {
this.commandsContainer.animate(currentTime, repaintRegion);
}
//#endif
}
/**
* Animates this item.
* Subclasses can override this method to create animations.
* The default implementation returns false
*
* @return true when this item has been animated.
* @see #animate(long, ClippingRegion)
*/
public boolean animate() {
return false;
}
/**
* Retrieves the approriate style for focusing this item.
* This is either a item specific one or one inherit by its parents.
* When no parent has a specific focus style, the StyleSheet.focusedStyle is used.
*
* @return the style used for focussing this item.
*/
public Style getFocusedStyle() {
if (!this.isStyleInitialised) {
if (this.style != null) {
setStyle( this.style );
}
//#ifdef polish.useDynamicStyles
else {
initStyle();
}
//#endif
}
Style focStyle;
if (this.focusedStyle != null) {
focStyle = this.focusedStyle;
} else if (this.parent != null) {
focStyle = this.parent.getFocusedStyle();
} else {
focStyle= StyleSheet.focusedStyle;
}
//#if polish.css.visited-style
if (this.hasBeenVisited && focStyle != null) {
Style visitedStyle = (Style) focStyle.getObjectProperty("visited-style");
//#debug
System.out.println("found visited style " + (visitedStyle != null ? visitedStyle.name : "<none>") + " in " + focStyle.name);
if (visitedStyle != null) {
focStyle = visitedStyle;
}
}
//#endif
return focStyle;
}
//#if polish.hasPointerEvents
/**
* Handles the behavior of the virtual keyboard when the item is focused.
* By default, the virtual keyboard is hidden. Components which need to have the virtual keyboard
* shown when they are focused can override this method.
*/
public void handleOnFocusSoftKeyboardDisplayBehavior() {
DeviceControl.hideSoftKeyboard();
}
//#endif
/**
* Focuses this item.
*
* @param newStyle the style which is used to indicate the focused state
* @param direction the direction from which this item is focused,
* either Canvas.UP, Canvas.DOWN, Canvas.LEFT, Canvas.RIGHT or 0.
* When 0 is given, the direction is unknown.
* @return the current style of this item
*/
protected Style focus( Style newStyle, int direction ) {
//#debug
System.out.println("focus " + this);
Style oldStyle = this.style;
if ((!this.isFocused) || (newStyle != this.style && newStyle != null)) {
if (!this.isStyleInitialised && oldStyle != null) {
setStyle( oldStyle );
}
if (newStyle == null) {
newStyle = getFocusedStyle();
}
//#if polish.css.view-type
this.preserveViewType = true;
//#endif
this.isFocused = true;
this.isJustFocused = true;
setStyle( newStyle );
//#if polish.css.pressed-style
if (this.isPressed) {
this.normalStyle = newStyle;
}
//#endif
//#if polish.css.view-type
this.preserveViewType = false;
//#endif
// now set any commands of this item:
if (this.commands != null) {
showCommands();
}
if (oldStyle == null) {
oldStyle = StyleSheet.defaultStyle;
}
//#if polish.android
if (this._androidView != null) {
this._androidView.requestFocus();
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_FOCUS, this, new Integer(direction));
//#endif
}
return oldStyle;
}
/**
* Removes the focus from this item.
*
* @param originalStyle the original style which will be restored.
*/
protected void defocus( Style originalStyle ) {
//#debug
System.out.println("defocus " + this + " with style " + (originalStyle != null ? originalStyle.name : "<no style>"));
if (this.isPressed) {
notifyItemPressedEnd();
}
this.backgroundYOffset = 0;
this.isFocused = false;
if (originalStyle != null) {
setStyle( originalStyle );
if (this.label != null) {
Style prevLabelStyle = this.label.style;
//#if polish.css.label-style
prevLabelStyle = (Style) originalStyle.getObjectProperty("label-style");
if (prevLabelStyle == null) {
prevLabelStyle = this.label.style;
}
//#endif
this.label.defocus(prevLabelStyle);
}
} else {
this.background = null;
this.border = null;
this.style = null;
}
// now remove any commands which are associated with this item:
if (this.commands != null) {
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
}
//#if polish.Item.ShowCommandsOnHold
this.isShowCommands = false;
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_DEFOCUS, this, null);
//#endif
}
/**
* Shows the commands on the screen.
*/
public void showCommands() {
COMMANDS.clear();
addCommands( COMMANDS );
Screen scr = getScreen();
if (scr != null) {
scr.setItemCommands( COMMANDS, this );
}
}
// /**
// * Shows the commands on the screen.
// *
// * @param commandsList an ArrayList with the commands from this item.
// */
// protected void showCommands(ArrayList commandsList) {
// addCommands(commandsList);
// if (this.commands != null) {
// commandsList.addAll( this.commands );
// }
// if (this.parent != null) {
// this.parent.showCommands(commandsList);
// } else {
// Screen scr = getScreen();
// if (scr != null) {
// scr.setItemCommands( commandsList, this );
// }
// }
// }
/**
* Adds all commands to the specified list.
*
* @param commandsList an ArrayList into which the commands from this item should be added.
*/
protected void addCommands( ArrayList commandsList) {
if (this.commands != null) {
commandsList.addAll( this.commands );
}
if (this.parent != null) {
this.parent.addCommands(commandsList);
}
}
/**
* Tries to handle the specified command.
* The item checks if the command belongs to this item and if it has an associated ItemCommandListener.
* Only then it handles the command.
* @param cmd the command
* @return true when the command has been handled by this item
*/
protected boolean handleCommand( Command cmd ) {
if (cmd == this.defaultCommand) {
notifyVisited();
}
if (cmd.commandAction(this, null)) {
return true;
}
ItemCommandListener listener = this.itemCommandListener;
if (this.commands == null || listener == null || !this.commands.contains(cmd) ) {
//#if polish.Item.suppressDefaultCommand
if (listener == null || cmd != this.defaultCommand) {
//#endif
return false;
//#if polish.Item.suppressDefaultCommand
}
//#endif
}
try {
listener.commandAction( cmd, this );
return true;
} catch (Exception e) {
//#debug error
System.out.println("Unable to handle command " + cmd.getLabel() + e );
}
return false;
}
//#if polish.LibraryBuild
/**
* Tries to handle the specified command.
* The item checks if the command belongs to this item and if it has an associated ItemCommandListener.
* Only then it handles the command.
* @param cmd the command
* @return true when the command has been handled by this item
*/
protected boolean handleCommand( javax.microedition.lcdui.Command cmd ) {
return false;
}
//#endif
/**
* Called by the system to notify the item that it is now at least
* partially visible, when it previously had been completely invisible.
* The item may receive <code>paint()</code> calls after
* <code>showNotify()</code> has been called.
*
* <p>The default implementation of this method sets the isShown field to true and calls showNotify on style elements.</p>
*/
protected void showNotify()
{
if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
}
this.isShown = true;
if (this.label != null) {
this.label.showNotify();
}
if (this.background != null) {
this.background.showNotify();
}
if (this.border != null) {
this.border.showNotify();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.showNotify();
}
//#endif
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.showNotify();
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.showNotify();
}
//#endif
//#if polish.blackberry
if (this.isFocused && this._bbField != null) {
Display.getInstance().notifyFocusSet(this);
}
//#endif
//#if polish.android
if (this._androidView != null) {
AndroidDisplay.getInstance().onShow(this._androidView, this);
}
//#endif
//#if tmp.handleEvents
//System.out.println("triggering event 'show' for " + this + " with style " + (this.style != null ? this.style.name : "<null>") + ", animations=" + (this.style != null ? "" + this.style.getAnimations() : "<null>"));
if (!this.hasBeenShownBefore) {
EventManager.fireEvent( EventManager.EVENT_SHOW_FIRST_TIME, this, null );
this.hasBeenShownBefore = true;
}
EventManager.fireEvent( EventManager.EVENT_SHOW, this, null );
//#endif
}
/**
* Called by the system to notify the item that it is now completely
* invisible, when it previously had been at least partially visible. No
* further <code>paint()</code> calls will be made on this item
* until after a <code>showNotify()</code> has been called again.
*
* <p>The default implementation of this method sets the isShown field to false and calls hideNotify on style elements.</p>
*/
protected void hideNotify()
{
this.isShown = false;
if (this.label != null) {
this.label.hideNotify();
}
if (this.background != null) {
this.background.hideNotify();
}
if (this.border != null) {
this.border.hideNotify();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.hideNotify();
}
//#endif
//#if polish.css.complete-background
if (this.completeBackground != null) {
this.completeBackground.hideNotify();
}
//#endif
//#if polish.css.complete-border
if (this.completeBorder != null) {
this.completeBorder.hideNotify();
}
//#endif
if (this.isPressed) {
notifyItemPressedEnd();
}
//#if polish.android
if (this._androidView != null) {
AndroidDisplay.getInstance().onHide(this._androidView, this);
}
//#endif
//#if tmp.handleEvents
EventManager.fireEvent( EventManager.EVENT_HIDE, this, null );
//#endif
}
/**
* Shows the screen to which item belongs to and focusses this item.
* This method is the equivalent to display.setCurrentItem( item ).
*
* @param display the display of the MIDlet.
*/
public void show( Display display ) {
Screen myScreen = getScreen();
if ( myScreen == null ) {
//#debug warn
System.out.println("Unable to show this item, since the screen is not known.");
return;
}
myScreen.focus( this );
display.setCurrent( myScreen );
}
/**
* Releases all (memory intensive) resources such as images or RGB arrays of this item.
* The default implementation releases any background resources.
*/
public void releaseResources() {
if (this.background != null) {
this.background.releaseResources();
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.releaseResources();
}
//#endif
//#if polish.css.filter && polish.midp2
if (this.filters != null) {
for (int i=0; i<this.filters.length; i++) {
RgbFilter filter = this.filters[i];
filter.releaseResources();
}
}
//#endif
}
/**
* Destroy the item by removing all references to parent, screen, listeners etc.
* and calling releaseResources()
*/
public void destroy() {
releaseResources();
AnimationThread.removeAnimationItem(this);
if(null != this.itemCommandListener)
this.itemCommandListener = null;
if(null != this.itemStateListener)
this.itemStateListener = null;
if(null != this.parent)
this.parent = null;
if(null != this.screen)
this.screen = null;
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.destroy();
this.view = null;
}
//#endif
}
/**
* Sets an arbitrary attribute for this item.
*
* @param key the key for the attribute
* @param value the attribute value
*/
public void setAttribute( Object key, Object value ) {
if (this.attributes == null) {
this.attributes = new HashMap();
}
this.attributes.put( key, value );
}
/**
* Gets an previously added attribute of this item.
*
* @param key the key of the attribute
* @return the attribute value, null if none has been registered under the given key before
*/
public Object getAttribute( Object key ) {
if (this.attributes == null) {
return null;
}
return this.attributes.get( key );
}
/**
* Removes an previously added attribute of this item.
*
* @param key the key of the attribute
* @return the attribute value, null if none has been registered under the given key before
*/
public Object removeAttribute(Object key)
{
if (this.attributes == null) {
return null;
}
return this.attributes.remove( key );
}
/**
* Returns a HashMap object with all registered attributes.
*
* @return a HashMap object with all attribute key/value pairs, null if no attribute was stored before.
*/
public HashMap getAttributes() {
return this.attributes;
}
/**
* Determines if this item or one of it's children is within the specified point.
* The default implementation returns this item or this item's label when the position fits.
*
* @param relX the x position of the point relative to this item's left position
* @param relY the y position of the point relative to this item's top position
* @return this item or one of it's children, when the position fits, otherwise null is returned
*/
public Item getItemAt( int relX, int relY ) {
if ( isInItemArea(relX, relY) ) {
if (this.label != null) {
Item item = this.label.getItemAt(relX, relY);
if (item != null) {
return item;
}
}
return this;
}
return null;
}
/**
* Retrieves this item's current absolute horizontal position
*
* @return the absolute x position of this item in pixel.
*/
public int getAbsoluteX() {
int absX = this.relativeX;
// if (this.label != null && this.useSingleRow && !this.isLayoutCenter && !this.isLayoutRight) {
// // hack for left align with additional label:
// absX += this.contentX;
// }
Item item = this.parent;
if (item != null && item.label == this && item.useSingleRow) {
// this is the label of another item
absX -= item.contentX;
}
//#if polish.css.x-adjust
if (this.xAdjustment != null) {
int value = this.xAdjustment.getValue(this.itemWidth);
absX += value;
}
//#endif
while (item != null) {
absX += item.relativeX + item.contentX;
item = item.parent;
}
return absX;
}
/**
* Retrieves this item's current absolute vertical position
*
* @return the absolute y position of this item in pixel.
*/
public int getAbsoluteY() {
int absY = this.relativeY; // + this.contentY; in that case no label is included anymore
Item item = this.parent;
if (item != null && item.label == this) {
absY -= item.contentY;
}
//#if polish.css.y-adjust
if (this.yAdjustment != null) {
absY += this.yAdjustment.getValue(this.itemHeight);
}
//#endif
while (item != null) {
absY += item.relativeY + item.contentY;
if (item instanceof Container) {
absY += ((Container)item).yOffset;
}
item = item.parent;
}
return absY;
}
/**
* Sets the absolute vertical position of this item.
* Note that results may vary depending on the view-type of the root container.
*
* @param absY the absolute y position of this item in pixel.
*/
public void setAbsoluteY(int absY) {
// find out vertical offset for root container:
int currentAbsY = getAbsoluteY();
int diff = absY - currentAbsY;
//System.out.println("setting absY to " + absY + ", current=" + currentAbsY + ", diff=" + diff + " for item " + this);
Item item = this;
while (item.parent != null) {
item = item.parent;
}
if (item instanceof Container) {
Container container = (Container)item;
int offset = container.getScrollYOffset() + diff;
//System.out.println("resulting in scrollOffset=" + offset + ", currentScrollOffset=" + container.getScrollYOffset());
container.setScrollYOffset(offset, false);
}
//System.out.println("after setAbsoluteY=" + getAbsoluteY() + ", should be=" + absY);
}
/**
* Retrieves the start of the content relative to this item's absolute x position.
* @return the horizontal start of the content
* @see #getAbsoluteX()
*/
public int getContentX() {
return this.contentX;
}
/**
* Retrieves the start of the content relative to this item's absolute y position.
* @return the vertical start of the content
* @see #getAbsoluteY()
*/
public int getContentY() {
return this.contentY;
}
/**
* Retrieves the width of the content.
* @return the content width in pixels
*/
public int getContentWidth()
{
return this.contentWidth;
}
/**
* Retrieves the height of the content.
* @return the content height in pixels
*/
public int getContentHeight()
{
return this.contentHeight;
}
/**
* Retrieves the width of the content.
* @return the content width in pixels
*/
public int getAvailableContentWidth()
{
return this.availContentWidth;
}
/**
* Retrieves the height of the content.
* @return the content height in pixels
*/
public int getAvailableContentHeight()
{
return this.availContentHeight;
}
/**
* Retrieves the height of the area that this item covers.
* This can be different from the original itemHeight for items that have popups such as the POPUP ChoiceGroup
* @return the height of the item's area in pixel
*/
public int getItemAreaHeight()
{
return Math.max( this.itemHeight, this.marginTop + this.backgroundHeight + this.marginBottom );
}
/**
* Retrieves the start of the background relative to this item's origin.
*
* @return the horizontal background start in pixels.
*/
public int getBackgroundX() {
//#if polish.css.include-label
if (this.includeLabel) {
return this.marginLeft;
} else {
//#endif
return this.contentX - this.paddingLeft;
//#if polish.css.include-label
}
//#endif
}
/**
* Retrieves the start of the background relative to this item's origin.
*
* @return the horizontal background start in pixels.
*/
public int getBackgroundY() {
//#if polish.css.include-label
if (this.includeLabel) {
return this.marginTop;
} else {
//#endif
return this.contentY - this.paddingTop;
//#if polish.css.include-label
}
//#endif
}
/**
* Retrieves the width of this item's background.
* @return the width in pixels
*/
public int getBackgroundWidth() {
return this.backgroundWidth;
}
/**
* Retrieves the height of this item's background.
* @return the height in pixels
*/
public int getBackgroundHeight() {
return this.backgroundHeight;
}
/**
* Retrieves the parent of this item.
*
* @return this item's parent.
*/
public Item getParent() {
return this.parent;
}
/**
* Retrieves the parent root of this item.
*
* @return this item's super parent, either this item itself or it's last known ancestor.
*/
public Item getParentRoot() {
Item p = this;
while (p.parent != null) {
p = p.parent;
}
return p;
}
/**
* Sets a parent for this item.
* @param parent the parent of this item
*/
public void setParent(Item parent)
{
this.parent = parent;
}
//#if polish.midp
/**
* Sets a parent for this item.
* @param parent the parent of this item
*/
public void setParent(javax.microedition.lcdui.Item parent)
{
// ignore
}
//#endif
/**
* Sets the visible status of this item.
* Invisible items occupy no space on the UI screen and cannot be focused/traversed.
* Note that you can call this method ONLY when the preprocessing variable polish.supportInvisibleItems is true or when you use the CSS attribute 'visible' in your polish.css file.
* @param visible true when this item should become visible.
*/
public void setVisible( boolean visible ) {
//#if tmp.invisible
boolean invisible = !visible;
if (invisible == this.isInvisible) {
return;
}
// if (visible) {
// System.out.println("+++ SETTING VISIBLE: " + this );
// } else {
// System.out.println("--- SETTING INVISIBLE: " + this );
// }
if (this.parent instanceof Container) {
Container parentContainer = (Container) this.parent;
if (invisible && this.isFocused) {
//System.out.println("making focused item invisible: " + this);
// remove any item commands:
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
int itemIndex = parentContainer.indexOf( this );
boolean isFocusSet = parentContainer.focusClosestItemAbove( itemIndex );
this.isFocused = false;
//System.out.println("new focus set: " + isFocusSet + ", new index=" + parentContainer.focusedIndex + ", this.index=" + itemIndex );
if (isFocusSet) {
if (parentContainer.focusedIndex > itemIndex ) {
// focused has moved downwards, since the above item is now invisible,
// adjust the scrolling accordingly:
int offset = parentContainer.yOffset + this.itemHeight + parentContainer.paddingVertical;
if (offset > 0) {
offset = 0;
}
//System.out.println("setting parent scroll offset to " + offset );
parentContainer.setScrollYOffset( offset, false );
} else {
parentContainer.scroll( 0, parentContainer.focusedItem, true);
}
} else {
parentContainer.focusChild(-1);
}
if (this instanceof Container) {
((Container)this).focusChild(-1);
}
} else if (!this.isFocused && parentContainer.focusedIndex > parentContainer.indexOf(this)) {
// adjust scrolling so that the focused element of the parent container stays in the current position:
int offset;
if (invisible) {
offset = parentContainer.getScrollYOffset() + this.itemHeight;
if (offset > 0) {
offset = 0;
}
//System.out.println("invisible: adjusting yScrollOffset with itemHeight=" + this.itemHeight + " to " + (offset > 0 ? 0 : offset) );
parentContainer.setScrollYOffset( offset, false );
} else {
int height = this.invisibleItemHeight;
if (height == 0 && this.parent != null) {
//System.out.println("visible getting height for available width of " + this.parent.contentWidth );
this.isInvisible = false;
setInitialized(false);
height = getItemHeight( this.parent.contentWidth, this.parent.contentWidth, this.parent.contentHeight );
} else {
this.itemHeight = height;
}
offset = parentContainer.getScrollYOffset() - height;
//System.out.println("visible: adjusting yScrollOffset with height=" + height + " to " + offset );
parentContainer.setScrollYOffset( offset, false );
}
// adjust the internal Y position:
Item parentItem = this;
while (parentItem != null) {
if (parentItem.internalX != NO_POSITION_SET) {
if (invisible) {
parentItem.internalY -= this.itemHeight;
} else {
parentItem.internalY += this.itemHeight;
}
}
parentItem = parentItem.parent;
}
} else if (parentContainer.focusedIndex == -1)
{
if(visible)
{
//No other container is set to focused
//so it is ASSUMED that this is the only
//visisble item
this.relativeY = 0;
parentContainer.setScrollYOffset(0);
parentContainer.focusChild(parentContainer.indexOf(this));
}
}
}
if ( invisible ) {
this.invisibleAppearanceModeCache = this.appearanceMode;
this.invisibleItemHeight = this.itemHeight;
this.appearanceMode = PLAIN;
} else {
this.appearanceMode = this.invisibleAppearanceModeCache;
}
this.isInvisible = invisible;
requestInit();
//#endif
}
/**
* Gets the visible status of this item.
* Invisible items occupy no space on the UI screen and cannot be focused/traversed.
* Note that you can call this method ONLY when the preprocessing variable polish.supportInvisibleItems is true or when you use the 'visible' CSS attribute.
* @return true when this item is visible.
*/
public boolean isVisible() {
boolean result;
//#if !tmp.invisible
result = false;
//#else
result = !this.isInvisible;
//#endif
return result;
}
//#if polish.debug.error || polish.keepToString
/**
* Generates a String representation of this item.
* This method is only implemented when the logging framework is active or the preprocessing variable
* "polish.keepToString" is set to true.
* @return a String representation of this item.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
if (this.label != null && this.label.text != null) {
buffer.append( '"' ).append( this.label.text ).append("\"");
}
if (this.style != null) {
buffer.append(" [").append(this.style.name).append("]");
}
buffer.append(": ");
buffer.append( super.toString() );
return buffer.toString();
}
//#endif
/**
* Determines whether this item contains the given command.
*
* @param command the command
* @return true when this item contains this command
*/
public boolean containsCommand(Command command) {
return this.commands != null && this.commands.contains(command);
}
/**
* @return the default command
*/
public Command getDefaultCommand() {
return this.defaultCommand;
}
/**
* @return the commands associated with this item in an arraylist - might be null!
*/
public ArrayList getItemCommands() {
return this.commands;
}
/**
* Sets the initialized state of this item.
* @param initialized true when this item is deemed to be initialized, otherwise false. When setting to 'false' the item will run its init() and initContent() methods at the next option.
*/
public void setInitialized(boolean initialized)
{
this.isInitialized = initialized;
}
/**
* Determines the initialization state of this item
* @return true when it is initialized, false otherwise
*/
public boolean isInitialized()
{
return this.isInitialized;
}
/**
* Sets the item's complete height
* @param height the height in pixel
*/
public void setItemHeight( int height ) {
int diff = height - this.itemHeight;
//#debug
System.out.println("setting item height " + height + ", diff=" + diff + ", vcenter=" +isLayoutVerticalCenter() + " for " + this );
this.itemHeight = height;
this.backgroundHeight += diff;
if (isLayoutVerticalCenter()) {
this.contentY += diff/2;
} else if (isLayoutBottom()) {
this.contentY += diff;
}
}
/**
* Sets the item's complete width
* @param width the width in pixel
*/
public void setItemWidth( int width ) {
int diff = width - this.itemWidth;
//#debug
System.out.println("setting item width " + width + ", diff=" + diff + ", hcenter=" +isLayoutCenter() + " for " + this );
this.itemWidth = width;
this.backgroundWidth += diff;
if (isLayoutCenter()) {
this.contentX += diff/2;
} else if (isLayoutRight()) {
this.contentX += diff;
}
}
/**
* Retrieves the internal area's horizontal start relative to this item's content area
* @return the horizontal start in pixels, -1 if it not set
*/
public int getInternalX() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalX;
}
/**
* Retrieves the internal area's vertical start relative to this item's content area
* @return the vertical start in pixels, -1 if it not set
*/
public int getInternalY() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalY;
}
/**
* Retrieves the internal area's vertical width
* @return the vertical width in pixels, -1 if it not set
*/
public int getInternalWidth() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalWidth;
}
/**
* Retrieves the internal area's vertical height
* @return the vertical height in pixels, -1 if it not set
*/
public int getInternalHeight() {
if (this.internalX == NO_POSITION_SET) {
return -1;
}
return this.internalHeight;
}
/**
* Fires an event for this item as well as its subitems like its label.
*
* @param eventName the name of the event
* @param eventData the event data
* @see EventManager#fireEvent(String, Object, Object)
*/
public void fireEvent( String eventName, Object eventData ) {
if (this.label != null) {
EventManager.fireEvent(eventName, this.label, eventData);
}
EventManager.fireEvent(eventName, this, eventData);
}
/**
* Updates the internal area on BB and similar platforms that contain native fields.
*/
public void updateInternalArea() {
// subclasses may override this.
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a right layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutRight()
{
return this.isLayoutRight;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a left layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutLeft()
{
return !(this.isLayoutRight | this.isLayoutCenter);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a center layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutCenter()
{
return this.isLayoutCenter;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a top layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutTop()
{
return (this.layout & LAYOUT_BOTTOM) == 0;
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a bottom layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutBottom()
{
return ((this.layout & LAYOUT_VCENTER) == LAYOUT_BOTTOM);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vcenter layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalCenter()
{
return ((this.layout & LAYOUT_VCENTER) == LAYOUT_VCENTER);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vshrink layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalShrink() {
return ((this.layout & LAYOUT_VSHRINK) == LAYOUT_VSHRINK);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a vexpand layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutVerticalExpand() {
return ((this.layout & LAYOUT_VEXPAND) == LAYOUT_VEXPAND);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a horizontal expand layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutExpand() {
return ((this.layout & LAYOUT_EXPAND) == LAYOUT_EXPAND);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a horizontal shrink layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutShrink() {
return ((this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a newwline-after layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutNewlineAfter() {
return ((this.layout & LAYOUT_NEWLINE_AFTER) == LAYOUT_NEWLINE_AFTER);
}
/**
* Determines the layout of this item.
* Note that either setLayout() or init() has to be called before this method returns valid values.
*
* @return true when the item has a newwline-after layout.
* @see #setLayout(int)
* @see #init(int,int,int)
*/
public boolean isLayoutNewlineBefore() {
return ((this.layout & LAYOUT_NEWLINE_BEFORE) == LAYOUT_NEWLINE_BEFORE);
}
public void setItemTransition( ItemTransition transition ) {
this.itemTransition = transition;
}
public Image toImage() {
Image img;
//#if polish.midp2
int[] pixels = new int[ this.itemWidth * this.itemHeight ];
img = Image.createRGBImage( pixels, this.itemWidth, this.itemHeight, true );
//#else
img = Image.createImage( this.itemWidth, this.itemHeight );
//#endif
Graphics g = img.getGraphics();
ItemTransition t = this.itemTransition;
this.itemTransition = null;
paint( 0, 0, 0, this.itemWidth, g );
this.itemTransition = t;
return img;
}
public RgbImage toRgbImage() {
return new RgbImage( toImage(), true );
}
/**
* Determines whether this item is interactive and thus can be selected.
* @return true when this item is deemed to be interactive
*/
public boolean isInteractive() {
return this.appearanceMode != PLAIN;
}
/**
* Resets the style of this item and all its children (if any).
* This is useful when you have applied changes to this Item's style or one of its elements.
* @param recursive true when all subelements of this Item should reset their style as well.
* @see Screen#resetStyle(boolean)
* @see UiAccess#resetStyle(Screen,boolean)
* @see UiAccess#resetStyle(Item,boolean)
*/
public void resetStyle(boolean recursive) {
if (this.style != null) {
setStyle(this.style);
}
if (recursive) {
if (this.label != null) {
this.label.resetStyle(recursive);
}
}
}
/**
* Notifies this item about a new screen size.
* The default implementation just checks if the design should switch to portrait or landscape-style (if those CSS attributes are used).
* The item will be re-initialized with its available dimensions using init(int,int,int) soon.
* @param screenWidth the screen width
* @param screenHeight the screen height
*/
public void onScreenSizeChanged( int screenWidth, int screenHeight ) {
//#debug
System.out.println("onScreenSizeChanged to " + screenWidth + ", " + screenHeight + " for " + this);
if (this.label != null) {
this.label.onScreenSizeChanged(screenWidth, screenHeight);
}
//#ifdef polish.css.view-type
if (this.view != null) {
this.view.onScreenSizeChanged(screenWidth, screenHeight);
}
//#endif
//#if polish.css.portrait-style || polish.css.landscape-style
if (!this.isStyleInitialised && this.style != null) {
setStyle( this.style );
}
Style newStyle = null;
if (screenWidth > screenHeight) {
if (this.landscapeStyle != null && this.style != this.landscapeStyle) {
newStyle = this.landscapeStyle;
}
} else if (this.portraitStyle != null && this.style != this.portraitStyle){
newStyle = this.portraitStyle;
}
Style oldStyle = null;
if (newStyle != null) {
//#debug
System.out.println("onScreenSizeChanged(): setting new style " + newStyle.name + " for " + this);
oldStyle = this.style;
setStyle( newStyle );
//#if polish.css.pressed-style
if (this.isPressed) {
this.normalStyle = newStyle;
}
//#endif
if (this.isFocused) {
if (this.parent instanceof Container) {
Container cont = (Container)this.parent;
cont.itemStyle = newStyle;
setStyle( getFocusedStyle() );
}
} else if (oldStyle != null && this.parent instanceof Container) {
Container cont = (Container)this.parent;
if (cont.itemStyle == oldStyle) {
cont.itemStyle = newStyle;
}
}
}
//#endif
}
/**
* Retrieves the available width for this item.
* @return the available width in pixel, can be 0 when this item has not yet been initialized
*/
public int getAvailableWidth() {
return this.availableWidth;
}
/**
* Retrieves the available height for this item.
* @return the available height in pixel, can be 0 when this item has not yet been initialized
*/
public int getAvailableHeight() {
return this.availableHeight;
}
/**
* Sets an UiEventListener for the this item and its children.
* @param listener the listener, use null to remove a listener
*/
public void setUiEventListener(UiEventListener listener) {
this.uiEventListener = listener;
}
/**
* Retrieves the UiEventListener for this item or for one of its parents.
* @return the listener or null, if none has been registered
*/
public UiEventListener getUiEventListener() {
UiEventListener listener = this.uiEventListener;
if (listener == null) {
Item parentItem = this.parent;
while (parentItem != null && listener == null) {
listener = parentItem.uiEventListener;
parentItem = parentItem.parent;
}
if (listener == null) {
listener = getScreen().getUiEventListener();
}
}
return listener;
}
/**
* Retrieves the RGB data of this item.
* This method only works on MIDP 2.0+ devices.
*
* @return the RGB data as an int array.
*/
public int[] getRgbData() {
return getRgbData( true, 255 );
}
/**
* Retrieves the RGB data of this item.
* This method only works on MIDP 2.0+ devices.
*
* @param supportTranslucency true when not only transparent but also translucent parts of the item should be rendered correctly
* @param rgbOpacity The opacity of the item between 0 (fully transparent) and 255 (fully opaque)
* @return the RGB data as an int array.
*/
public int[] getRgbData( boolean supportTranslucency, int rgbOpacity ) {
int[] result = new int[0];
//#if polish.midp2
if (this.itemWidth < 1 || this.itemHeight < 1) {
//#debug error
System.out.println("Unable to retrieve RGB data for item with a dimension of " + this.itemWidth + "x" + this.itemHeight + " for " + this );
return new int[0];
}
Image image = Image.createImage( this.itemWidth, this.itemHeight );
if (supportTranslucency) {
// we use a two-pass painting for determing translucent pixels as well:
// in the first run we paint it on a black background (dataBlack),
// in the second we use a white background (dataWhite).
// We then compare the pixels in dataBlack and dataWhite:
// a) when a pixel is black in dataBlack and white and dataWhite it is fully transparent
// b) when a pixel has the same value in dataBlack and in dataWhite it is fully opaque
// c) when the pixel has different values it contains translucency - we can extract the original value from the difference between data1 and data2.
// The solution is based on this formula for determining the final green component value when adding a pixel with alpha value on another opaque pixel:
// final_green_value = ( pixel1_green * alpha + pixel2_green * ( 255 - alpha ) ) / 255
// When can work our way backwards to determine the original green and alpha values.
Graphics g = image.getGraphics();
int bgColorBlack = 0x0;
g.setColor(bgColorBlack);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
int[] transparentColorRgb = new int[1];
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
bgColorBlack = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] dataBlack = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(dataBlack, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
int bgColorWhite = 0xffffff;
g.setColor(bgColorWhite);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
bgColorWhite = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] dataWhite = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(dataWhite, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
rgbOpacity = (rgbOpacity << 24) | (0x00ffffff);
result = new int[ dataBlack.length ];
int lastPixelWhite = 0;
int lastPixelBlack = 0;
int lastPixelResult = 0;
// ensure transparent parts are indeed transparent
for (int i = 0; i < dataBlack.length; i++) {
int pixelBlack = dataBlack[i];
int pixelWhite = dataWhite[i];
if (pixelBlack == pixelWhite) {
result[i] = pixelBlack & rgbOpacity;
} else if (pixelBlack != bgColorBlack || pixelWhite != bgColorWhite ) {
if (pixelBlack == lastPixelBlack && pixelWhite == lastPixelWhite) {
result[i] = lastPixelResult;
} else {
// this pixel contains translucency:
int redBlack = (pixelBlack & 0xff0000) >> 16;
int greenBlack = (pixelBlack & 0xff00) >> 8;
int blueBlack = (pixelBlack & 0xff);
int redWhite = (pixelWhite & 0xff0000) >> 16;
int greenWhite = (pixelWhite & 0xff00) >> 8;
int blueWhite = (pixelWhite & 0xff);
int originalAlpha = 0;
int originalRed;
if (redBlack == 0 && redWhite == 255) {
originalRed = 0;
} else {
if (redBlack == 0) {
redBlack = 1;
} else if (redWhite == 255) {
redWhite = 254;
}
originalRed = (255 * redBlack) / (redBlack - redWhite + 255);
originalAlpha = redBlack - redWhite + 255;
}
int originalGreen;
if (greenBlack == 0 && greenWhite == 255) {
originalGreen = 0;
} else {
if (greenBlack == 0) {
greenBlack = 1;
} else if (greenWhite == 255) {
greenWhite = 254;
}
originalGreen = (255 * greenBlack) / (greenBlack - greenWhite + 255);
originalAlpha = greenBlack - greenWhite + 255;
}
int originalBlue;
if (blueBlack == 0 && blueWhite == 255) {
originalBlue = 0;
} else {
if (blueBlack == 0) {
blueBlack = 1;
} else if (blueWhite == 255) {
blueWhite = 254;
}
originalBlue = (255 * blueBlack) / (blueBlack - blueWhite + 255);
originalAlpha = blueBlack - blueWhite + 255;
}
if ( originalAlpha > 255 ) {
originalAlpha = 255;
}
lastPixelWhite = pixelWhite;
lastPixelBlack = pixelBlack;
lastPixelResult = ((originalAlpha << 24) | (originalRed << 16) | (originalGreen << 8) | originalBlue) & rgbOpacity;
result[i] = lastPixelResult;
}
}
}
} else {
int transparentColor = 0x12345678;
Graphics g = image.getGraphics();
g.setColor(transparentColor);
g.fillRect(0, 0, this.itemWidth, this.itemHeight );
int[] transparentColorRgb = new int[1];
image.getRGB(transparentColorRgb, 0, 1, 0, 0, 1, 1 );
transparentColor = transparentColorRgb[0];
this.paint( 0, 0, 0, this.itemWidth, g );
int[] itemRgbData = new int[ this.itemWidth * this.itemHeight ];
image.getRGB(itemRgbData, 0, this.itemWidth, 0, 0, this.itemWidth, this.itemHeight );
boolean addOpacity = (rgbOpacity != 255);
rgbOpacity = (rgbOpacity << 24) | (0x00ffffff);
// ensure transparent parts are indeed transparent
for (int i = 0; i < itemRgbData.length; i++) {
int data = itemRgbData[i];
if( data == transparentColor ) {
itemRgbData[i] = 0;
} else if (addOpacity) {
itemRgbData[i] = data & rgbOpacity;
}
}
}
//#endif
return result;
}
/**
* Fires a cycle event.
* The default implementation forwards the event to the cycle listener if one is registered, otherwise it will be forwarded to the parent item.
* When there is neither a parent item or a cycle listener, this method will return true.
*
* @param direction the direction, e.g. CycleListener.DIRECTION_BOTTOM_TO_TOP
* @return true when the cycling process can continue, false when the cycle event should be aborted
* @see CycleListener#DIRECTION_BOTTOM_TO_TOP
* @see CycleListener#DIRECTION_TOP_TO_BOTTOM
* @see CycleListener#DIRECTION_LEFT_TO_RIGHT
* @see CycleListener#DIRECTION_RIGHT_TO_LEFT
* @see #setCycleListener(CycleListener)
* @see #getCycleListener()
*/
public boolean fireContinueCycle( int direction ) {
if (this.cycleListener != null) {
return this.cycleListener.onCycle(this, direction);
}
if (this.parent != null) {
return this.parent.fireContinueCycle(direction);
}
return true;
}
/**
* Allows to specify a cycle listener
* @param listener the listener, use null to deregister the listener
* @see #getCycleListener()
*/
public void setCycleListener( CycleListener listener ) {
this.cycleListener = listener;
}
/**
* Retrieves the cycle listener
* @return the currently registered cycle listener
* @see #setCycleListener(CycleListener)
*/
public CycleListener getCycleListener() {
return this.cycleListener;
}
//#if polish.useNativeGui
/**
* Species a native implementation for this item.
* This method is only available when the preprocessing variable polish.useNativeGui is set to true.
* @param nativeItem the native implementation
*/
public void setNativeItem( NativeItem nativeItem ) {
this.nativeItem = nativeItem;
}
//#endif
//#if polish.useNativeGui
/**
* Species a native implementation for this item.
* This method is only available when the preprocessing variable polish.useNativeGui is set to true.
* @return the native implementation, can be null
*/
public NativeItem getNativeItem() {
return this.nativeItem;
}
//#endif
//#ifdef polish.Item.additionalMethods:defined
//#include ${polish.Item.additionalMethods}
//#endif
}
|
diff --git a/src/test/java/org/openmrs/module/mirebalais/smoke/EmergencyCheckinTest.java b/src/test/java/org/openmrs/module/mirebalais/smoke/EmergencyCheckinTest.java
index 713b7d0..b48f965 100644
--- a/src/test/java/org/openmrs/module/mirebalais/smoke/EmergencyCheckinTest.java
+++ b/src/test/java/org/openmrs/module/mirebalais/smoke/EmergencyCheckinTest.java
@@ -1,59 +1,59 @@
package org.openmrs.module.mirebalais.smoke;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openmrs.module.mirebalais.smoke.dataModel.BasicReportData;
import org.openmrs.module.mirebalais.smoke.pageobjects.AppDashboard;
import org.openmrs.module.mirebalais.smoke.pageobjects.BasicReportPage;
import org.openmrs.module.mirebalais.smoke.pageobjects.EmergencyCheckin;
import org.openmrs.module.mirebalais.smoke.pageobjects.LoginPage;
import org.openmrs.module.mirebalais.smoke.pageobjects.PatientRegistrationDashboard;
public class EmergencyCheckinTest extends BasicMirebalaisSmokeTest {
private EmergencyCheckin emergencyCheckinPO;
private static LoginPage loginPage;
private PatientRegistrationDashboard patientDashboard;
private BasicReportPage basicReport;
private AppDashboard appDashboard;
@Before
public void setUp() {
emergencyCheckinPO = new EmergencyCheckin(driver);
patientDashboard = new PatientRegistrationDashboard(driver);
appDashboard = new AppDashboard(driver);
basicReport = new BasicReportPage(driver);
}
@BeforeClass
public static void setUpEnvironment() {
loginPage = new LoginPage(driver);
loginPage.logInAsAdmin();
}
@Test
public void checkinOnEmergencyShouldCountOnReports() {
appDashboard.openReportApp();
BasicReportData brd1 = basicReport.getData();
appDashboard.openStartHospitalVisitApp();
emergencyCheckinPO.checkinMaleUnindentifiedPatient();
assertThat(patientDashboard.getIdentifier(), is(notNullValue()));
assertThat(patientDashboard.getGender(), is("M"));
assertThat(patientDashboard.getName(), Matchers.stringContainsInOrder(Arrays.asList("UNKNOWN", "UNKNOWN")));
appDashboard.openReportApp();
BasicReportData brd2 = basicReport.getData();
assertThat(brd2.getOpenVisits(), Matchers.greaterThan(brd1.getOpenVisits()));
- assertThat(brd2.getRegistrationToday(), Matchers.greaterThan(brd1.getOpenVisits()));
+ assertThat(brd2.getRegistrationToday(), Matchers.greaterThan(brd1.getRegistrationToday()));
}
}
| true | true | public void checkinOnEmergencyShouldCountOnReports() {
appDashboard.openReportApp();
BasicReportData brd1 = basicReport.getData();
appDashboard.openStartHospitalVisitApp();
emergencyCheckinPO.checkinMaleUnindentifiedPatient();
assertThat(patientDashboard.getIdentifier(), is(notNullValue()));
assertThat(patientDashboard.getGender(), is("M"));
assertThat(patientDashboard.getName(), Matchers.stringContainsInOrder(Arrays.asList("UNKNOWN", "UNKNOWN")));
appDashboard.openReportApp();
BasicReportData brd2 = basicReport.getData();
assertThat(brd2.getOpenVisits(), Matchers.greaterThan(brd1.getOpenVisits()));
assertThat(brd2.getRegistrationToday(), Matchers.greaterThan(brd1.getOpenVisits()));
}
| public void checkinOnEmergencyShouldCountOnReports() {
appDashboard.openReportApp();
BasicReportData brd1 = basicReport.getData();
appDashboard.openStartHospitalVisitApp();
emergencyCheckinPO.checkinMaleUnindentifiedPatient();
assertThat(patientDashboard.getIdentifier(), is(notNullValue()));
assertThat(patientDashboard.getGender(), is("M"));
assertThat(patientDashboard.getName(), Matchers.stringContainsInOrder(Arrays.asList("UNKNOWN", "UNKNOWN")));
appDashboard.openReportApp();
BasicReportData brd2 = basicReport.getData();
assertThat(brd2.getOpenVisits(), Matchers.greaterThan(brd1.getOpenVisits()));
assertThat(brd2.getRegistrationToday(), Matchers.greaterThan(brd1.getRegistrationToday()));
}
|
diff --git a/src/main/java/uk/ac/ebi/fgpt/sampletab/PRIDEcron.java b/src/main/java/uk/ac/ebi/fgpt/sampletab/PRIDEcron.java
index 9d96fa87..6a202c0c 100644
--- a/src/main/java/uk/ac/ebi/fgpt/sampletab/PRIDEcron.java
+++ b/src/main/java/uk/ac/ebi/fgpt/sampletab/PRIDEcron.java
@@ -1,261 +1,261 @@
package uk.ac.ebi.fgpt.sampletab;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.fgpt.sampletab.utils.FTPUtils;
import uk.ac.ebi.fgpt.sampletab.utils.PRIDEutils;
public class PRIDEcron {
private Logger log = LoggerFactory.getLogger(getClass());
// singlton instance
private static PRIDEcron instance = null;
private FTPClient ftp = null;
private PRIDEcron() {
// private constructor to prevent accidental multiple initialisations
}
public static PRIDEcron getInstance() {
if (instance == null) {
instance = new PRIDEcron();
}
return instance;
}
private void close() {
try {
ftp.logout();
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
// do nothing
}
}
}
}
private File getTrimFile(File outdir, String accesssion) {
File subdir = new File(outdir, "GPR-" + accesssion);
File trim = new File(subdir, "trimmed.xml");
return trim.getAbsoluteFile();
}
private class XMLProjectRunnable implements Runnable {
private File subdir = null;
private Map<String, Set<String>> subs = null;
public XMLProjectRunnable(File subdir, Map<String, Set<String>> subs){
this.subdir = subdir;
this.subs = subs;
}
public void run() {
if (subdir.isDirectory() && subdir.getName().matches("GPR-[0-9]+")) {
// get the xml file in this subdirectory
File xmlfile = new File(subdir, "trimmed.xml");
if (xmlfile.exists()) {
Set<String> projects;
try {
projects = PRIDEutils.getProjects(xmlfile);
} catch (DocumentException e){
return;
}
for (String project : projects) {
// add it if it does not exist
synchronized (this.subs) {
if (!subs.containsKey(project)) {
subs.put(project, Collections.synchronizedSet(new HashSet<String>()));
}
}
// now put it in the mapping
subs.get(project).add(subdir.getName());
}
}
}
return;
}
}
public void run(File outdir) {
FTPFile[] files;
try {
ftp = FTPUtils.connect("ftp.ebi.ac.uk");
log.info("Getting file listing...");
files = ftp.listFiles("/pub/databases/pride/");
log.info("Got file listing");
} catch (IOException e) {
System.err.println("Unable to connect to FTP");
e.printStackTrace();
System.exit(1);
return;
}
//Pattern regex = Pattern.compile("PRIDE_Exp_Complete_Ac_([0-9]+)\\.xml\\.gz");
Pattern regex = Pattern.compile("PRIDE_Exp_IdentOnly_Ac_([0-9]+)\\.xml\\.gz");
int nothreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(nothreads*2);
for (FTPFile file : files) {
String filename = file.getName();
//do a regular expression to match and pull out accession
Matcher matcher = regex.matcher(filename);
if (matcher.matches()) {
String accession = matcher.group(1);
File outfile = getTrimFile(outdir, accession);
// do not overwrite existing files unless newer
Calendar ftptime = file.getTimestamp();
Calendar outfiletime = new GregorianCalendar();
outfiletime.setTimeInMillis(outfile.lastModified());
if (!outfile.exists() || ftptime.after(outfiletime)) {
pool.execute(new PRIDEXMLFTPDownload(accession, outfile, false));
}
}
}
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination");
e.printStackTrace();
}
}
log.info("Completed downloading, starting parsing...");
// now that all the files have been updated, parse them to extract the relevant data
Map<String, Set<String>> subs = new HashMap<String, Set<String>>();
subs = Collections.synchronizedMap(subs);
//create a new thread pool since the last one was shut down
pool = Executors.newFixedThreadPool(nothreads);
for (File subdir : outdir.listFiles()) {
pool.execute(new XMLProjectRunnable(subdir, subs));
}
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination");
e.printStackTrace();
}
}
//5 min pause to watch where file descriptors are used
log.info("Parsing completed, starting output to disk...");
try {
- Thread.sleep((long) 300.0);
+ Thread.sleep(1000*60*5);
} catch (InterruptedException e) {
//do nothing, carry on as normal
}
// at this point, subs is a mapping from the project name to a set of BioSample accessions
// output them to a file
File projout = new File(outdir, "projects.tab.txt");
BufferedWriter projoutwrite = null;
try {
projoutwrite = new BufferedWriter(new FileWriter(projout));
synchronized (subs) {
// sort them to put them in a sensible order
List<String> projects = new ArrayList<String>(subs.keySet());
Collections.sort(projects);
for (String project : projects) {
projoutwrite.write(project);
projoutwrite.write("\t");
List<String> accessions = new ArrayList<String>(subs.get(project));
Collections.sort(accessions);
for (String accession : accessions) {
projoutwrite.write(accession);
projoutwrite.write("\t");
}
projoutwrite.write("\n");
}
}
} catch (IOException e) {
log.error("Unable to write to " + projout);
e.printStackTrace();
System.exit(1);
return;
} finally {
if (projoutwrite != null){
try {
projoutwrite.close();
} catch (IOException e) {
//failed within a fail so give up
log.error("Unable to close file writer " + projout);
}
}
}
//TODO hide files that have disappeared from the FTP site.
}
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Must provide the following paramters:");
System.err.println(" PRIDE local directory");
System.exit(1);
return;
}
String path = args[0];
File outdir = new File(path);
if (outdir.exists() && !outdir.isDirectory()) {
System.err.println("Target is not a directory");
System.exit(1);
return;
}
if (!outdir.exists())
outdir.mkdirs();
getInstance().run(outdir);
// tidy up ftp connection
getInstance().close();
}
}
| true | true | public void run(File outdir) {
FTPFile[] files;
try {
ftp = FTPUtils.connect("ftp.ebi.ac.uk");
log.info("Getting file listing...");
files = ftp.listFiles("/pub/databases/pride/");
log.info("Got file listing");
} catch (IOException e) {
System.err.println("Unable to connect to FTP");
e.printStackTrace();
System.exit(1);
return;
}
//Pattern regex = Pattern.compile("PRIDE_Exp_Complete_Ac_([0-9]+)\\.xml\\.gz");
Pattern regex = Pattern.compile("PRIDE_Exp_IdentOnly_Ac_([0-9]+)\\.xml\\.gz");
int nothreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(nothreads*2);
for (FTPFile file : files) {
String filename = file.getName();
//do a regular expression to match and pull out accession
Matcher matcher = regex.matcher(filename);
if (matcher.matches()) {
String accession = matcher.group(1);
File outfile = getTrimFile(outdir, accession);
// do not overwrite existing files unless newer
Calendar ftptime = file.getTimestamp();
Calendar outfiletime = new GregorianCalendar();
outfiletime.setTimeInMillis(outfile.lastModified());
if (!outfile.exists() || ftptime.after(outfiletime)) {
pool.execute(new PRIDEXMLFTPDownload(accession, outfile, false));
}
}
}
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination");
e.printStackTrace();
}
}
log.info("Completed downloading, starting parsing...");
// now that all the files have been updated, parse them to extract the relevant data
Map<String, Set<String>> subs = new HashMap<String, Set<String>>();
subs = Collections.synchronizedMap(subs);
//create a new thread pool since the last one was shut down
pool = Executors.newFixedThreadPool(nothreads);
for (File subdir : outdir.listFiles()) {
pool.execute(new XMLProjectRunnable(subdir, subs));
}
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination");
e.printStackTrace();
}
}
//5 min pause to watch where file descriptors are used
log.info("Parsing completed, starting output to disk...");
try {
Thread.sleep((long) 300.0);
} catch (InterruptedException e) {
//do nothing, carry on as normal
}
// at this point, subs is a mapping from the project name to a set of BioSample accessions
// output them to a file
File projout = new File(outdir, "projects.tab.txt");
BufferedWriter projoutwrite = null;
try {
projoutwrite = new BufferedWriter(new FileWriter(projout));
synchronized (subs) {
// sort them to put them in a sensible order
List<String> projects = new ArrayList<String>(subs.keySet());
Collections.sort(projects);
for (String project : projects) {
projoutwrite.write(project);
projoutwrite.write("\t");
List<String> accessions = new ArrayList<String>(subs.get(project));
Collections.sort(accessions);
for (String accession : accessions) {
projoutwrite.write(accession);
projoutwrite.write("\t");
}
projoutwrite.write("\n");
}
}
} catch (IOException e) {
log.error("Unable to write to " + projout);
e.printStackTrace();
System.exit(1);
return;
} finally {
if (projoutwrite != null){
try {
projoutwrite.close();
} catch (IOException e) {
//failed within a fail so give up
log.error("Unable to close file writer " + projout);
}
}
}
//TODO hide files that have disappeared from the FTP site.
}
| public void run(File outdir) {
FTPFile[] files;
try {
ftp = FTPUtils.connect("ftp.ebi.ac.uk");
log.info("Getting file listing...");
files = ftp.listFiles("/pub/databases/pride/");
log.info("Got file listing");
} catch (IOException e) {
System.err.println("Unable to connect to FTP");
e.printStackTrace();
System.exit(1);
return;
}
//Pattern regex = Pattern.compile("PRIDE_Exp_Complete_Ac_([0-9]+)\\.xml\\.gz");
Pattern regex = Pattern.compile("PRIDE_Exp_IdentOnly_Ac_([0-9]+)\\.xml\\.gz");
int nothreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(nothreads*2);
for (FTPFile file : files) {
String filename = file.getName();
//do a regular expression to match and pull out accession
Matcher matcher = regex.matcher(filename);
if (matcher.matches()) {
String accession = matcher.group(1);
File outfile = getTrimFile(outdir, accession);
// do not overwrite existing files unless newer
Calendar ftptime = file.getTimestamp();
Calendar outfiletime = new GregorianCalendar();
outfiletime.setTimeInMillis(outfile.lastModified());
if (!outfile.exists() || ftptime.after(outfiletime)) {
pool.execute(new PRIDEXMLFTPDownload(accession, outfile, false));
}
}
}
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination");
e.printStackTrace();
}
}
log.info("Completed downloading, starting parsing...");
// now that all the files have been updated, parse them to extract the relevant data
Map<String, Set<String>> subs = new HashMap<String, Set<String>>();
subs = Collections.synchronizedMap(subs);
//create a new thread pool since the last one was shut down
pool = Executors.newFixedThreadPool(nothreads);
for (File subdir : outdir.listFiles()) {
pool.execute(new XMLProjectRunnable(subdir, subs));
}
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination");
e.printStackTrace();
}
}
//5 min pause to watch where file descriptors are used
log.info("Parsing completed, starting output to disk...");
try {
Thread.sleep(1000*60*5);
} catch (InterruptedException e) {
//do nothing, carry on as normal
}
// at this point, subs is a mapping from the project name to a set of BioSample accessions
// output them to a file
File projout = new File(outdir, "projects.tab.txt");
BufferedWriter projoutwrite = null;
try {
projoutwrite = new BufferedWriter(new FileWriter(projout));
synchronized (subs) {
// sort them to put them in a sensible order
List<String> projects = new ArrayList<String>(subs.keySet());
Collections.sort(projects);
for (String project : projects) {
projoutwrite.write(project);
projoutwrite.write("\t");
List<String> accessions = new ArrayList<String>(subs.get(project));
Collections.sort(accessions);
for (String accession : accessions) {
projoutwrite.write(accession);
projoutwrite.write("\t");
}
projoutwrite.write("\n");
}
}
} catch (IOException e) {
log.error("Unable to write to " + projout);
e.printStackTrace();
System.exit(1);
return;
} finally {
if (projoutwrite != null){
try {
projoutwrite.close();
} catch (IOException e) {
//failed within a fail so give up
log.error("Unable to close file writer " + projout);
}
}
}
//TODO hide files that have disappeared from the FTP site.
}
|
diff --git a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java
index 187bf74a..4e763ccb 100644
--- a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java
+++ b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java
@@ -1,182 +1,182 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.javascript.internal.ui.text.completion;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashSet;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.dltk.core.CompletionProposal;
import org.eclipse.dltk.core.IMember;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.internal.javascript.reference.resolvers.SelfCompletingReference;
import org.eclipse.dltk.internal.javascript.typeinference.IReference;
import org.eclipse.dltk.javascript.scriptdoc.ScriptDocumentationProvider;
import org.eclipse.dltk.ui.text.completion.AbstractScriptCompletionProposal;
import org.eclipse.dltk.ui.text.completion.CompletionProposalLabelProvider;
import org.eclipse.dltk.ui.text.completion.IScriptCompletionProposal;
import org.eclipse.dltk.ui.text.completion.ProposalInfo;
import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposal;
import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposalCollector;
import org.eclipse.dltk.ui.text.completion.ScriptContentAssistInvocationContext;
import org.eclipse.swt.graphics.Image;
public class JavaScriptCompletionProposalCollector extends
ScriptCompletionProposalCollector {
protected final static char[] VAR_TRIGGER = new char[] { '\t', ' ', '=',
';', '.' };
private final HashSet doubleFilter = new HashSet();
protected char[] getVarTrigger() {
return VAR_TRIGGER;
}
public JavaScriptCompletionProposalCollector(ISourceModule module) {
super(module);
}
// Label provider
protected CompletionProposalLabelProvider createLabelProvider() {
return new JavaScriptCompletionProposalLabelProvider();
}
// Invocation context
protected ScriptContentAssistInvocationContext createScriptContentAssistInvocationContext(
ISourceModule sourceModule) {
return new ScriptContentAssistInvocationContext(sourceModule) {
protected CompletionProposalLabelProvider createLabelProvider() {
return new JavaScriptCompletionProposalLabelProvider();
}
};
}
/**
* @see org.eclipse.dltk.ui.text.completion.ScriptCompletionProposalCollector#beginReporting()
*/
public void beginReporting() {
super.beginReporting();
doubleFilter.clear();
}
/**
* @see org.eclipse.dltk.ui.text.completion.ScriptCompletionProposalCollector#isFiltered(org.eclipse.dltk.core.CompletionProposal)
*/
protected boolean isFiltered(CompletionProposal proposal) {
if (!doubleFilter.add(new String(proposal.getName()))) {
return true;
}
return super.isFiltered(proposal);
}
// Specific proposals creation. May be use factory?
protected IScriptCompletionProposal createScriptCompletionProposal(
CompletionProposal proposal) {
// TODO Auto-generated method stub
final IScriptCompletionProposal createScriptCompletionProposal2 = super
.createScriptCompletionProposal(proposal);
AbstractScriptCompletionProposal createScriptCompletionProposal = (AbstractScriptCompletionProposal) createScriptCompletionProposal2;
final Object ref = (Object) proposal.extraInfo;
ProposalInfo proposalInfo = new ProposalInfo(null) {
public String getInfo(IProgressMonitor monitor) {
if (ref instanceof SelfCompletingReference
&& ((SelfCompletingReference) ref).getProposalInfo() != null) {
return ((SelfCompletingReference) ref).getProposalInfo();
} else if (ref instanceof IReference) {
ArrayList ms = new ArrayList();
((IReference) ref).addModelElements(ms);
- if (ms.size() > 0)
- ;
- Reader contentReader = new ScriptDocumentationProvider()
- .getInfo((IMember) ms.get(0), true, true);
- if (contentReader != null) {
- String string = getString(contentReader);
- return string;
+ if (ms.size() > 0) {
+ Reader contentReader = new ScriptDocumentationProvider()
+ .getInfo((IMember) ms.get(0), true, true);
+ if (contentReader != null) {
+ String string = getString(contentReader);
+ return string;
+ }
}
} else if (ref instanceof IMember) {
Reader contentReader = new ScriptDocumentationProvider()
.getInfo((IMember) ref, true, true);
if (contentReader != null) {
String string = getString(contentReader);
return string;
}
} else if (ref instanceof String) {
return (String) ref;
}
return "Documentation not resolved";
}
/**
* Gets the reader content as a String
*/
private String getString(Reader reader) {
StringBuffer buf = new StringBuffer();
char[] buffer = new char[1024];
int count;
try {
while ((count = reader.read(buffer)) != -1)
buf.append(buffer, 0, count);
} catch (IOException e) {
return null;
}
return buf.toString();
}
};
createScriptCompletionProposal.setProposalInfo(proposalInfo);
return createScriptCompletionProposal;
}
protected ScriptCompletionProposal createScriptCompletionProposal(
String completion, int replaceStart, int length, Image image,
String displayString, int i) {
JavaScriptCompletionProposal javaScriptCompletionProposal = new JavaScriptCompletionProposal(
completion, replaceStart, length, image, displayString, i);
return javaScriptCompletionProposal;
}
protected ScriptCompletionProposal createScriptCompletionProposal(
String completion, int replaceStart, int length, Image image,
String displayString, int i, boolean isInDoc) {
JavaScriptCompletionProposal javaScriptCompletionProposal = new JavaScriptCompletionProposal(
completion, replaceStart, length, image, displayString, i,
isInDoc);
return javaScriptCompletionProposal;
}
protected ScriptCompletionProposal createOverrideCompletionProposal(
IScriptProject scriptProject, ISourceModule compilationUnit,
String name, String[] paramTypes, int start, int length,
String displayName, String completionProposal) {
return new JavaScriptOverrideCompletionProposal(scriptProject,
compilationUnit, name, paramTypes, start, length, displayName,
completionProposal);
}
protected IScriptCompletionProposal createKeywordProposal(
CompletionProposal proposal) {
String completion = String.valueOf(proposal.getCompletion());
int start = proposal.getReplaceStart();
int length = getLength(proposal);
String label = getLabelProvider().createSimpleLabel(proposal);
Image img = getImage(getLabelProvider().createMethodImageDescriptor(
proposal));
int relevance = computeRelevance(proposal);
return createScriptCompletionProposal(completion, start, length, img,
label, relevance);
}
}
| true | true | protected IScriptCompletionProposal createScriptCompletionProposal(
CompletionProposal proposal) {
// TODO Auto-generated method stub
final IScriptCompletionProposal createScriptCompletionProposal2 = super
.createScriptCompletionProposal(proposal);
AbstractScriptCompletionProposal createScriptCompletionProposal = (AbstractScriptCompletionProposal) createScriptCompletionProposal2;
final Object ref = (Object) proposal.extraInfo;
ProposalInfo proposalInfo = new ProposalInfo(null) {
public String getInfo(IProgressMonitor monitor) {
if (ref instanceof SelfCompletingReference
&& ((SelfCompletingReference) ref).getProposalInfo() != null) {
return ((SelfCompletingReference) ref).getProposalInfo();
} else if (ref instanceof IReference) {
ArrayList ms = new ArrayList();
((IReference) ref).addModelElements(ms);
if (ms.size() > 0)
;
Reader contentReader = new ScriptDocumentationProvider()
.getInfo((IMember) ms.get(0), true, true);
if (contentReader != null) {
String string = getString(contentReader);
return string;
}
} else if (ref instanceof IMember) {
Reader contentReader = new ScriptDocumentationProvider()
.getInfo((IMember) ref, true, true);
if (contentReader != null) {
String string = getString(contentReader);
return string;
}
} else if (ref instanceof String) {
return (String) ref;
}
return "Documentation not resolved";
}
/**
* Gets the reader content as a String
*/
private String getString(Reader reader) {
StringBuffer buf = new StringBuffer();
char[] buffer = new char[1024];
int count;
try {
while ((count = reader.read(buffer)) != -1)
buf.append(buffer, 0, count);
} catch (IOException e) {
return null;
}
return buf.toString();
}
};
createScriptCompletionProposal.setProposalInfo(proposalInfo);
return createScriptCompletionProposal;
}
| protected IScriptCompletionProposal createScriptCompletionProposal(
CompletionProposal proposal) {
// TODO Auto-generated method stub
final IScriptCompletionProposal createScriptCompletionProposal2 = super
.createScriptCompletionProposal(proposal);
AbstractScriptCompletionProposal createScriptCompletionProposal = (AbstractScriptCompletionProposal) createScriptCompletionProposal2;
final Object ref = (Object) proposal.extraInfo;
ProposalInfo proposalInfo = new ProposalInfo(null) {
public String getInfo(IProgressMonitor monitor) {
if (ref instanceof SelfCompletingReference
&& ((SelfCompletingReference) ref).getProposalInfo() != null) {
return ((SelfCompletingReference) ref).getProposalInfo();
} else if (ref instanceof IReference) {
ArrayList ms = new ArrayList();
((IReference) ref).addModelElements(ms);
if (ms.size() > 0) {
Reader contentReader = new ScriptDocumentationProvider()
.getInfo((IMember) ms.get(0), true, true);
if (contentReader != null) {
String string = getString(contentReader);
return string;
}
}
} else if (ref instanceof IMember) {
Reader contentReader = new ScriptDocumentationProvider()
.getInfo((IMember) ref, true, true);
if (contentReader != null) {
String string = getString(contentReader);
return string;
}
} else if (ref instanceof String) {
return (String) ref;
}
return "Documentation not resolved";
}
/**
* Gets the reader content as a String
*/
private String getString(Reader reader) {
StringBuffer buf = new StringBuffer();
char[] buffer = new char[1024];
int count;
try {
while ((count = reader.read(buffer)) != -1)
buf.append(buffer, 0, count);
} catch (IOException e) {
return null;
}
return buf.toString();
}
};
createScriptCompletionProposal.setProposalInfo(proposalInfo);
return createScriptCompletionProposal;
}
|
diff --git a/src/main/java/ch/o2it/weblounge/taglib/content/HTMLHeaderTag.java b/src/main/java/ch/o2it/weblounge/taglib/content/HTMLHeaderTag.java
index 4c4cdd3bb..3ee6cedf5 100644
--- a/src/main/java/ch/o2it/weblounge/taglib/content/HTMLHeaderTag.java
+++ b/src/main/java/ch/o2it/weblounge/taglib/content/HTMLHeaderTag.java
@@ -1,123 +1,127 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2010 The Weblounge Team
* http://weblounge.o2it.ch
*
* This program 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 ch.o2it.weblounge.taglib.content;
import ch.o2it.weblounge.common.content.Renderer;
import ch.o2it.weblounge.common.content.page.DeclarativeHTMLHeadElement;
import ch.o2it.weblounge.common.content.page.HTMLHeadElement;
import ch.o2it.weblounge.common.content.page.Page;
import ch.o2it.weblounge.common.content.page.Pagelet;
import ch.o2it.weblounge.common.request.WebloungeRequest;
import ch.o2it.weblounge.common.site.HTMLAction;
import ch.o2it.weblounge.common.site.Module;
import ch.o2it.weblounge.common.site.Site;
import ch.o2it.weblounge.taglib.WebloungeTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.jsp.JspException;
/**
* This tag prints out various headers for the <head> section of an html
* page.
*/
public class HTMLHeaderTag extends WebloungeTag {
/** Serial version uid */
private static final long serialVersionUID = -1813975272420106327L;
/** Logging facility provided by log4j */
private static final Logger logger = LoggerFactory.getLogger(HTMLHeaderTag.class);
/**
* Does the tag processing.
*
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException {
HTMLAction action = (HTMLAction) getRequest().getAttribute(WebloungeRequest.ACTION);
// See what the action has to contribute
try {
pageContext.getOut().flush();
if (action != null && action.startHeader(request, response) == HTMLAction.SKIP_HEADER) {
pageContext.getOut().flush();
return EVAL_PAGE;
}
} catch (Exception e) {
logger.error("Error asking action '" + action + "' for headers", e);
}
// Start with the default processing
Set<HTMLHeadElement> headElements = new HashSet<HTMLHeadElement>();
+ Site site = request.getSite();
// Pagelets links & scripts
Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);
if (page != null) {
Pagelet[] pagelets = page.getPagelets();
- Site site = request.getSite();
for (Pagelet p : pagelets) {
String moduleId = p.getModule();
Module module = site.getModule(moduleId);
if (module == null) {
logger.debug("Unable to load includes for renderer '{}': module '{}' not installed", new Object[] { p.getIdentifier(), site, request.getRequestedUrl(), moduleId });
continue;
}
Renderer renderer = module.getRenderer(p.getIdentifier());
if (renderer != null) {
for (HTMLHeadElement header : renderer.getHTMLHeaders()) {
if (header instanceof DeclarativeHTMLHeadElement)
((DeclarativeHTMLHeadElement)header).configure(request, site, module);
headElements.add(header);
}
} else {
logger.warn("Renderer '" + p + "' not found for " + request.getUrl() + "!");
continue;
}
}
}
// Action links & scripts
if (action != null) {
- for (HTMLHeadElement l : action.getHTMLHeaders())
+ Module module = action.getModule();
+ for (HTMLHeadElement l : action.getHTMLHeaders()) {
+ if (l instanceof DeclarativeHTMLHeadElement)
+ ((DeclarativeHTMLHeadElement)l).configure(request, site, module);
headElements.add(l);
+ }
}
// Write links & scripts to output
try {
pageContext.getOut().flush();
for (HTMLHeadElement s : headElements) {
pageContext.getOut().println(s.toXml());
}
pageContext.getOut().flush();
} catch (IOException e) {
throw new JspException();
}
return EVAL_BODY_INCLUDE;
}
}
| false | true | public int doEndTag() throws JspException {
HTMLAction action = (HTMLAction) getRequest().getAttribute(WebloungeRequest.ACTION);
// See what the action has to contribute
try {
pageContext.getOut().flush();
if (action != null && action.startHeader(request, response) == HTMLAction.SKIP_HEADER) {
pageContext.getOut().flush();
return EVAL_PAGE;
}
} catch (Exception e) {
logger.error("Error asking action '" + action + "' for headers", e);
}
// Start with the default processing
Set<HTMLHeadElement> headElements = new HashSet<HTMLHeadElement>();
// Pagelets links & scripts
Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);
if (page != null) {
Pagelet[] pagelets = page.getPagelets();
Site site = request.getSite();
for (Pagelet p : pagelets) {
String moduleId = p.getModule();
Module module = site.getModule(moduleId);
if (module == null) {
logger.debug("Unable to load includes for renderer '{}': module '{}' not installed", new Object[] { p.getIdentifier(), site, request.getRequestedUrl(), moduleId });
continue;
}
Renderer renderer = module.getRenderer(p.getIdentifier());
if (renderer != null) {
for (HTMLHeadElement header : renderer.getHTMLHeaders()) {
if (header instanceof DeclarativeHTMLHeadElement)
((DeclarativeHTMLHeadElement)header).configure(request, site, module);
headElements.add(header);
}
} else {
logger.warn("Renderer '" + p + "' not found for " + request.getUrl() + "!");
continue;
}
}
}
// Action links & scripts
if (action != null) {
for (HTMLHeadElement l : action.getHTMLHeaders())
headElements.add(l);
}
// Write links & scripts to output
try {
pageContext.getOut().flush();
for (HTMLHeadElement s : headElements) {
pageContext.getOut().println(s.toXml());
}
pageContext.getOut().flush();
} catch (IOException e) {
throw new JspException();
}
return EVAL_BODY_INCLUDE;
}
| public int doEndTag() throws JspException {
HTMLAction action = (HTMLAction) getRequest().getAttribute(WebloungeRequest.ACTION);
// See what the action has to contribute
try {
pageContext.getOut().flush();
if (action != null && action.startHeader(request, response) == HTMLAction.SKIP_HEADER) {
pageContext.getOut().flush();
return EVAL_PAGE;
}
} catch (Exception e) {
logger.error("Error asking action '" + action + "' for headers", e);
}
// Start with the default processing
Set<HTMLHeadElement> headElements = new HashSet<HTMLHeadElement>();
Site site = request.getSite();
// Pagelets links & scripts
Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);
if (page != null) {
Pagelet[] pagelets = page.getPagelets();
for (Pagelet p : pagelets) {
String moduleId = p.getModule();
Module module = site.getModule(moduleId);
if (module == null) {
logger.debug("Unable to load includes for renderer '{}': module '{}' not installed", new Object[] { p.getIdentifier(), site, request.getRequestedUrl(), moduleId });
continue;
}
Renderer renderer = module.getRenderer(p.getIdentifier());
if (renderer != null) {
for (HTMLHeadElement header : renderer.getHTMLHeaders()) {
if (header instanceof DeclarativeHTMLHeadElement)
((DeclarativeHTMLHeadElement)header).configure(request, site, module);
headElements.add(header);
}
} else {
logger.warn("Renderer '" + p + "' not found for " + request.getUrl() + "!");
continue;
}
}
}
// Action links & scripts
if (action != null) {
Module module = action.getModule();
for (HTMLHeadElement l : action.getHTMLHeaders()) {
if (l instanceof DeclarativeHTMLHeadElement)
((DeclarativeHTMLHeadElement)l).configure(request, site, module);
headElements.add(l);
}
}
// Write links & scripts to output
try {
pageContext.getOut().flush();
for (HTMLHeadElement s : headElements) {
pageContext.getOut().println(s.toXml());
}
pageContext.getOut().flush();
} catch (IOException e) {
throw new JspException();
}
return EVAL_BODY_INCLUDE;
}
|
diff --git a/ScormPackager/src/au/edu/labshare/schedserver/scormpackager/service/ScormPackager.java b/ScormPackager/src/au/edu/labshare/schedserver/scormpackager/service/ScormPackager.java
index 6ab7ce58..e14c7709 100644
--- a/ScormPackager/src/au/edu/labshare/schedserver/scormpackager/service/ScormPackager.java
+++ b/ScormPackager/src/au/edu/labshare/schedserver/scormpackager/service/ScormPackager.java
@@ -1,177 +1,185 @@
package au.edu.labshare.schedserver.scormpackager.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Properties;
import au.edu.labshare.schedserver.scormpackager.sahara.RigLaunchPageCreator;
import au.edu.labshare.schedserver.scormpackager.sahara.RigMedia;
import au.edu.labshare.schedserver.scormpackager.types.CreatePIF;
import au.edu.labshare.schedserver.scormpackager.types.CreatePIFResponse;
import au.edu.labshare.schedserver.scormpackager.types.CreateSCO;
import au.edu.labshare.schedserver.scormpackager.types.CreateSCOResponse;
import au.edu.labshare.schedserver.scormpackager.types.DeletePIF;
import au.edu.labshare.schedserver.scormpackager.types.DeletePIFResponse;
import au.edu.labshare.schedserver.scormpackager.types.DeleteSCO;
import au.edu.labshare.schedserver.scormpackager.types.DeleteSCOResponse;
import au.edu.labshare.schedserver.scormpackager.types.ValidateManifest;
import au.edu.labshare.schedserver.scormpackager.types.ValidateManifestResponse;
import au.edu.labshare.schedserver.scormpackager.types.ValidatePIF;
import au.edu.labshare.schedserver.scormpackager.types.ValidatePIFResponse;
import au.edu.labshare.schedserver.scormpackager.types.ValidateSCO;
import au.edu.labshare.schedserver.scormpackager.types.ValidateSCOResponse;
import au.edu.labshare.schedserver.scormpackager.utilities.ScormUtilities;
import au.edu.labshare.schedserver.scormpackager.lila.ManifestXMLDecorator;
import au.edu.labshare.schedserver.scormpackager.lila.ShareableContentObjectCreator;
//import au.edu.uts.eng.remotelabs.schedserver.dataaccess.DataAccessActivator;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.RigTypeDao;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.RigTypeMedia;
import au.edu.uts.eng.remotelabs.schedserver.logger.Logger;
import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator;
public class ScormPackager implements ScormPackagerSkeletonInterface
{
/** Logger. */
private Logger logger;
//private org.hibernate.Session session;
public ScormPackager()
{
this.logger = LoggerActivator.getLogger();
//this.session = DataAccessActivator.getNewSession();
}
@Override
public CreatePIFResponse createPIF(CreatePIF createPIF)
{
au.edu.labshare.schedserver.scormpackager.types.CreateSCO SCOInfo = new au.edu.labshare.schedserver.scormpackager.types.CreateSCO();
SCOInfo.setContent(createPIF.getContent());
SCOInfo.setExperimentName(createPIF.getExperimentName());
CreateSCOResponse SCOResponse = createSCO(SCOInfo);
//Setup the response with the data to return back to the user
CreatePIFResponse createPIFResponse = new CreatePIFResponse();
createPIFResponse.setPathPIF(SCOResponse.getPathSCO());
return createPIFResponse;
}
@Override
public CreateSCOResponse createSCO(CreateSCO createSCO)
{
String pathOfSCO = null;
Properties defaultProps = new Properties();
FileInputStream in;
String cwd = null;
LinkedList<File> content = new LinkedList<File>();
//Start by adding extra content that was provided by user. Will not set if it is null
if(createSCO.getContent() != null)
content = ScormUtilities.getFilesFromPath(createSCO.getContent());
try
{
cwd = new java.io.File( "." ).getCanonicalPath();
}
catch(IOException e)
{
e.printStackTrace(); //TODO: Need to replace with Sahara Logger
}
//Add the lmsstub.js
if(!cwd.contains("ScormPackager"))
content.add(new File(cwd + "/ScormPackager/" + ManifestXMLDecorator.RESOURCES_PATH + "/lmsstub.js"));
else
content.add(new File(ManifestXMLDecorator.RESOURCES_PATH + "/lmsstub.js"));
//We want to get the content from the Rig DB Persistence end
org.hibernate.Session db = new RigTypeDao().getSession();
RigMedia saharaRigMedia = new RigMedia(db);
//Go through the rig media information and add any data that is in them
- Iterator<RigTypeMedia> iter = saharaRigMedia.getRigType(createSCO.getExperimentName()).getMedia().iterator();
+ Iterator<RigTypeMedia> iter;
+ if(saharaRigMedia.getRigType(createSCO.getExperimentName()) != null)
+ iter = saharaRigMedia.getRigType(createSCO.getExperimentName()).getMedia().iterator();
+ else
+ {
+ CreateSCOResponse errorSCOResponse = new CreateSCOResponse();
+ errorSCOResponse.setPathSCO("NON EXISTENT RIGTYPE - SCORM WEB SERVICE ERROR"); //TODO: Place this as a status code static string
+ return errorSCOResponse;
+ }
while(iter.hasNext())
content.add(new File(iter.next().getFileName()));
// We want to generate a LaunchPage (launchpage.html) that is to be added to SCO
RigLaunchPageCreator rigLaunchPageCreator = new RigLaunchPageCreator();
// create and load default properties
try
{
if(!cwd.contains("ScormPackager"))
in = new FileInputStream(cwd + "/ScormPackager/" + "resources/scormpackager.properties"); //TODO: Should place this as a static string
else
in = new FileInputStream("resources/scormpackager.properties"); //TODO: Should place this as a static string
defaultProps.load(in);
in.close();
}
catch (Exception e)
{
e.printStackTrace(); //TODO: Need to replace with Sahara Logger
}
//TODO: Should place this as static string - scormpackager_output_path
pathOfSCO = (String) defaultProps.getProperty("scormpackager_output_path");
//Add the content - i.e. Add launchPage with Experiment/Rig name
rigLaunchPageCreator.setOutputPath(pathOfSCO + ScormUtilities.replaceWhiteSpace(createSCO.getExperimentName(),"_") + ".html");
content.add(new File(rigLaunchPageCreator.createLaunchPage(createSCO.getExperimentName(), db)));
//Create the SCO to be sent out
ShareableContentObjectCreator shrContentObj = new ShareableContentObjectCreator(logger);
shrContentObj.createSCO(createSCO.getExperimentName(), content, pathOfSCO);
//Setup the response with the data to return back to the user
CreateSCOResponse createSCOResponse = new CreateSCOResponse();
createSCOResponse.setPathSCO(pathOfSCO);
return createSCOResponse;
}
@Override
public DeletePIFResponse deletePIF(DeletePIF deletePIF)
{
// TODO Auto-generated method stub
return null;
}
@Override
public DeleteSCOResponse deleteSCO(DeleteSCO deleteSCO)
{
// TODO Auto-generated method stub
return null;
}
@Override
public ValidateManifestResponse validateManifest(ValidateManifest validateManifest)
{
// TODO Auto-generated method stub
return null;
}
@Override
public ValidatePIFResponse validatePIF(ValidatePIF validatePIF)
{
// TODO Auto-generated method stub
return null;
}
@Override
public ValidateSCOResponse validateSCO(ValidateSCO validateSCO)
{
// TODO Auto-generated method stub
return null;
}
}
| true | true | public CreateSCOResponse createSCO(CreateSCO createSCO)
{
String pathOfSCO = null;
Properties defaultProps = new Properties();
FileInputStream in;
String cwd = null;
LinkedList<File> content = new LinkedList<File>();
//Start by adding extra content that was provided by user. Will not set if it is null
if(createSCO.getContent() != null)
content = ScormUtilities.getFilesFromPath(createSCO.getContent());
try
{
cwd = new java.io.File( "." ).getCanonicalPath();
}
catch(IOException e)
{
e.printStackTrace(); //TODO: Need to replace with Sahara Logger
}
//Add the lmsstub.js
if(!cwd.contains("ScormPackager"))
content.add(new File(cwd + "/ScormPackager/" + ManifestXMLDecorator.RESOURCES_PATH + "/lmsstub.js"));
else
content.add(new File(ManifestXMLDecorator.RESOURCES_PATH + "/lmsstub.js"));
//We want to get the content from the Rig DB Persistence end
org.hibernate.Session db = new RigTypeDao().getSession();
RigMedia saharaRigMedia = new RigMedia(db);
//Go through the rig media information and add any data that is in them
Iterator<RigTypeMedia> iter = saharaRigMedia.getRigType(createSCO.getExperimentName()).getMedia().iterator();
while(iter.hasNext())
content.add(new File(iter.next().getFileName()));
// We want to generate a LaunchPage (launchpage.html) that is to be added to SCO
RigLaunchPageCreator rigLaunchPageCreator = new RigLaunchPageCreator();
// create and load default properties
try
{
if(!cwd.contains("ScormPackager"))
in = new FileInputStream(cwd + "/ScormPackager/" + "resources/scormpackager.properties"); //TODO: Should place this as a static string
else
in = new FileInputStream("resources/scormpackager.properties"); //TODO: Should place this as a static string
defaultProps.load(in);
in.close();
}
catch (Exception e)
{
e.printStackTrace(); //TODO: Need to replace with Sahara Logger
}
//TODO: Should place this as static string - scormpackager_output_path
pathOfSCO = (String) defaultProps.getProperty("scormpackager_output_path");
//Add the content - i.e. Add launchPage with Experiment/Rig name
rigLaunchPageCreator.setOutputPath(pathOfSCO + ScormUtilities.replaceWhiteSpace(createSCO.getExperimentName(),"_") + ".html");
content.add(new File(rigLaunchPageCreator.createLaunchPage(createSCO.getExperimentName(), db)));
//Create the SCO to be sent out
ShareableContentObjectCreator shrContentObj = new ShareableContentObjectCreator(logger);
shrContentObj.createSCO(createSCO.getExperimentName(), content, pathOfSCO);
//Setup the response with the data to return back to the user
CreateSCOResponse createSCOResponse = new CreateSCOResponse();
createSCOResponse.setPathSCO(pathOfSCO);
return createSCOResponse;
}
| public CreateSCOResponse createSCO(CreateSCO createSCO)
{
String pathOfSCO = null;
Properties defaultProps = new Properties();
FileInputStream in;
String cwd = null;
LinkedList<File> content = new LinkedList<File>();
//Start by adding extra content that was provided by user. Will not set if it is null
if(createSCO.getContent() != null)
content = ScormUtilities.getFilesFromPath(createSCO.getContent());
try
{
cwd = new java.io.File( "." ).getCanonicalPath();
}
catch(IOException e)
{
e.printStackTrace(); //TODO: Need to replace with Sahara Logger
}
//Add the lmsstub.js
if(!cwd.contains("ScormPackager"))
content.add(new File(cwd + "/ScormPackager/" + ManifestXMLDecorator.RESOURCES_PATH + "/lmsstub.js"));
else
content.add(new File(ManifestXMLDecorator.RESOURCES_PATH + "/lmsstub.js"));
//We want to get the content from the Rig DB Persistence end
org.hibernate.Session db = new RigTypeDao().getSession();
RigMedia saharaRigMedia = new RigMedia(db);
//Go through the rig media information and add any data that is in them
Iterator<RigTypeMedia> iter;
if(saharaRigMedia.getRigType(createSCO.getExperimentName()) != null)
iter = saharaRigMedia.getRigType(createSCO.getExperimentName()).getMedia().iterator();
else
{
CreateSCOResponse errorSCOResponse = new CreateSCOResponse();
errorSCOResponse.setPathSCO("NON EXISTENT RIGTYPE - SCORM WEB SERVICE ERROR"); //TODO: Place this as a status code static string
return errorSCOResponse;
}
while(iter.hasNext())
content.add(new File(iter.next().getFileName()));
// We want to generate a LaunchPage (launchpage.html) that is to be added to SCO
RigLaunchPageCreator rigLaunchPageCreator = new RigLaunchPageCreator();
// create and load default properties
try
{
if(!cwd.contains("ScormPackager"))
in = new FileInputStream(cwd + "/ScormPackager/" + "resources/scormpackager.properties"); //TODO: Should place this as a static string
else
in = new FileInputStream("resources/scormpackager.properties"); //TODO: Should place this as a static string
defaultProps.load(in);
in.close();
}
catch (Exception e)
{
e.printStackTrace(); //TODO: Need to replace with Sahara Logger
}
//TODO: Should place this as static string - scormpackager_output_path
pathOfSCO = (String) defaultProps.getProperty("scormpackager_output_path");
//Add the content - i.e. Add launchPage with Experiment/Rig name
rigLaunchPageCreator.setOutputPath(pathOfSCO + ScormUtilities.replaceWhiteSpace(createSCO.getExperimentName(),"_") + ".html");
content.add(new File(rigLaunchPageCreator.createLaunchPage(createSCO.getExperimentName(), db)));
//Create the SCO to be sent out
ShareableContentObjectCreator shrContentObj = new ShareableContentObjectCreator(logger);
shrContentObj.createSCO(createSCO.getExperimentName(), content, pathOfSCO);
//Setup the response with the data to return back to the user
CreateSCOResponse createSCOResponse = new CreateSCOResponse();
createSCOResponse.setPathSCO(pathOfSCO);
return createSCOResponse;
}
|
diff --git a/src/main/java/org/basex/http/restxq/RestXqFunction.java b/src/main/java/org/basex/http/restxq/RestXqFunction.java
index 24edc63ee..f8cbd059b 100644
--- a/src/main/java/org/basex/http/restxq/RestXqFunction.java
+++ b/src/main/java/org/basex/http/restxq/RestXqFunction.java
@@ -1,479 +1,479 @@
package org.basex.http.restxq;
import static org.basex.http.HTTPMethod.*;
import static org.basex.http.restxq.RestXqText.*;
import static org.basex.util.Token.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;
import javax.servlet.http.*;
import org.basex.build.*;
import org.basex.http.*;
import org.basex.io.*;
import org.basex.io.in.*;
import org.basex.io.serial.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.func.*;
import org.basex.query.iter.*;
import org.basex.query.util.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.type.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* This class represents a single RESTXQ function.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
final class RestXqFunction implements Comparable<RestXqFunction> {
/** Pattern for a single template. */
private static final Pattern TEMPLATE =
Pattern.compile("\\s*\\{\\s*\\$(.+?)\\s*\\}\\s*");
/** Supported methods. */
EnumSet<HTTPMethod> methods = EnumSet.allOf(HTTPMethod.class);
/** Serialization parameters. */
final SerializerProp output = new SerializerProp();
/** Associated function. */
final StaticUserFunc function;
/** Associated module. */
final RestXqModule module;
/** Path. */
RestXqPath path;
/** Query parameters. */
final ArrayList<RestXqParam> queryParams = new ArrayList<RestXqParam>();
/** Form parameters. */
final ArrayList<RestXqParam> formParams = new ArrayList<RestXqParam>();
/** Header parameters. */
final ArrayList<RestXqParam> headerParams = new ArrayList<RestXqParam>();
/** Cookie parameters. */
final ArrayList<RestXqParam> cookieParams = new ArrayList<RestXqParam>();
/** Query context. */
private final QueryContext context;
/** Consumed media types. */
private final StringList consumes = new StringList();
/** Returned media types. */
private final StringList produces = new StringList();
/** Post/Put variable. */
private QNm requestBody;
/**
* Constructor.
* @param uf associated user function
* @param qc query context
* @param m associated module
*/
RestXqFunction(final StaticUserFunc uf, final QueryContext qc, final RestXqModule m) {
function = uf;
context = qc;
module = m;
}
/**
* Processes the HTTP request.
* Parses new modules and discards obsolete ones.
* @param http HTTP context
* @throws Exception exception
*/
void process(final HTTPContext http) throws Exception {
try {
module.process(http, this);
} catch(final QueryException ex) {
if(ex.file() == null) ex.info(function.info);
throw ex;
}
}
/**
* Checks a function for RESTFful annotations.
* @return {@code true} if module contains relevant annotations
* @throws QueryException query exception
*/
boolean analyze() throws QueryException {
// parse all annotations
final EnumSet<HTTPMethod> mth = EnumSet.noneOf(HTTPMethod.class);
final boolean[] declared = new boolean[function.args.length];
boolean found = false;
final int as = function.ann.size();
for(int a = 0; a < as; a++) {
final QNm name = function.ann.names[a];
final Value value = function.ann.values[a];
final byte[] local = name.local();
final byte[] uri = name.uri();
final boolean rexq = eq(uri, QueryText.RESTXQURI);
if(rexq) {
if(eq(PATH, local)) {
// annotation "path"
if(path != null) error(ANN_TWICE, "%", name.string());
path = new RestXqPath(toString(value, name));
for(final String s : path) {
if(s.trim().startsWith("{")) checkVariable(s, AtomType.AAT, declared);
}
} else if(eq(CONSUMES, local)) {
// annotation "consumes"
strings(value, name, consumes);
} else if(eq(PRODUCES, local)) {
// annotation "produces"
strings(value, name, produces);
} else if(eq(QUERY_PARAM, local)) {
// annotation "query-param"
queryParams.add(param(value, name, declared));
} else if(eq(FORM_PARAM, local)) {
// annotation "form-param"
formParams.add(param(value, name, declared));
} else if(eq(HEADER_PARAM, local)) {
// annotation "header-param"
headerParams.add(param(value, name, declared));
} else if(eq(COOKIE_PARAM, local)) {
// annotation "cookie-param"
cookieParams.add(param(value, name, declared));
} else {
// method annotations
final HTTPMethod m = HTTPMethod.get(string(local));
if(m == null) error(ANN_UNKNOWN, "%", name.string());
if(!value.isEmpty()) {
// remember post/put variable
if(requestBody != null) error(ANN_TWICE, "%", name.string());
if(m != POST && m != PUT) error(METHOD_VALUE, m);
requestBody = checkVariable(toString(value, name), declared);
}
if(mth.contains(m)) error(ANN_TWICE, "%", name.string());
mth.add(m);
}
} else if(eq(uri, QueryText.OUTPUTURI)) {
// serialization parameters
final String key = string(local);
final String val = toString(value, name);
if(output.get(key) == null) error(UNKNOWN_SER, key);
output.set(key, val);
}
found |= rexq;
}
if(!mth.isEmpty()) methods = mth;
if(found) {
if(path == null) error(ANN_MISSING, PATH);
for(int i = 0; i < declared.length; i++)
- if(!declared[i]) error(VAR_UNDEFINED, function.args[i]);
+ if(!declared[i]) error(VAR_UNDEFINED, function.args[i].name.string());
}
return found;
}
/**
* Checks if an HTTP request matches this function and its constraints.
* @param http http context
* @return result of check
*/
boolean matches(final HTTPContext http) {
// check method, path, consumed and produced media type
return methods.contains(http.method) && pathMatches(http) &&
consumes(http) && produces(http);
}
/**
* Binds the annotated variables.
* @param http http context
* @param arg argument array
* @throws QueryException query exception
* @throws IOException I/O exception
*/
void bind(final HTTPContext http, final Expr[] arg) throws QueryException, IOException {
// bind variables from segments
for(int s = 0; s < path.size; s++) {
final Matcher m = TEMPLATE.matcher(path.segment[s]);
if(!m.find()) continue;
final QNm qnm = new QNm(token(m.group(1)), context);
bind(qnm, arg, new Atm(http.segment(s)));
}
// cache request body
final String ct = http.contentType();
IOContent body = null;
if(requestBody != null) {
body = cache(http, null);
try {
// bind request body in the correct format
body.name(http.method + IO.XMLSUFFIX);
bind(requestBody, arg, Parser.item(body, context.context.prop, ct));
} catch(final IOException ex) {
error(INPUT_CONV, ex);
}
}
// bind query parameters
final Map<String, String[]> params = http.params();
for(final RestXqParam rxp : queryParams) bind(rxp, arg, params.get(rxp.key));
// bind form parameters
if(!formParams.isEmpty()) {
if(MimeTypes.APP_FORM.equals(ct)) {
// convert parameters encoded in a form
body = cache(http, body);
addParams(body.toString(), params);
}
for(final RestXqParam rxp : formParams) bind(rxp, arg, params.get(rxp.key));
}
// bind header parameters
for(final RestXqParam rxp : headerParams) {
final StringList sl = new StringList();
final Enumeration<?> en = http.req.getHeaders(rxp.key);
while(en.hasMoreElements()) {
for(final String s : en.nextElement().toString().split(", *")) sl.add(s);
}
bind(rxp, arg, sl.toArray());
}
// bind cookie parameters
final Cookie[] ck = http.req.getCookies();
for(final RestXqParam rxp : cookieParams) {
String v = null;
if(ck != null) {
for(final Cookie c : ck) {
if(rxp.key.equals(c.getName())) v = c.getValue();
}
}
if(v == null) bind(rxp, arg);
else bind(rxp, arg, v);
}
}
/**
* Creates an exception with the specified message.
* @param msg message
* @param ext error extension
* @return exception
* @throws QueryException query exception
*/
QueryException error(final String msg, final Object... ext) throws QueryException {
throw new QueryException(function.info, Err.BASX_RESTXQ, Util.info(msg, ext));
}
@Override
public int compareTo(final RestXqFunction rxf) {
return path.compareTo(rxf.path);
}
// PRIVATE METHODS ====================================================================
/**
* Checks the specified template and adds a variable.
* @param tmp template string
* @param declared variable declaration flags
* @return resulting variable
* @throws QueryException query exception
*/
private QNm checkVariable(final String tmp, final boolean[] declared)
throws QueryException {
return checkVariable(tmp, AtomType.ITEM, declared);
}
/**
* Checks the specified template and adds a variable.
* @param tmp template string
* @param type allowed type
* @param declared variable declaration flags
* @return resulting variable
* @throws QueryException query exception
*/
private QNm checkVariable(final String tmp, final Type type, final boolean[] declared)
throws QueryException {
final Var[] args = function.args;
final Matcher m = TEMPLATE.matcher(tmp);
if(!m.find()) error(INV_TEMPLATE, tmp);
final byte[] vn = token(m.group(1));
if(!XMLToken.isQName(vn)) error(INV_VARNAME, vn);
final QNm qnm = new QNm(vn, context);
int r = -1;
while(++r < args.length && !args[r].name.eq(qnm));
if(r == args.length) error(UNKNOWN_VAR, vn);
if(declared[r]) error(VAR_ASSIGNED, vn);
final SeqType st = args[r].declaredType();
if(args[r].checksType() && !st.type.instanceOf(type)) error(INV_VARTYPE, vn, type);
declared[r] = true;
return qnm;
}
/**
* Checks if the path matches the HTTP request.
* @param http http context
* @return result of check
*/
private boolean pathMatches(final HTTPContext http) {
return path.matches(http);
}
/**
* Checks if the consumed content type matches.
* @param http http context
* @return result of check
*/
private boolean consumes(final HTTPContext http) {
// return true if no type is given
if(consumes.isEmpty()) return true;
// return true if no content type is specified by the user
final String ct = http.contentType();
if(ct == null) return true;
// check if any combination matches
for(final String c : consumes) {
if(MimeTypes.matches(c, ct)) return true;
}
return false;
}
/**
* Checks if the produced content type matches.
* @param http http context
* @return result of check
*/
private boolean produces(final HTTPContext http) {
// return true if no type is given
if(produces.isEmpty()) return true;
// check if any combination matches
for(final String pr : http.produces()) {
for(final String p : produces) {
if(MimeTypes.matches(p, pr)) return true;
}
}
return false;
}
/**
* Binds the specified parameter to a variable.
* @param rxp parameter
* @param args argument array
* @param values values to be bound; the parameter's default value is assigned
* if the argument is {@code null} or empty
* @throws QueryException query exception
*/
private void bind(final RestXqParam rxp, final Expr[] args, final String... values)
throws QueryException {
final Value val;
if(values == null || values.length == 0) {
val = rxp.value;
} else {
final ValueBuilder vb = new ValueBuilder();
for(final String s : values) vb.add(new Atm(s));
val = vb.value();
}
bind(rxp.name, args, val);
}
/**
* Binds the specified value to a variable.
* @param name variable name
* @param args argument array
* @param value value to be bound
* @throws QueryException query exception
*/
private void bind(final QNm name, final Expr[] args, final Value value)
throws QueryException {
// skip nulled values
if(value == null) return;
for(int i = 0; i < function.args.length; i++) {
final Var var = function.args[i];
if(!var.name.eq(name)) continue;
// casts and binds the value
args[i] = var.checkType(value, context, null);
break;
}
}
/**
* Returns the specified value as an atomic string.
* @param value value
* @param name name
* @return string
* @throws QueryException HTTP exception
*/
private String toString(final Value value, final QNm name) throws QueryException {
if(!(value instanceof Str)) error(ANN_STRING, "%", name.string(), value);
return ((Str) value).toJava();
}
/**
* Adds items to the specified list.
* @param value value
* @param name name
* @param list list to add values to
* @throws QueryException HTTP exception
*/
private void strings(final Value value, final QNm name, final StringList list)
throws QueryException {
final long vs = value.size();
for(int v = 0; v < vs; v++) list.add(toString(value.itemAt(v), name));
}
/**
* Returns a parameter.
* @param value value
* @param name name
* @param declared variable declaration flags
* @return parameter
* @throws QueryException HTTP exception
*/
private RestXqParam param(final Value value, final QNm name, final boolean[] declared)
throws QueryException {
// [CG] RESTXQ: allow identical field names?
final long vs = value.size();
if(vs < 2) error(ANN_PARAMS, "%", name.string(), 2);
// name of parameter
final String key = toString(value.itemAt(0), name);
// variable template
final QNm qnm = checkVariable(toString(value.itemAt(1), name), declared);
// default value
final ValueBuilder vb = new ValueBuilder();
for(int v = 2; v < vs; v++) vb.add(value.itemAt(v));
return new RestXqParam(qnm, key, vb.value());
}
// PRIVATE STATIC METHODS =============================================================
/**
* Caches the request body, if not done yet.
* @param http http context
* @param cache cache existing cache reference
* @return cache
* @throws IOException I/O exception
*/
private static IOContent cache(final HTTPContext http, final IOContent cache)
throws IOException {
if(cache != null) return cache;
final BufferInput bi = new BufferInput(http.req.getInputStream());
final IOContent io = new IOContent(bi.content());
io.name(http.method + IO.XMLSUFFIX);
return io;
}
/**
* Adds parameters from the passed on request body.
* @param body request body
* @param params map parameters
*/
private static void addParams(final String body, final Map<String, String[]> params) {
for(final String nv : body.split("&")) {
final String[] parts = nv.split("=", 2);
if(parts.length < 2) continue;
try {
params.put(parts[0], new String[] { URLDecoder.decode(parts[1], Token.UTF8) });
} catch(final Exception ex) {
Util.notexpected(ex);
}
}
}
}
| true | true | boolean analyze() throws QueryException {
// parse all annotations
final EnumSet<HTTPMethod> mth = EnumSet.noneOf(HTTPMethod.class);
final boolean[] declared = new boolean[function.args.length];
boolean found = false;
final int as = function.ann.size();
for(int a = 0; a < as; a++) {
final QNm name = function.ann.names[a];
final Value value = function.ann.values[a];
final byte[] local = name.local();
final byte[] uri = name.uri();
final boolean rexq = eq(uri, QueryText.RESTXQURI);
if(rexq) {
if(eq(PATH, local)) {
// annotation "path"
if(path != null) error(ANN_TWICE, "%", name.string());
path = new RestXqPath(toString(value, name));
for(final String s : path) {
if(s.trim().startsWith("{")) checkVariable(s, AtomType.AAT, declared);
}
} else if(eq(CONSUMES, local)) {
// annotation "consumes"
strings(value, name, consumes);
} else if(eq(PRODUCES, local)) {
// annotation "produces"
strings(value, name, produces);
} else if(eq(QUERY_PARAM, local)) {
// annotation "query-param"
queryParams.add(param(value, name, declared));
} else if(eq(FORM_PARAM, local)) {
// annotation "form-param"
formParams.add(param(value, name, declared));
} else if(eq(HEADER_PARAM, local)) {
// annotation "header-param"
headerParams.add(param(value, name, declared));
} else if(eq(COOKIE_PARAM, local)) {
// annotation "cookie-param"
cookieParams.add(param(value, name, declared));
} else {
// method annotations
final HTTPMethod m = HTTPMethod.get(string(local));
if(m == null) error(ANN_UNKNOWN, "%", name.string());
if(!value.isEmpty()) {
// remember post/put variable
if(requestBody != null) error(ANN_TWICE, "%", name.string());
if(m != POST && m != PUT) error(METHOD_VALUE, m);
requestBody = checkVariable(toString(value, name), declared);
}
if(mth.contains(m)) error(ANN_TWICE, "%", name.string());
mth.add(m);
}
} else if(eq(uri, QueryText.OUTPUTURI)) {
// serialization parameters
final String key = string(local);
final String val = toString(value, name);
if(output.get(key) == null) error(UNKNOWN_SER, key);
output.set(key, val);
}
found |= rexq;
}
if(!mth.isEmpty()) methods = mth;
if(found) {
if(path == null) error(ANN_MISSING, PATH);
for(int i = 0; i < declared.length; i++)
if(!declared[i]) error(VAR_UNDEFINED, function.args[i]);
}
return found;
}
| boolean analyze() throws QueryException {
// parse all annotations
final EnumSet<HTTPMethod> mth = EnumSet.noneOf(HTTPMethod.class);
final boolean[] declared = new boolean[function.args.length];
boolean found = false;
final int as = function.ann.size();
for(int a = 0; a < as; a++) {
final QNm name = function.ann.names[a];
final Value value = function.ann.values[a];
final byte[] local = name.local();
final byte[] uri = name.uri();
final boolean rexq = eq(uri, QueryText.RESTXQURI);
if(rexq) {
if(eq(PATH, local)) {
// annotation "path"
if(path != null) error(ANN_TWICE, "%", name.string());
path = new RestXqPath(toString(value, name));
for(final String s : path) {
if(s.trim().startsWith("{")) checkVariable(s, AtomType.AAT, declared);
}
} else if(eq(CONSUMES, local)) {
// annotation "consumes"
strings(value, name, consumes);
} else if(eq(PRODUCES, local)) {
// annotation "produces"
strings(value, name, produces);
} else if(eq(QUERY_PARAM, local)) {
// annotation "query-param"
queryParams.add(param(value, name, declared));
} else if(eq(FORM_PARAM, local)) {
// annotation "form-param"
formParams.add(param(value, name, declared));
} else if(eq(HEADER_PARAM, local)) {
// annotation "header-param"
headerParams.add(param(value, name, declared));
} else if(eq(COOKIE_PARAM, local)) {
// annotation "cookie-param"
cookieParams.add(param(value, name, declared));
} else {
// method annotations
final HTTPMethod m = HTTPMethod.get(string(local));
if(m == null) error(ANN_UNKNOWN, "%", name.string());
if(!value.isEmpty()) {
// remember post/put variable
if(requestBody != null) error(ANN_TWICE, "%", name.string());
if(m != POST && m != PUT) error(METHOD_VALUE, m);
requestBody = checkVariable(toString(value, name), declared);
}
if(mth.contains(m)) error(ANN_TWICE, "%", name.string());
mth.add(m);
}
} else if(eq(uri, QueryText.OUTPUTURI)) {
// serialization parameters
final String key = string(local);
final String val = toString(value, name);
if(output.get(key) == null) error(UNKNOWN_SER, key);
output.set(key, val);
}
found |= rexq;
}
if(!mth.isEmpty()) methods = mth;
if(found) {
if(path == null) error(ANN_MISSING, PATH);
for(int i = 0; i < declared.length; i++)
if(!declared[i]) error(VAR_UNDEFINED, function.args[i].name.string());
}
return found;
}
|
diff --git a/SVSierpinski/src/SierpinskiTriangle/Peg.java b/SVSierpinski/src/SierpinskiTriangle/Peg.java
index 8737477..30e323b 100644
--- a/SVSierpinski/src/SierpinskiTriangle/Peg.java
+++ b/SVSierpinski/src/SierpinskiTriangle/Peg.java
@@ -1,52 +1,56 @@
package SierpinskiTriangle;
import SVGraphics.*;
import SVGraphics.SVRectangle;
import static SierpinskiTriangle.SierpinskiTriangle.colors;
import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;
/**
* Peg class extends SVCustom is used by Tower class.
*
* @author Martin Wolfenbarger
* @version 2013/05/16
*/
public class Peg extends SVCustom{
public Peg(ArrayList<Integer> a, int total) {
super();
SVRectangle r = new SVRectangle(new Point(-3,20),6,60);
r.setBorderRadius(3);
r.setColor(Color.black);
addContent(r, "a");
if(total > 0) this.addDisks(a, total);
}
/** Draws the disks on this peg
@param a arraylist of integers
@param total total disks on all three pegs
*/
private void addDisks(ArrayList<Integer> a, int total) {
+ int current;
+ int sizeFactor;
for(int i = 0; a.size() > i; i++) {
- SVEllipse e = new SVEllipse(new Point(0,-1*i*13+68),30-i*3,14);
- SVEllipse esmall = new SVEllipse(new Point(0,-1*i*13+68),(26-i*3)/2,13);
- SVText t = new SVText(new Point(0,-1*i*13+73),""+a.get(i));
+ current = a.get(i);
+ sizeFactor = 10*(current+1)/total;
+ SVEllipse e = new SVEllipse(new Point(0,-1*i*13+68),20 + sizeFactor,14);
+ SVEllipse esmall = new SVEllipse(new Point(0,-1*i*13+68),11,13);
+ SVText t = new SVText(new Point(0,-1*i*13+73),""+current);
esmall.setColor(Color.white);
- e.setColor(this.getCurrentColor(a.get(i)));
+ e.setColor(this.getCurrentColor(current));
esmall.setBorderWidth(1);
esmall.setBorderColor(Color.lightGray);
addContent(e, "e"+i);
addContent(esmall, "esmall"+i);
addContent(t,"t"+i);
}
}
private Color getCurrentColor(int i) {
try {
return SierpinskiTriangle.colors.get(i);
} catch (IndexOutOfBoundsException iobe) {
return Color.BLACK;
}
}
}
| false | true | private void addDisks(ArrayList<Integer> a, int total) {
for(int i = 0; a.size() > i; i++) {
SVEllipse e = new SVEllipse(new Point(0,-1*i*13+68),30-i*3,14);
SVEllipse esmall = new SVEllipse(new Point(0,-1*i*13+68),(26-i*3)/2,13);
SVText t = new SVText(new Point(0,-1*i*13+73),""+a.get(i));
esmall.setColor(Color.white);
e.setColor(this.getCurrentColor(a.get(i)));
esmall.setBorderWidth(1);
esmall.setBorderColor(Color.lightGray);
addContent(e, "e"+i);
addContent(esmall, "esmall"+i);
addContent(t,"t"+i);
}
}
| private void addDisks(ArrayList<Integer> a, int total) {
int current;
int sizeFactor;
for(int i = 0; a.size() > i; i++) {
current = a.get(i);
sizeFactor = 10*(current+1)/total;
SVEllipse e = new SVEllipse(new Point(0,-1*i*13+68),20 + sizeFactor,14);
SVEllipse esmall = new SVEllipse(new Point(0,-1*i*13+68),11,13);
SVText t = new SVText(new Point(0,-1*i*13+73),""+current);
esmall.setColor(Color.white);
e.setColor(this.getCurrentColor(current));
esmall.setBorderWidth(1);
esmall.setBorderColor(Color.lightGray);
addContent(e, "e"+i);
addContent(esmall, "esmall"+i);
addContent(t,"t"+i);
}
}
|
diff --git a/DBoxBroker/src/dBox/Broker/DBoxBroker.java b/DBoxBroker/src/dBox/Broker/DBoxBroker.java
index 92a354f..2e4c45d 100644
--- a/DBoxBroker/src/dBox/Broker/DBoxBroker.java
+++ b/DBoxBroker/src/dBox/Broker/DBoxBroker.java
@@ -1,57 +1,57 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dBox.Broker;
import dBox.IAuthentication;
import dBox.ServerUtils.DataAccess;
import dBox.ServerUtils.MetaData;
import dBox.utils.ConfigManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author harsimran.maan
*/
public class DBoxBroker
{
private static void printMessage(String simpleName)
{
System.out.println("Bound " + simpleName);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
try
{
ConfigManager context = ConfigManager.getInstance();
- String server = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("hostname"));
+ String server = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("host"));
String ip = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("ip"));
System.setProperty("java.rmi.server.hostname", ip);
System.setProperty("java.net.preferIPv4Stack", "true");
printMessage(server + " " + ip);
// Bind the remote object in the registry
int port = Integer.parseInt(context.getPropertyValue("port"));
printMessage(String.valueOf(port));
Registry registry = LocateRegistry.createRegistry(port);
registry.rebind(IAuthentication.class.getSimpleName(), new Authenticator());
printMessage(IAuthentication.class.getSimpleName());
DataAccess.init(context.getPropertyValue("dbConnection"), context.getPropertyValue("dbUserId"), context.getPropertyValue("dbUserToken"));
System.out.println("Server started");
}
catch (RemoteException ex)
{
Logger.getLogger(DBoxBroker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true | true | public static void main(String[] args)
{
try
{
ConfigManager context = ConfigManager.getInstance();
String server = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("hostname"));
String ip = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("ip"));
System.setProperty("java.rmi.server.hostname", ip);
System.setProperty("java.net.preferIPv4Stack", "true");
printMessage(server + " " + ip);
// Bind the remote object in the registry
int port = Integer.parseInt(context.getPropertyValue("port"));
printMessage(String.valueOf(port));
Registry registry = LocateRegistry.createRegistry(port);
registry.rebind(IAuthentication.class.getSimpleName(), new Authenticator());
printMessage(IAuthentication.class.getSimpleName());
DataAccess.init(context.getPropertyValue("dbConnection"), context.getPropertyValue("dbUserId"), context.getPropertyValue("dbUserToken"));
System.out.println("Server started");
}
catch (RemoteException ex)
{
Logger.getLogger(DBoxBroker.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public static void main(String[] args)
{
try
{
ConfigManager context = ConfigManager.getInstance();
String server = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("host"));
String ip = MetaData.get(context.getPropertyValue("meta") + context.getPropertyValue("ip"));
System.setProperty("java.rmi.server.hostname", ip);
System.setProperty("java.net.preferIPv4Stack", "true");
printMessage(server + " " + ip);
// Bind the remote object in the registry
int port = Integer.parseInt(context.getPropertyValue("port"));
printMessage(String.valueOf(port));
Registry registry = LocateRegistry.createRegistry(port);
registry.rebind(IAuthentication.class.getSimpleName(), new Authenticator());
printMessage(IAuthentication.class.getSimpleName());
DataAccess.init(context.getPropertyValue("dbConnection"), context.getPropertyValue("dbUserId"), context.getPropertyValue("dbUserToken"));
System.out.println("Server started");
}
catch (RemoteException ex)
{
Logger.getLogger(DBoxBroker.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
diff --git a/nat/src/main/java/net/tomp2p/relay/Test.java b/nat/src/main/java/net/tomp2p/relay/Test.java
index 02699cdc..7d4bf9b3 100644
--- a/nat/src/main/java/net/tomp2p/relay/Test.java
+++ b/nat/src/main/java/net/tomp2p/relay/Test.java
@@ -1,88 +1,88 @@
package net.tomp2p.relay;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Random;
import net.tomp2p.connection.Bindings;
import net.tomp2p.futures.FutureGet;
import net.tomp2p.futures.FuturePut;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerMaker;
import net.tomp2p.peers.Number160;
import net.tomp2p.storage.Data;
public class Test {
private final static Random rnd = new Random();
private final static int PORT = 7777;
public static void main(String[] args) throws Exception {
/*
* 1. bootstrap: no arguments
* 2. put: <bootstrap address> <key> <value>
* 3. get: <bootstrap address> <key>
*/
if (args.length == 0) {
//bootstrap node
Bindings b = new Bindings();
Peer peer = new PeerMaker(Number160.createHash("boot")).setEnableMaintenance(false).ports(PORT).bindings(b).makeAndListen();
System.err.println("bootstrap peer id: " + peer.getPeerAddress().getPeerId());
- new RelayRPC(peer);
+ RelayRPC.setup(peer);
System.err.println("bootstrap peer is running");
while(true) {
Thread.sleep(10000);
System.err.println(peer.getPeerBean().peerMap().peerMapVerified());
}
} else if (args.length == 3) {
//put
int port = (rnd.nextInt() % 10000) + 10000;
Peer peer = new PeerMaker(Number160.createHash(args[1])).ports(port).setEnableMaintenance(false).makeAndListen();
System.err.println("put peer id: " + peer.getPeerAddress().getPeerId());
- new RelayRPC(peer);
+ RelayRPC.setup(peer);
InetAddress address = Inet4Address.getByName(args[0]);
//RelayManager manager = new RelayManager(peer, new PeerAddress(bootstrapId, InetSocketAddress.createUnresolved(args[0], PORT)));
- RelayFuture rf = new RelayBuilder(peer).bootstrapInetAddress(address).ports(PORT).start();
+ RelayFuture rf = new RelayBuilder(new RelayPeer(peer)).bootstrapInetAddress(address).ports(PORT).start();
rf.awaitUninterruptibly();
if (rf.isSuccess()) {
System.err.println("Successfuly set up relays");
Thread.sleep(1000);
}
FuturePut fp = peer.put(Number160.createHash(args[1])).setData(new Data(args[2].toUpperCase())).start();
System.err.println("hash:" + Number160.createHash(args[1]));
fp.awaitUninterruptibly();
if (fp.isSuccess()) {
System.err.println("Successfully stored " + args[1] + ":" + args[2]);
}
} else if (args.length == 2) {
//get
int port = (rnd.nextInt() % 10000) + 10000;
Peer peer = new PeerMaker(Number160.createHash("bla")).setEnableMaintenance(false).ports(port).makeAndListen();
System.err.println("get peer id: " + peer.getPeerAddress().getPeerId());
System.err.println("hash:" + Number160.createHash(args[1]));
InetAddress address = Inet4Address.getByName(args[0]);
- RelayFuture rf = new RelayBuilder(peer).bootstrapInetAddress(address).ports(PORT).start();
+ RelayFuture rf = new RelayBuilder(new RelayPeer(peer)).bootstrapInetAddress(address).ports(PORT).start();
rf.awaitUninterruptibly();
if (rf.isSuccess()) {
System.err.println("Successfuly set up relays");
}
FutureGet fg = peer.get(Number160.createHash(args[1])).start();
fg.awaitUninterruptibly();
if (fg.isSuccess()) {
System.err.println("Received: " + fg.getData().object());
} else {
System.err.println(fg.getFailedReason());
}
}
}
}
| false | true | public static void main(String[] args) throws Exception {
/*
* 1. bootstrap: no arguments
* 2. put: <bootstrap address> <key> <value>
* 3. get: <bootstrap address> <key>
*/
if (args.length == 0) {
//bootstrap node
Bindings b = new Bindings();
Peer peer = new PeerMaker(Number160.createHash("boot")).setEnableMaintenance(false).ports(PORT).bindings(b).makeAndListen();
System.err.println("bootstrap peer id: " + peer.getPeerAddress().getPeerId());
new RelayRPC(peer);
System.err.println("bootstrap peer is running");
while(true) {
Thread.sleep(10000);
System.err.println(peer.getPeerBean().peerMap().peerMapVerified());
}
} else if (args.length == 3) {
//put
int port = (rnd.nextInt() % 10000) + 10000;
Peer peer = new PeerMaker(Number160.createHash(args[1])).ports(port).setEnableMaintenance(false).makeAndListen();
System.err.println("put peer id: " + peer.getPeerAddress().getPeerId());
new RelayRPC(peer);
InetAddress address = Inet4Address.getByName(args[0]);
//RelayManager manager = new RelayManager(peer, new PeerAddress(bootstrapId, InetSocketAddress.createUnresolved(args[0], PORT)));
RelayFuture rf = new RelayBuilder(peer).bootstrapInetAddress(address).ports(PORT).start();
rf.awaitUninterruptibly();
if (rf.isSuccess()) {
System.err.println("Successfuly set up relays");
Thread.sleep(1000);
}
FuturePut fp = peer.put(Number160.createHash(args[1])).setData(new Data(args[2].toUpperCase())).start();
System.err.println("hash:" + Number160.createHash(args[1]));
fp.awaitUninterruptibly();
if (fp.isSuccess()) {
System.err.println("Successfully stored " + args[1] + ":" + args[2]);
}
} else if (args.length == 2) {
//get
int port = (rnd.nextInt() % 10000) + 10000;
Peer peer = new PeerMaker(Number160.createHash("bla")).setEnableMaintenance(false).ports(port).makeAndListen();
System.err.println("get peer id: " + peer.getPeerAddress().getPeerId());
System.err.println("hash:" + Number160.createHash(args[1]));
InetAddress address = Inet4Address.getByName(args[0]);
RelayFuture rf = new RelayBuilder(peer).bootstrapInetAddress(address).ports(PORT).start();
rf.awaitUninterruptibly();
if (rf.isSuccess()) {
System.err.println("Successfuly set up relays");
}
FutureGet fg = peer.get(Number160.createHash(args[1])).start();
fg.awaitUninterruptibly();
if (fg.isSuccess()) {
System.err.println("Received: " + fg.getData().object());
} else {
System.err.println(fg.getFailedReason());
}
}
}
| public static void main(String[] args) throws Exception {
/*
* 1. bootstrap: no arguments
* 2. put: <bootstrap address> <key> <value>
* 3. get: <bootstrap address> <key>
*/
if (args.length == 0) {
//bootstrap node
Bindings b = new Bindings();
Peer peer = new PeerMaker(Number160.createHash("boot")).setEnableMaintenance(false).ports(PORT).bindings(b).makeAndListen();
System.err.println("bootstrap peer id: " + peer.getPeerAddress().getPeerId());
RelayRPC.setup(peer);
System.err.println("bootstrap peer is running");
while(true) {
Thread.sleep(10000);
System.err.println(peer.getPeerBean().peerMap().peerMapVerified());
}
} else if (args.length == 3) {
//put
int port = (rnd.nextInt() % 10000) + 10000;
Peer peer = new PeerMaker(Number160.createHash(args[1])).ports(port).setEnableMaintenance(false).makeAndListen();
System.err.println("put peer id: " + peer.getPeerAddress().getPeerId());
RelayRPC.setup(peer);
InetAddress address = Inet4Address.getByName(args[0]);
//RelayManager manager = new RelayManager(peer, new PeerAddress(bootstrapId, InetSocketAddress.createUnresolved(args[0], PORT)));
RelayFuture rf = new RelayBuilder(new RelayPeer(peer)).bootstrapInetAddress(address).ports(PORT).start();
rf.awaitUninterruptibly();
if (rf.isSuccess()) {
System.err.println("Successfuly set up relays");
Thread.sleep(1000);
}
FuturePut fp = peer.put(Number160.createHash(args[1])).setData(new Data(args[2].toUpperCase())).start();
System.err.println("hash:" + Number160.createHash(args[1]));
fp.awaitUninterruptibly();
if (fp.isSuccess()) {
System.err.println("Successfully stored " + args[1] + ":" + args[2]);
}
} else if (args.length == 2) {
//get
int port = (rnd.nextInt() % 10000) + 10000;
Peer peer = new PeerMaker(Number160.createHash("bla")).setEnableMaintenance(false).ports(port).makeAndListen();
System.err.println("get peer id: " + peer.getPeerAddress().getPeerId());
System.err.println("hash:" + Number160.createHash(args[1]));
InetAddress address = Inet4Address.getByName(args[0]);
RelayFuture rf = new RelayBuilder(new RelayPeer(peer)).bootstrapInetAddress(address).ports(PORT).start();
rf.awaitUninterruptibly();
if (rf.isSuccess()) {
System.err.println("Successfuly set up relays");
}
FutureGet fg = peer.get(Number160.createHash(args[1])).start();
fg.awaitUninterruptibly();
if (fg.isSuccess()) {
System.err.println("Received: " + fg.getData().object());
} else {
System.err.println(fg.getFailedReason());
}
}
}
|
diff --git a/src/com/norcode/bukkit/jukeloop/LoopingJukebox.java b/src/com/norcode/bukkit/jukeloop/LoopingJukebox.java
index 0fbae84..433d93b 100644
--- a/src/com/norcode/bukkit/jukeloop/LoopingJukebox.java
+++ b/src/com/norcode/bukkit/jukeloop/LoopingJukebox.java
@@ -1,182 +1,184 @@
package com.norcode.bukkit.jukeloop;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Chest;
import org.bukkit.block.Jukebox;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class LoopingJukebox {
private Location location;
private Jukebox jukebox;
private Chest chest;
private JukeLoopPlugin plugin;
private int startedAt = -1;
public boolean isDead = false;
public static LinkedHashMap<Location, LoopingJukebox> jukeboxMap = new LinkedHashMap<Location, LoopingJukebox>();
public static LoopingJukebox getAt(JukeLoopPlugin plugin, Location loc) {
LoopingJukebox box = null;
if (jukeboxMap.containsKey(loc)) {
box = jukeboxMap.get(loc);
} else {
box = new LoopingJukebox(plugin, loc);
}
if (box.validate()) {
jukeboxMap.put(loc, box);
return box;
}
return null;
}
public Location getLocation() {
return location;
}
public LoopingJukebox(JukeLoopPlugin plugin, Location location) {
this.location = location;
this.plugin = plugin;
}
public void log(String msg) {
plugin.getLogger().info("[Jukebox@" + location.getWorld().getName() + " " + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ() + "] " + msg);
}
public Jukebox getJukebox() {
try {
return (Jukebox)this.location.getBlock().getState();
} catch (ClassCastException ex) {
return null;
}
}
public Chest getChest() {
if (this.chest == null) {
return null;
} else {
try {
return (Chest)this.chest.getBlock().getLocation().getBlock().getState();
} catch (ClassCastException ex) {}
}
return null;
}
public boolean validate() {
try {
this.jukebox = (Jukebox)this.location.getBlock().getState();
} catch (ClassCastException ex) {
return false;
}
this.chest = null;
BlockState rel = null;
for (BlockFace f: plugin.directions) {
try {
rel = (BlockState)this.jukebox.getBlock().getRelative(f).getState();
this.chest = (Chest)rel;
} catch (ClassCastException ex) {
continue;
}
}
return true;
}
public boolean playersNearby() {
double dist;
for (Player p: plugin.getServer().getOnlinePlayers()) {
try {
dist = getJukebox().getLocation().distance(p.getLocation());
if (dist <= 64) {
return true;
}
} catch (IllegalArgumentException ex) {
// Cannot measure distance between 2 different worlds.
//log(ex.getMessage());
}
}
return false;
}
public void doLoop() {
Jukebox jukebox = getJukebox();
if (jukebox == null) {
log("Destroyed, removing from cache");
this.isDead = true;
return;
}
if (!getJukebox().isPlaying()) return;
int now = (int)(System.currentTimeMillis()/1000);
Material record = this.jukebox.getPlaying();
if (now - startedAt > plugin.recordDurations.get(record)) {
if (!playersNearby()) return;
if (this.getChest() == null) {
loopOneDisc(now);
} else {
loopFromChest(now);
}
}
}
private void loopOneDisc(int now) {
Material record = this.getJukebox().getPlaying();
log("Looping single disc: " + plugin.recordNames.get(record));
this.getJukebox().setPlaying(record);
onInsert(record);
}
public void onInsert(Material record) {
startedAt = (int)(System.currentTimeMillis()/1000);
}
public void onEject() {
this.startedAt = -1;
}
private void loopFromChest(int now) {
Jukebox jukebox = getJukebox();
Material record = jukebox.getPlaying();
Chest chest = getChest();
int idx = chest.getBlockInventory().firstEmpty();
if (idx == -1) {
loopOneDisc(now);
return;
}
chest.getBlockInventory().setItem(idx, new ItemStack(record));
Material newRecord = null;
ItemStack[] contents = chest.getBlockInventory().getContents();
int i=idx +1;
if (i >= chest.getBlockInventory().getSize()) i = 0;
while (newRecord == null) {
if (contents[i] != null) {
if (plugin.recordDurations.containsKey(contents[i].getType())) {
newRecord = contents[i].getType();
chest.getBlockInventory().setItem(i, new ItemStack(Material.AIR));
break;
}
}
i++;
if (i == contents.length) i = 0;
if (i == idx) break;
}
log("Looping from chest: " + plugin.recordNames.get(record) + " -> " + plugin.recordNames.get(newRecord));
this.startedAt = now;
- jukebox.setPlaying(newRecord);
+ if (newRecord != null) {
+ jukebox.setPlaying(newRecord);
+ }
}
}
| true | true | private void loopFromChest(int now) {
Jukebox jukebox = getJukebox();
Material record = jukebox.getPlaying();
Chest chest = getChest();
int idx = chest.getBlockInventory().firstEmpty();
if (idx == -1) {
loopOneDisc(now);
return;
}
chest.getBlockInventory().setItem(idx, new ItemStack(record));
Material newRecord = null;
ItemStack[] contents = chest.getBlockInventory().getContents();
int i=idx +1;
if (i >= chest.getBlockInventory().getSize()) i = 0;
while (newRecord == null) {
if (contents[i] != null) {
if (plugin.recordDurations.containsKey(contents[i].getType())) {
newRecord = contents[i].getType();
chest.getBlockInventory().setItem(i, new ItemStack(Material.AIR));
break;
}
}
i++;
if (i == contents.length) i = 0;
if (i == idx) break;
}
log("Looping from chest: " + plugin.recordNames.get(record) + " -> " + plugin.recordNames.get(newRecord));
this.startedAt = now;
jukebox.setPlaying(newRecord);
}
| private void loopFromChest(int now) {
Jukebox jukebox = getJukebox();
Material record = jukebox.getPlaying();
Chest chest = getChest();
int idx = chest.getBlockInventory().firstEmpty();
if (idx == -1) {
loopOneDisc(now);
return;
}
chest.getBlockInventory().setItem(idx, new ItemStack(record));
Material newRecord = null;
ItemStack[] contents = chest.getBlockInventory().getContents();
int i=idx +1;
if (i >= chest.getBlockInventory().getSize()) i = 0;
while (newRecord == null) {
if (contents[i] != null) {
if (plugin.recordDurations.containsKey(contents[i].getType())) {
newRecord = contents[i].getType();
chest.getBlockInventory().setItem(i, new ItemStack(Material.AIR));
break;
}
}
i++;
if (i == contents.length) i = 0;
if (i == idx) break;
}
log("Looping from chest: " + plugin.recordNames.get(record) + " -> " + plugin.recordNames.get(newRecord));
this.startedAt = now;
if (newRecord != null) {
jukebox.setPlaying(newRecord);
}
}
|
diff --git a/src/org/meta_environment/rascal/interpreter/TraversalEvaluator.java b/src/org/meta_environment/rascal/interpreter/TraversalEvaluator.java
index be5921f1e4..484734e07d 100644
--- a/src/org/meta_environment/rascal/interpreter/TraversalEvaluator.java
+++ b/src/org/meta_environment/rascal/interpreter/TraversalEvaluator.java
@@ -1,481 +1,481 @@
package org.meta_environment.rascal.interpreter;
import static org.meta_environment.rascal.interpreter.result.ResultFactory.makeResult;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map.Entry;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IMapWriter;
import org.eclipse.imp.pdb.facts.INode;
import org.eclipse.imp.pdb.facts.ISet;
import org.eclipse.imp.pdb.facts.ISetWriter;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.ITuple;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.meta_environment.rascal.ast.Case;
import org.meta_environment.rascal.ast.Expression;
import org.meta_environment.rascal.ast.Replacement;
import org.meta_environment.rascal.interpreter.asserts.ImplementationError;
import org.meta_environment.rascal.interpreter.env.Environment;
import org.meta_environment.rascal.interpreter.env.RewriteRule;
import org.meta_environment.rascal.interpreter.matching.IBooleanResult;
import org.meta_environment.rascal.interpreter.matching.LiteralPattern;
import org.meta_environment.rascal.interpreter.matching.RegExpPatternValue;
import org.meta_environment.rascal.interpreter.staticErrors.SyntaxError;
import org.meta_environment.rascal.interpreter.staticErrors.UnexpectedTypeError;
// TODO: this class is still too tightly coupled with evaluator
public class TraversalEvaluator {
public enum DIRECTION {BottomUp, TopDown} // Parameters for traversing trees
public enum FIXEDPOINT {Yes, No}
public enum PROGRESS {Continuing, Breaking}
private final Evaluator eval;
private static final TypeFactory tf = TypeFactory.getInstance();
public TraversalEvaluator(Evaluator eval) {
this.eval = eval;
}
/*
* TraverseResult contains the value returned by a traversal
* and a changed flag that indicates whether the value itself or
* any of its children has been changed during the traversal.
*/
// TODO: can this be put in the result hierarchy?
public class TraverseResult {
public final boolean matched; // Some rule matched;
public final IValue value; // Result<IValue> of the
public final boolean changed; // Original subject has been changed
public TraverseResult(boolean someMatch, IValue value){
this.matched = someMatch;
this.value = value;
this.changed = false;
}
public TraverseResult(IValue value){
this.matched = false;
this.value = value;
this.changed = false;
}
public TraverseResult(IValue value, boolean changed){
this.matched = true;
this.value = value;
this.changed = changed;
}
public TraverseResult(boolean someMatch, IValue value, boolean changed){
this.matched = someMatch;
this.value = value;
this.changed = changed;
}
}
/*
* CaseOrRule is the union of a Case or a Rule and allows the sharing of
* traversal code for both.
*/
public class CasesOrRules {
private java.util.List<Case> cases;
private java.util.List<RewriteRule> rules;
@SuppressWarnings("unchecked")
public CasesOrRules(java.util.List<?> casesOrRules){
if(casesOrRules.get(0) instanceof Case){
this.cases = (java.util.List<Case>) casesOrRules;
} else {
rules = (java.util.List<RewriteRule>)casesOrRules;
}
}
public boolean hasRules(){
return rules != null;
}
public boolean hasCases(){
return cases != null;
}
public int length(){
return (cases != null) ? cases.size() : rules.size();
}
public java.util.List<Case> getCases(){
return cases;
}
public java.util.List<RewriteRule> getRules(){
return rules;
}
}
public TraverseResult traverse(IValue subject, CasesOrRules casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint) {
//System.err.println("traverse: subject=" + subject + ", casesOrRules=" + casesOrRules);
do {
TraverseResult tr = traverseOnce(subject, casesOrRules, direction, progress);
if(fixedpoint == FIXEDPOINT.Yes){
if (!tr.changed) {
return tr;
}
subject = tr.value;
} else {
return tr;
}
} while (true);
}
private TraverseResult traverseOnce(IValue subject, CasesOrRules casesOrRules,
DIRECTION direction, PROGRESS progress){
Type subjectType = subject.getType();
boolean matched = false;
boolean changed = false;
IValue result = subject;
//System.err.println("traverseOnce: " + subject + ", type=" + subject.getType() + ", direction=" + direction + ", progress=" + progress);
if(subjectType.isStringType()){
return traverseString(subject, casesOrRules);
}
if(direction == DIRECTION.TopDown){
TraverseResult tr = traverseTop(subjectType, subject, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
- if((progress == PROGRESS.Breaking) && changed){
+ if((progress == PROGRESS.Breaking) && matched){
return tr;
}
subject = tr.value;
}
if(subjectType.isAbstractDataType()){
IConstructor cons = (IConstructor)subject;
if(cons.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[cons.arity()];
for(int i = 0; i < cons.arity(); i++){
IValue child = cons.get(i);
// Type childType = cons.getConstructorType().getFieldType(i);
TraverseResult tr = traverseOnce(child, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
Type t = cons.getConstructorType();
IConstructor rcons = eval.getValueFactory().constructor(t, args);
if(cons.hasAnnotations()) rcons = rcons.setAnnotations(cons.getAnnotations());
result = applyRules(t, rcons);
}
} else if(subjectType.isNodeType()){
INode node = (INode)subject;
if(node.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[node.arity()];
for(int i = 0; i < node.arity(); i++){
IValue child = node.get(i);
TraverseResult tr = traverseOnce(child, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
INode n = eval.getValueFactory().node(node.getName(), args);
if(node.hasAnnotations()) n = n.setAnnotations(node.getAnnotations());
result = applyRules(tf.nodeType(), n);
}
} else if(subjectType.isListType()){
IList list = (IList) subject;
int len = list.length();
if(len > 0){
IListWriter w = list.getType().writer(eval.getValueFactory());
for(int i = 0; i < len; i++){
IValue elem = list.get(i);
TraverseResult tr = traverseOnce(elem, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.append(tr.value);
}
result = w.done();
} else {
result = subject;
}
} else if(subjectType.isSetType()){
ISet set = (ISet) subject;
if(!set.isEmpty()){
ISetWriter w = set.getType().writer(eval.getValueFactory());
for (IValue v : set){
TraverseResult tr = traverseOnce(v, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value);
}
result = w.done();
} else {
result = subject;
}
} else if (subjectType.isMapType()) {
IMap map = (IMap) subject;
if(!map.isEmpty()){
IMapWriter w = map.getType().writer(eval.getValueFactory());
Iterator<Entry<IValue,IValue>> iter = map.entryIterator();
while (iter.hasNext()) {
Entry<IValue,IValue> entry = iter.next();
TraverseResult tr = traverseOnce(entry.getKey(), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newKey = tr.value;
tr = traverseOnce(entry.getValue(), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newValue = tr.value;
w.put(newKey, newValue);
}
result = w.done();
} else {
result = subject;
}
} else if(subjectType.isTupleType()){
ITuple tuple = (ITuple) subject;
int arity = tuple.arity();
IValue args[] = new IValue[arity];
for(int i = 0; i < arity; i++){
TraverseResult tr = traverseOnce(tuple.get(i), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
result = eval.getValueFactory().tuple(args);
} else {
result = subject;
}
if(direction == DIRECTION.BottomUp){
//System.err.println("traverseOnce: bottomup: changed=" + changed);
if((progress == PROGRESS.Breaking) && changed){
return new TraverseResult(matched, result, changed);
}
TraverseResult tr = traverseTop(subjectType, result, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
return new TraverseResult(matched, tr.value, changed);
}
return new TraverseResult(matched,result,changed);
}
/**
* Replace an old subject by a new one as result of an insert statement.
*/
private TraverseResult replacement(Type type, IValue oldSubject, IValue newSubject){
if(newSubject.getType().equivalent((oldSubject.getType())))
return new TraverseResult(true, newSubject, true);
throw new UnexpectedTypeError(oldSubject.getType(), newSubject.getType(), eval.getCurrentAST());
}
/**
* Loop over all cases or rules.
*/
public TraverseResult applyCasesOrRules(Type type, IValue subject, CasesOrRules casesOrRules) {
//System.err.println("applyCasesOrRules: " + subject.getValue());
if(casesOrRules.hasCases()){
for (Case cs : casesOrRules.getCases()) {
Environment old = eval.getCurrentEnvt();
try {
eval.pushEnv();
eval.setCurrentAST(cs);
if (cs.isDefault()) {
cs.getStatement().accept(eval);
return new TraverseResult(true,subject);
}
TraverseResult tr = applyOneRule(type, subject, cs.getPatternWithAction());
//System.err.println("applyCasesOrRules: matches");
if(tr.matched){
return tr;
}
}
finally {
eval.unwind(old);
}
}
} else {
//System.err.println("hasRules");
for(RewriteRule rule : casesOrRules.getRules()){
Environment oldEnv = eval.getCurrentEnvt();
try {
eval.setCurrentAST(rule.getRule());
eval.setCurrentEnvt(rule.getEnvironment());
eval.pushEnv();
TraverseResult tr = applyOneRule(type, subject, rule.getRule());
if(tr.matched){
return tr;
}
}
finally {
eval.setCurrentEnvt(oldEnv);
}
}
}
//System.err.println("applyCasesorRules does not match");
return new TraverseResult(subject);
}
/*
* traverseTop: traverse the outermost symbol of the subject.
*/
public TraverseResult traverseTop(Type type, IValue subject, CasesOrRules casesOrRules) {
//System.err.println("traversTop(" + subject + ")");
try {
return applyCasesOrRules(type, subject, casesOrRules);
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e) {
//System.err.println("traversTop(" + subject + "): replacement: " + e.getValue());
return replacement(type, subject, e.getValue().getValue());
}
}
/*
* traverseString implements a visit of a string subject by visiting subsequent substrings
* subject[0,len], subject[1,len] ...and trying to match the cases. If a case matches
* the subject cursor is advanced by the length of the match and the matched substring may be replaced.
* At the end, the subject string including all replacements is returned.
*
* Performance issue: we create a lot of garbage by producing all these substrings.
*/
public TraverseResult traverseString(IValue subject, CasesOrRules casesOrRules){
String subjectString = ((IString) subject).getValue();
int len = subjectString.length();
boolean matched = false;
boolean changed = false;
int subjectCursor = 0;
int subjectCursorForResult = 0;
StringBuffer replacementString = null;
while(subjectCursor < len){
//System.err.println("cursor = " + cursor);
try {
IString substring = eval.getValueFactory().string(subjectString.substring(subjectCursor, len));
IValue subresult = substring;
TraverseResult tr = applyCasesOrRules(subresult.getType(), subresult, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
//System.err.println("matched=" + matched + ", changed=" + changed);
subjectCursor++;
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){
IValue repl = e.getValue().getValue();
if(repl.getType().isStringType()){
int start;
int end;
IBooleanResult lastPattern = e.getMatchPattern();
if(lastPattern == null)
throw new ImplementationError("No last pattern known");
if(lastPattern instanceof RegExpPatternValue){
start = ((RegExpPatternValue)lastPattern).getStart();
end = ((RegExpPatternValue)lastPattern).getEnd();
} else if(lastPattern instanceof LiteralPattern){
start = 0;
end = ((IString)repl).getValue().length();
} else {
throw new SyntaxError("Illegal pattern " + lastPattern + " in string visit", eval.getCurrentAST().getLocation());
}
// Create replacementString when this is the first replacement
if(replacementString == null)
replacementString = new StringBuffer();
// Copy replacement into replacement string
for(; subjectCursorForResult < subjectCursor + start; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
subjectCursorForResult = subjectCursor + end;
replacementString.append(((IString)repl).getValue());
matched = changed = true;
subjectCursor += end;
} else {
throw new UnexpectedTypeError(tf.stringType(),repl.getType(), eval.getCurrentAST());
}
}
}
if(!changed){
return new TraverseResult(matched, subject, changed);
}
// Copy remaining characters of subject string into replacement string
for(; subjectCursorForResult < len; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
return new TraverseResult(matched, eval.getValueFactory().string(replacementString.toString()), changed);
}
/*
* applyOneRule: try to apply one rule to the subject.
*/
private TraverseResult applyOneRule(Type type, IValue subject, org.meta_environment.rascal.ast.PatternWithAction rule) {
//System.err.println("applyOneRule: subject=" + subject + ", type=" + subject.getType() + ", rule=" + rule);
if (rule.isArbitrary()){
if(eval.matchAndEval(makeResult(type, subject, eval), rule.getPattern(), rule.getStatement())) {
return new TraverseResult(true, subject);
}
/*
} else if (rule.isGuarded()) {
org.meta_environment.rascal.ast.Type tp = rule.getType();
Type type = evalType(tp);
rule = rule.getRule();
if (subject.getType().isSubtypeOf(type) &&
matchAndEval(subject, rule.getPattern(), rule.getStatement())) {
return new TraverseResult(true, subject);
}
*/
} else if (rule.isReplacing()) {
//System.err.println("applyOneRule: subject=" + subject + ", replacing");
Replacement repl = rule.getReplacement();
java.util.List<Expression> conditions = repl.isConditional() ? repl.getConditions() : new ArrayList<Expression>();
if(eval.matchEvalAndReplace(makeResult(type, subject, eval), rule.getPattern(), conditions, repl.getReplacementExpression())){
//System.err.println("applyOneRule: matches");
return new TraverseResult(true, subject);
}
} else {
throw new ImplementationError("Impossible case in rule");
}
return new TraverseResult(subject);
}
public IValue applyRules(Type type, IValue value){
Type typeToSearchFor = value.getType();
if (typeToSearchFor.isAbstractDataType()) {
typeToSearchFor = ((IConstructor) value).getConstructorType();
}
java.util.List<RewriteRule> rules = eval.getHeap().getRules(typeToSearchFor);
if (rules.size() > 0) {
TraverseResult tr = traverseTop(type, value, new CasesOrRules(rules));
return tr.value;
}
return value;
}
}
| true | true | private TraverseResult traverseOnce(IValue subject, CasesOrRules casesOrRules,
DIRECTION direction, PROGRESS progress){
Type subjectType = subject.getType();
boolean matched = false;
boolean changed = false;
IValue result = subject;
//System.err.println("traverseOnce: " + subject + ", type=" + subject.getType() + ", direction=" + direction + ", progress=" + progress);
if(subjectType.isStringType()){
return traverseString(subject, casesOrRules);
}
if(direction == DIRECTION.TopDown){
TraverseResult tr = traverseTop(subjectType, subject, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
if((progress == PROGRESS.Breaking) && changed){
return tr;
}
subject = tr.value;
}
if(subjectType.isAbstractDataType()){
IConstructor cons = (IConstructor)subject;
if(cons.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[cons.arity()];
for(int i = 0; i < cons.arity(); i++){
IValue child = cons.get(i);
// Type childType = cons.getConstructorType().getFieldType(i);
TraverseResult tr = traverseOnce(child, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
Type t = cons.getConstructorType();
IConstructor rcons = eval.getValueFactory().constructor(t, args);
if(cons.hasAnnotations()) rcons = rcons.setAnnotations(cons.getAnnotations());
result = applyRules(t, rcons);
}
} else if(subjectType.isNodeType()){
INode node = (INode)subject;
if(node.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[node.arity()];
for(int i = 0; i < node.arity(); i++){
IValue child = node.get(i);
TraverseResult tr = traverseOnce(child, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
INode n = eval.getValueFactory().node(node.getName(), args);
if(node.hasAnnotations()) n = n.setAnnotations(node.getAnnotations());
result = applyRules(tf.nodeType(), n);
}
} else if(subjectType.isListType()){
IList list = (IList) subject;
int len = list.length();
if(len > 0){
IListWriter w = list.getType().writer(eval.getValueFactory());
for(int i = 0; i < len; i++){
IValue elem = list.get(i);
TraverseResult tr = traverseOnce(elem, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.append(tr.value);
}
result = w.done();
} else {
result = subject;
}
} else if(subjectType.isSetType()){
ISet set = (ISet) subject;
if(!set.isEmpty()){
ISetWriter w = set.getType().writer(eval.getValueFactory());
for (IValue v : set){
TraverseResult tr = traverseOnce(v, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value);
}
result = w.done();
} else {
result = subject;
}
} else if (subjectType.isMapType()) {
IMap map = (IMap) subject;
if(!map.isEmpty()){
IMapWriter w = map.getType().writer(eval.getValueFactory());
Iterator<Entry<IValue,IValue>> iter = map.entryIterator();
while (iter.hasNext()) {
Entry<IValue,IValue> entry = iter.next();
TraverseResult tr = traverseOnce(entry.getKey(), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newKey = tr.value;
tr = traverseOnce(entry.getValue(), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newValue = tr.value;
w.put(newKey, newValue);
}
result = w.done();
} else {
result = subject;
}
} else if(subjectType.isTupleType()){
ITuple tuple = (ITuple) subject;
int arity = tuple.arity();
IValue args[] = new IValue[arity];
for(int i = 0; i < arity; i++){
TraverseResult tr = traverseOnce(tuple.get(i), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
result = eval.getValueFactory().tuple(args);
} else {
result = subject;
}
if(direction == DIRECTION.BottomUp){
//System.err.println("traverseOnce: bottomup: changed=" + changed);
if((progress == PROGRESS.Breaking) && changed){
return new TraverseResult(matched, result, changed);
}
TraverseResult tr = traverseTop(subjectType, result, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
return new TraverseResult(matched, tr.value, changed);
}
return new TraverseResult(matched,result,changed);
}
| private TraverseResult traverseOnce(IValue subject, CasesOrRules casesOrRules,
DIRECTION direction, PROGRESS progress){
Type subjectType = subject.getType();
boolean matched = false;
boolean changed = false;
IValue result = subject;
//System.err.println("traverseOnce: " + subject + ", type=" + subject.getType() + ", direction=" + direction + ", progress=" + progress);
if(subjectType.isStringType()){
return traverseString(subject, casesOrRules);
}
if(direction == DIRECTION.TopDown){
TraverseResult tr = traverseTop(subjectType, subject, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
if((progress == PROGRESS.Breaking) && matched){
return tr;
}
subject = tr.value;
}
if(subjectType.isAbstractDataType()){
IConstructor cons = (IConstructor)subject;
if(cons.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[cons.arity()];
for(int i = 0; i < cons.arity(); i++){
IValue child = cons.get(i);
// Type childType = cons.getConstructorType().getFieldType(i);
TraverseResult tr = traverseOnce(child, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
Type t = cons.getConstructorType();
IConstructor rcons = eval.getValueFactory().constructor(t, args);
if(cons.hasAnnotations()) rcons = rcons.setAnnotations(cons.getAnnotations());
result = applyRules(t, rcons);
}
} else if(subjectType.isNodeType()){
INode node = (INode)subject;
if(node.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[node.arity()];
for(int i = 0; i < node.arity(); i++){
IValue child = node.get(i);
TraverseResult tr = traverseOnce(child, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
INode n = eval.getValueFactory().node(node.getName(), args);
if(node.hasAnnotations()) n = n.setAnnotations(node.getAnnotations());
result = applyRules(tf.nodeType(), n);
}
} else if(subjectType.isListType()){
IList list = (IList) subject;
int len = list.length();
if(len > 0){
IListWriter w = list.getType().writer(eval.getValueFactory());
for(int i = 0; i < len; i++){
IValue elem = list.get(i);
TraverseResult tr = traverseOnce(elem, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.append(tr.value);
}
result = w.done();
} else {
result = subject;
}
} else if(subjectType.isSetType()){
ISet set = (ISet) subject;
if(!set.isEmpty()){
ISetWriter w = set.getType().writer(eval.getValueFactory());
for (IValue v : set){
TraverseResult tr = traverseOnce(v, casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value);
}
result = w.done();
} else {
result = subject;
}
} else if (subjectType.isMapType()) {
IMap map = (IMap) subject;
if(!map.isEmpty()){
IMapWriter w = map.getType().writer(eval.getValueFactory());
Iterator<Entry<IValue,IValue>> iter = map.entryIterator();
while (iter.hasNext()) {
Entry<IValue,IValue> entry = iter.next();
TraverseResult tr = traverseOnce(entry.getKey(), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newKey = tr.value;
tr = traverseOnce(entry.getValue(), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newValue = tr.value;
w.put(newKey, newValue);
}
result = w.done();
} else {
result = subject;
}
} else if(subjectType.isTupleType()){
ITuple tuple = (ITuple) subject;
int arity = tuple.arity();
IValue args[] = new IValue[arity];
for(int i = 0; i < arity; i++){
TraverseResult tr = traverseOnce(tuple.get(i), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value;
}
result = eval.getValueFactory().tuple(args);
} else {
result = subject;
}
if(direction == DIRECTION.BottomUp){
//System.err.println("traverseOnce: bottomup: changed=" + changed);
if((progress == PROGRESS.Breaking) && changed){
return new TraverseResult(matched, result, changed);
}
TraverseResult tr = traverseTop(subjectType, result, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
return new TraverseResult(matched, tr.value, changed);
}
return new TraverseResult(matched,result,changed);
}
|
diff --git a/src/main/java/com/github/davidmoten/logan/Data.java b/src/main/java/com/github/davidmoten/logan/Data.java
index 685dd9f..0f9e7a7 100644
--- a/src/main/java/com/github/davidmoten/logan/Data.java
+++ b/src/main/java/com/github/davidmoten/logan/Data.java
@@ -1,274 +1,274 @@
package com.github.davidmoten.logan;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
public class Data {
private static final int DEFAULT_MAX_SIZE = 1000000;
private static Logger log = Logger.getLogger(Data.class.getName());
private TreeMap<Long, Collection<LogEntry>> map;
private ListMultimap<Long, LogEntry> facade;
private final TreeSet<String> keys = Sets.newTreeSet();
private final TreeSet<String> sources = Sets.newTreeSet();
private final int maxSize;
private final AtomicLong counter = new AtomicLong();
public Data() {
this(DEFAULT_MAX_SIZE, false);
}
public Data(int maxSize, boolean loadDummyData) {
this.maxSize = maxSize;
map = Maps.newTreeMap();
facade = Multimaps.newListMultimap(map, new Supplier<List<LogEntry>>() {
@Override
public List<LogEntry> get() {
return Lists.newArrayList();
}
});
if (loadDummyData)
for (int i = 0; i < 10000; i++)
add(createRandomLogEntry(i));
}
private static LogEntry createRandomLogEntry(int i) {
Map<String, String> map = Maps.newHashMap();
String sp1 = Math.random() * 100 + "";
map.put("specialNumber", sp1);
String sp2 = Math.random() * 50 + "";
map.put("specialNumber2", sp2);
boolean processing = Math.random() > 0.5;
map.put("processing", processing + "");
map.put(Field.MSG, "processing=" + processing + ",specialNumber=" + sp1
+ ",specialNumber2=" + sp2);
return new LogEntry(System.currentTimeMillis()
- TimeUnit.MINUTES.toMillis(i), map);
}
/**
* Adds a {@link LogEntry} to the data.
*
* @param entry
* @return this
*/
public synchronized Data add(LogEntry entry) {
facade.put(entry.getTime(), entry);
for (Entry<String, String> pair : entry.getProperties().entrySet())
if (isNumeric(pair.getValue()))
keys.add(pair.getKey());
if (facade.size() % 10000 == 0 && facade.size() < maxSize)
log.info("data size=" + facade.size());
if (facade.size() > maxSize)
facade.removeAll(map.firstKey());
String source = entry.getSource();
if (source != null)
sources.add(source);
incrementCounter();
return this;
}
private boolean isNumeric(String s) {
try {
Double.parseDouble(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public synchronized Iterable<LogEntry> find(final long startTime,
final long finishTime) {
return new Iterable<LogEntry>() {
@Override
public Iterator<LogEntry> iterator() {
return createIterator(startTime, finishTime);
}
};
}
private synchronized Iterator<LogEntry> createIterator(
final long startTime, final long finishTime) {
return new Iterator<LogEntry>() {
Long t = map.ceilingKey(startTime);
Long last = map.floorKey(finishTime);
Iterator<LogEntry> it = null;
@Override
public boolean hasNext() {
if (it == null || !it.hasNext())
return last != null && t != null && t <= last;
else
return it.hasNext();
}
@Override
public LogEntry next() {
while (it == null || !it.hasNext()) {
it = map.get(t).iterator();
t = map.higherKey(t);
}
return it.next();
}
@Override
public void remove() {
throw new RuntimeException("not implemented");
}
};
}
public synchronized Buckets execute(final BucketQuery query) {
Iterable<LogEntry> entries = find(query.getStartTime().getTime(),
query.getFinishTime());
Iterable<LogEntry> filtered = entries;
// filter by field
if (query.getField().isPresent()) {
filtered = Iterables.filter(filtered, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String value = entry.getProperties().get(
query.getField().get());
return value != null;
}
});
}
// filter by source
if (query.getSource().isPresent())
- filtered = Iterables.filter(entries, new Predicate<LogEntry>() {
+ filtered = Iterables.filter(filtered, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String src = entry.getProperties().get(Field.SOURCE);
return query.getSource().get().equals(src);
}
});
// filter by text
if (query.getText().isPresent())
- filtered = Iterables.filter(entries, new Predicate<LogEntry>() {
+ filtered = Iterables.filter(filtered, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String searchFor = query.getText().get();
return contains(entry, Field.MSG, searchFor)
|| contains(entry, Field.LEVEL, searchFor)
|| contains(entry, Field.METHOD, searchFor)
|| contains(entry, Field.SOURCE, searchFor)
|| contains(entry, Field.THREAD_NAME, searchFor);
}
});
Buckets buckets = new Buckets(query);
for (LogEntry entry : filtered) {
if (query.getField().isPresent()) {
String s = entry.getProperties().get(query.getField().get());
try {
double d = Double.parseDouble(s);
buckets.add(entry.getTime(), d);
} catch (NumberFormatException e) {
// ignored value because non-numeric
}
} else
// just count the entries
buckets.add(entry.getTime(), 1);
}
return buckets;
}
private static boolean contains(LogEntry entry, String field,
String searchFor) {
String s = entry.getProperties().get(field);
if (s == null)
return false;
else
return s.contains(searchFor);
}
public synchronized long getNumEntries() {
return facade.size();
}
public synchronized long getNumEntriesAdded() {
return counter.get();
}
public NavigableSet<String> getKeys() {
return keys;
}
public Iterable<String> getLogs(long startTime, long finishTime) {
return Iterables.transform(find(startTime, finishTime),
new Function<LogEntry, String>() {
@Override
public String apply(LogEntry entry) {
StringBuilder s = new StringBuilder();
DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
s.append(df.format(new Date(entry.getTime())));
s.append(' ');
s.append(entry.getProperties().get(Field.LEVEL));
s.append(' ');
s.append(entry.getProperties().get(Field.LOGGER));
s.append(" - ");
s.append(entry.getProperties().get(Field.MSG));
return s.toString();
}
});
}
public NavigableSet<String> getSources() {
return sources;
}
public Date oldestTime() {
if (map.size() == 0)
return null;
else
return new Date(map.firstKey());
}
private synchronized void incrementCounter() {
if (counter.incrementAndGet() % 1000 == 0)
log.info(counter + " log lines processed");
}
}
| false | true | public synchronized Buckets execute(final BucketQuery query) {
Iterable<LogEntry> entries = find(query.getStartTime().getTime(),
query.getFinishTime());
Iterable<LogEntry> filtered = entries;
// filter by field
if (query.getField().isPresent()) {
filtered = Iterables.filter(filtered, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String value = entry.getProperties().get(
query.getField().get());
return value != null;
}
});
}
// filter by source
if (query.getSource().isPresent())
filtered = Iterables.filter(entries, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String src = entry.getProperties().get(Field.SOURCE);
return query.getSource().get().equals(src);
}
});
// filter by text
if (query.getText().isPresent())
filtered = Iterables.filter(entries, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String searchFor = query.getText().get();
return contains(entry, Field.MSG, searchFor)
|| contains(entry, Field.LEVEL, searchFor)
|| contains(entry, Field.METHOD, searchFor)
|| contains(entry, Field.SOURCE, searchFor)
|| contains(entry, Field.THREAD_NAME, searchFor);
}
});
Buckets buckets = new Buckets(query);
for (LogEntry entry : filtered) {
if (query.getField().isPresent()) {
String s = entry.getProperties().get(query.getField().get());
try {
double d = Double.parseDouble(s);
buckets.add(entry.getTime(), d);
} catch (NumberFormatException e) {
// ignored value because non-numeric
}
} else
// just count the entries
buckets.add(entry.getTime(), 1);
}
return buckets;
}
| public synchronized Buckets execute(final BucketQuery query) {
Iterable<LogEntry> entries = find(query.getStartTime().getTime(),
query.getFinishTime());
Iterable<LogEntry> filtered = entries;
// filter by field
if (query.getField().isPresent()) {
filtered = Iterables.filter(filtered, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String value = entry.getProperties().get(
query.getField().get());
return value != null;
}
});
}
// filter by source
if (query.getSource().isPresent())
filtered = Iterables.filter(filtered, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String src = entry.getProperties().get(Field.SOURCE);
return query.getSource().get().equals(src);
}
});
// filter by text
if (query.getText().isPresent())
filtered = Iterables.filter(filtered, new Predicate<LogEntry>() {
@Override
public boolean apply(LogEntry entry) {
String searchFor = query.getText().get();
return contains(entry, Field.MSG, searchFor)
|| contains(entry, Field.LEVEL, searchFor)
|| contains(entry, Field.METHOD, searchFor)
|| contains(entry, Field.SOURCE, searchFor)
|| contains(entry, Field.THREAD_NAME, searchFor);
}
});
Buckets buckets = new Buckets(query);
for (LogEntry entry : filtered) {
if (query.getField().isPresent()) {
String s = entry.getProperties().get(query.getField().get());
try {
double d = Double.parseDouble(s);
buckets.add(entry.getTime(), d);
} catch (NumberFormatException e) {
// ignored value because non-numeric
}
} else
// just count the entries
buckets.add(entry.getTime(), 1);
}
return buckets;
}
|
diff --git a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTeamServlet.java b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTeamServlet.java
index a3fe56d..d8ae9fd 100644
--- a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTeamServlet.java
+++ b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTeamServlet.java
@@ -1,65 +1,65 @@
package org.cvut.wa2.projectcontrol;
import java.io.IOException;
import java.util.ArrayList;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.cvut.wa2.projectcontrol.DAO.PMF;
import org.cvut.wa2.projectcontrol.entities.Team;
import org.cvut.wa2.projectcontrol.entities.TeamMember;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class CreateTeamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService service = UserServiceFactory.getUserService();
User user = service.getCurrentUser();
if (user != null) {
String teamName = req.getParameter("teamName");
RequestDispatcher disp = req.getRequestDispatcher("CreateTeam.jsp");
if (teamName.trim().equals("")) {
disp.forward(req, resp);
} else {
PersistenceManager manager = PMF.get().getPersistenceManager();
Team team = null;
try {
+ team = manager.getObjectById(Team.class, teamName);
disp.forward(req, resp);
} catch (JDOObjectNotFoundException e) {
- team = manager.getObjectById(Team.class, teamName);
Team newTeam = new Team();
newTeam.setTeamKey(KeyFactory.createKey(
Team.class.getSimpleName(), teamName));
newTeam.setName(teamName);
newTeam.setMembers(new ArrayList<TeamMember>());
manager.makePersistent(newTeam);
req.setAttribute("team", newTeam);
disp = req.getRequestDispatcher("EditTeam.jsp");
disp.forward(req, resp);
}
}
} else {
resp.sendRedirect("/projectcontrol");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
| false | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService service = UserServiceFactory.getUserService();
User user = service.getCurrentUser();
if (user != null) {
String teamName = req.getParameter("teamName");
RequestDispatcher disp = req.getRequestDispatcher("CreateTeam.jsp");
if (teamName.trim().equals("")) {
disp.forward(req, resp);
} else {
PersistenceManager manager = PMF.get().getPersistenceManager();
Team team = null;
try {
disp.forward(req, resp);
} catch (JDOObjectNotFoundException e) {
team = manager.getObjectById(Team.class, teamName);
Team newTeam = new Team();
newTeam.setTeamKey(KeyFactory.createKey(
Team.class.getSimpleName(), teamName));
newTeam.setName(teamName);
newTeam.setMembers(new ArrayList<TeamMember>());
manager.makePersistent(newTeam);
req.setAttribute("team", newTeam);
disp = req.getRequestDispatcher("EditTeam.jsp");
disp.forward(req, resp);
}
}
} else {
resp.sendRedirect("/projectcontrol");
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService service = UserServiceFactory.getUserService();
User user = service.getCurrentUser();
if (user != null) {
String teamName = req.getParameter("teamName");
RequestDispatcher disp = req.getRequestDispatcher("CreateTeam.jsp");
if (teamName.trim().equals("")) {
disp.forward(req, resp);
} else {
PersistenceManager manager = PMF.get().getPersistenceManager();
Team team = null;
try {
team = manager.getObjectById(Team.class, teamName);
disp.forward(req, resp);
} catch (JDOObjectNotFoundException e) {
Team newTeam = new Team();
newTeam.setTeamKey(KeyFactory.createKey(
Team.class.getSimpleName(), teamName));
newTeam.setName(teamName);
newTeam.setMembers(new ArrayList<TeamMember>());
manager.makePersistent(newTeam);
req.setAttribute("team", newTeam);
disp = req.getRequestDispatcher("EditTeam.jsp");
disp.forward(req, resp);
}
}
} else {
resp.sendRedirect("/projectcontrol");
}
}
|
diff --git a/core/src/main/java/hudson/tasks/Fingerprinter.java b/core/src/main/java/hudson/tasks/Fingerprinter.java
index a0e39740a..21ad016fa 100644
--- a/core/src/main/java/hudson/tasks/Fingerprinter.java
+++ b/core/src/main/java/hudson/tasks/Fingerprinter.java
@@ -1,295 +1,296 @@
package hudson.tasks;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.model.Action;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Fingerprint;
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Project;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.remoting.VirtualChannel;
import hudson.util.IOException2;
import hudson.util.FormFieldValidator;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Records fingerprints of the specified files.
*
* @author Kohsuke Kawaguchi
*/
public class Fingerprinter extends Publisher implements Serializable {
/**
* Comma-separated list of files/directories to be fingerprinted.
*/
private final String targets;
/**
* Also record all the finger prints of the build artifacts.
*/
private final boolean recordBuildArtifacts;
public Fingerprinter(String targets, boolean recordBuildArtifacts) {
this.targets = targets;
this.recordBuildArtifacts = recordBuildArtifacts;
}
public String getTargets() {
return targets;
}
public boolean getRecordBuildArtifacts() {
return recordBuildArtifacts;
}
public boolean perform(Build<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException {
try {
listener.getLogger().println("Recording fingerprints");
Map<String,String> record = new HashMap<String,String>();
if(targets.length()!=0)
record(build, listener, record, targets);
if(recordBuildArtifacts) {
ArtifactArchiver aa = (ArtifactArchiver) build.getProject().getPublishers().get(ArtifactArchiver.DESCRIPTOR);
if(aa==null) {
// configuration error
listener.error("Build artifacts are supposed to be fingerprinted, but build artifact archiving is not configured");
build.setResult(Result.FAILURE);
return true;
}
record(build, listener, record, aa.getArtifacts() );
}
build.getActions().add(new FingerprintAction(build,record));
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to record fingerprints"));
build.setResult(Result.FAILURE);
}
// failing to record fingerprints is an error but not fatal
return true;
}
private void record(Build<?,?> build, BuildListener listener, Map<String,String> record, final String targets) throws IOException, InterruptedException {
final class Record implements Serializable {
final boolean produced;
final String relativePath;
final String fileName;
final String md5sum;
public Record(boolean produced, String relativePath, String fileName, String md5sum) {
this.produced = produced;
this.relativePath = relativePath;
this.fileName = fileName;
this.md5sum = md5sum;
}
Fingerprint addRecord(Build build) throws IOException {
FingerprintMap map = Hudson.getInstance().getFingerprintMap();
return map.getOrCreate(produced?build:null, fileName, md5sum);
}
private static final long serialVersionUID = 1L;
}
Project p = build.getProject();
final long buildTimestamp = build.getTimestamp().getTimeInMillis();
FilePath ws = p.getWorkspace();
if(ws==null) {
listener.error("Unable to record fingerprints because there's no workspace");
build.setResult(Result.FAILURE);
return;
}
List<Record> records = ws.act(new FileCallable<List<Record>>() {
public List<Record> invoke(File baseDir, VirtualChannel channel) throws IOException {
List<Record> results = new ArrayList<Record>();
FileSet src = new FileSet();
src.setDir(baseDir);
src.setIncludes(targets);
DirectoryScanner ds = src.getDirectoryScanner(new org.apache.tools.ant.Project());
for( String f : ds.getIncludedFiles() ) {
File file = new File(baseDir,f);
// consider the file to be produced by this build only if the timestamp
// is newer than when the build has started.
- boolean produced = buildTimestamp <= file.lastModified();
+ // 2000ms is an error margin since since VFAT only retains timestamp at 2sec precision
+ boolean produced = buildTimestamp <= file.lastModified()+2000;
try {
results.add(new Record(produced,f,file.getName(),new FilePath(file).digest()));
} catch (IOException e) {
throw new IOException2("Failed to compute digest for "+file,e);
} catch (InterruptedException e) {
throw new IOException2("Aborted",e);
}
}
return results;
}
});
for (Record r : records) {
Fingerprint fp = r.addRecord(build);
if(fp==null) {
listener.error("failed to record fingerprint for "+r.relativePath);
continue;
}
fp.add(build);
record.put(r.relativePath,fp.getHashString());
}
}
public Descriptor<Publisher> getDescriptor() {
return DESCRIPTOR;
}
public static final Descriptor<Publisher> DESCRIPTOR = new DescriptorImpl();
public static class DescriptorImpl extends Descriptor<Publisher> {
public DescriptorImpl() {
super(Fingerprinter.class);
}
public String getDisplayName() {
return "Record fingerprints of files to track usage";
}
public String getHelpFile() {
return "/help/project-config/fingerprint.html";
}
/**
* Performs on-the-fly validation on the file mask wildcard.
*/
public void doCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator.WorkspaceFileMask(req,rsp).process();
}
public Publisher newInstance(StaplerRequest req) {
return new Fingerprinter(
req.getParameter("fingerprint_targets").trim(),
req.getParameter("fingerprint_artifacts")!=null);
}
}
/**
* Action for displaying fingerprints.
*/
public static final class FingerprintAction implements Action {
private final AbstractBuild build;
/**
* From file name to the digest.
*/
private final Map<String,String> record;
private transient WeakReference<Map<String,Fingerprint>> ref;
public FingerprintAction(AbstractBuild build, Map<String, String> record) {
this.build = build;
this.record = record;
}
public String getIconFileName() {
return "fingerprint.gif";
}
public String getDisplayName() {
return "See fingerprints";
}
public String getUrlName() {
return "fingerprints";
}
public AbstractBuild getBuild() {
return build;
}
/**
* Map from file names of the fingerprinted file to its fingerprint record.
*/
public synchronized Map<String,Fingerprint> getFingerprints() {
if(ref!=null) {
Map<String,Fingerprint> m = ref.get();
if(m!=null)
return m;
}
Hudson h = Hudson.getInstance();
Map<String,Fingerprint> m = new TreeMap<String,Fingerprint>();
for (Entry<String, String> r : record.entrySet()) {
try {
Fingerprint fp = h._getFingerprint(r.getValue());
if(fp!=null)
m.put(r.getKey(), fp);
} catch (IOException e) {
logger.log(Level.WARNING,e.getMessage(),e);
}
}
m = Collections.unmodifiableMap(m);
ref = new WeakReference<Map<String,Fingerprint>>(m);
return m;
}
/**
* Gets the dependency to other builds in a map.
* Returns build numbers instead of {@link Build}, since log records may be gone.
*/
public Map<AbstractProject,Integer> getDependencies() {
Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
for (Fingerprint fp : getFingerprints().values()) {
BuildPtr bp = fp.getOriginal();
if(bp==null) continue; // outside Hudson
if(bp.is(build)) continue; // we are the owner
Integer existing = r.get(bp.getJob());
if(existing!=null && existing>bp.getNumber())
continue; // the record in the map is already up to date
r.put(bp.getJob(),bp.getNumber());
}
return r;
}
}
private static final Logger logger = Logger.getLogger(Fingerprinter.class.getName());
private static final long serialVersionUID = 1L;
}
| true | true | private void record(Build<?,?> build, BuildListener listener, Map<String,String> record, final String targets) throws IOException, InterruptedException {
final class Record implements Serializable {
final boolean produced;
final String relativePath;
final String fileName;
final String md5sum;
public Record(boolean produced, String relativePath, String fileName, String md5sum) {
this.produced = produced;
this.relativePath = relativePath;
this.fileName = fileName;
this.md5sum = md5sum;
}
Fingerprint addRecord(Build build) throws IOException {
FingerprintMap map = Hudson.getInstance().getFingerprintMap();
return map.getOrCreate(produced?build:null, fileName, md5sum);
}
private static final long serialVersionUID = 1L;
}
Project p = build.getProject();
final long buildTimestamp = build.getTimestamp().getTimeInMillis();
FilePath ws = p.getWorkspace();
if(ws==null) {
listener.error("Unable to record fingerprints because there's no workspace");
build.setResult(Result.FAILURE);
return;
}
List<Record> records = ws.act(new FileCallable<List<Record>>() {
public List<Record> invoke(File baseDir, VirtualChannel channel) throws IOException {
List<Record> results = new ArrayList<Record>();
FileSet src = new FileSet();
src.setDir(baseDir);
src.setIncludes(targets);
DirectoryScanner ds = src.getDirectoryScanner(new org.apache.tools.ant.Project());
for( String f : ds.getIncludedFiles() ) {
File file = new File(baseDir,f);
// consider the file to be produced by this build only if the timestamp
// is newer than when the build has started.
boolean produced = buildTimestamp <= file.lastModified();
try {
results.add(new Record(produced,f,file.getName(),new FilePath(file).digest()));
} catch (IOException e) {
throw new IOException2("Failed to compute digest for "+file,e);
} catch (InterruptedException e) {
throw new IOException2("Aborted",e);
}
}
return results;
}
});
for (Record r : records) {
Fingerprint fp = r.addRecord(build);
if(fp==null) {
listener.error("failed to record fingerprint for "+r.relativePath);
continue;
}
fp.add(build);
record.put(r.relativePath,fp.getHashString());
}
}
| private void record(Build<?,?> build, BuildListener listener, Map<String,String> record, final String targets) throws IOException, InterruptedException {
final class Record implements Serializable {
final boolean produced;
final String relativePath;
final String fileName;
final String md5sum;
public Record(boolean produced, String relativePath, String fileName, String md5sum) {
this.produced = produced;
this.relativePath = relativePath;
this.fileName = fileName;
this.md5sum = md5sum;
}
Fingerprint addRecord(Build build) throws IOException {
FingerprintMap map = Hudson.getInstance().getFingerprintMap();
return map.getOrCreate(produced?build:null, fileName, md5sum);
}
private static final long serialVersionUID = 1L;
}
Project p = build.getProject();
final long buildTimestamp = build.getTimestamp().getTimeInMillis();
FilePath ws = p.getWorkspace();
if(ws==null) {
listener.error("Unable to record fingerprints because there's no workspace");
build.setResult(Result.FAILURE);
return;
}
List<Record> records = ws.act(new FileCallable<List<Record>>() {
public List<Record> invoke(File baseDir, VirtualChannel channel) throws IOException {
List<Record> results = new ArrayList<Record>();
FileSet src = new FileSet();
src.setDir(baseDir);
src.setIncludes(targets);
DirectoryScanner ds = src.getDirectoryScanner(new org.apache.tools.ant.Project());
for( String f : ds.getIncludedFiles() ) {
File file = new File(baseDir,f);
// consider the file to be produced by this build only if the timestamp
// is newer than when the build has started.
// 2000ms is an error margin since since VFAT only retains timestamp at 2sec precision
boolean produced = buildTimestamp <= file.lastModified()+2000;
try {
results.add(new Record(produced,f,file.getName(),new FilePath(file).digest()));
} catch (IOException e) {
throw new IOException2("Failed to compute digest for "+file,e);
} catch (InterruptedException e) {
throw new IOException2("Aborted",e);
}
}
return results;
}
});
for (Record r : records) {
Fingerprint fp = r.addRecord(build);
if(fp==null) {
listener.error("failed to record fingerprint for "+r.relativePath);
continue;
}
fp.add(build);
record.put(r.relativePath,fp.getHashString());
}
}
|
diff --git a/cometd-javascript/common-test/src/test/java/org/cometd/javascript/CometDSubscribeWithPublishDeniedTest.java b/cometd-javascript/common-test/src/test/java/org/cometd/javascript/CometDSubscribeWithPublishDeniedTest.java
index 4a61644cb..0899ca581 100644
--- a/cometd-javascript/common-test/src/test/java/org/cometd/javascript/CometDSubscribeWithPublishDeniedTest.java
+++ b/cometd-javascript/common-test/src/test/java/org/cometd/javascript/CometDSubscribeWithPublishDeniedTest.java
@@ -1,89 +1,89 @@
/*
* Copyright (c) 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cometd.javascript;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.server.DefaultSecurityPolicy;
import org.junit.Assert;
import org.junit.Test;
public class CometDSubscribeWithPublishDeniedTest extends AbstractCometDTest
{
@Test
public void testSubscribeWithPublishDenied() throws Exception
{
bayeuxServer.setSecurityPolicy(new Policy());
defineClass(Latch.class);
evaluateScript("var subscribeLatch = new Latch(1);");
Latch subscribeLatch = get("subscribeLatch");
evaluateScript("var publishLatch = new Latch(1);");
Latch publishLatch = get("publishLatch");
evaluateScript("" +
"var subscribeFailed = false;" +
"var publishFailed = false;" +
"" +
"var channelName = '/foo';" +
"cometd.addListener('/meta/handshake', function(message)" +
"{" +
" cometd.subscribe(channelName, function(message) {});" +
"});" +
"" +
"cometd.addListener('/meta/subscribe', function(message)" +
"{" +
" if (!message.successful)" +
- " failed = true;" +
+ " subscribeFailed = true;" +
" subscribeLatch.countDown();" +
"});" +
"" +
"cometd.addListener('/meta/publish', function(message)" +
"{" +
" if (!message.successful)" +
" publishFailed = true;" +
" publishLatch.countDown();" +
"});" +
"" +
"cometd.init({ url: '" + cometdURL + "', logLevel: '" + getLogLevel() + "' });" +
"");
Assert.assertTrue(subscribeLatch.await(5000));
boolean subscribeFailed = (Boolean)get("subscribeFailed");
Assert.assertFalse(subscribeFailed);
evaluateScript("" +
"cometd.publish(channelName, {});" +
"");
Assert.assertTrue(publishLatch.await(5000));
boolean publishFailed = (Boolean)get("publishFailed");
// Denied by policy
Assert.assertTrue(publishFailed);
evaluateScript("cometd.disconnect(true);");
}
private class Policy extends DefaultSecurityPolicy
{
@Override
public boolean canPublish(BayeuxServer server, ServerSession session, ServerChannel channel, ServerMessage message)
{
return false;
}
}
}
| true | true | public void testSubscribeWithPublishDenied() throws Exception
{
bayeuxServer.setSecurityPolicy(new Policy());
defineClass(Latch.class);
evaluateScript("var subscribeLatch = new Latch(1);");
Latch subscribeLatch = get("subscribeLatch");
evaluateScript("var publishLatch = new Latch(1);");
Latch publishLatch = get("publishLatch");
evaluateScript("" +
"var subscribeFailed = false;" +
"var publishFailed = false;" +
"" +
"var channelName = '/foo';" +
"cometd.addListener('/meta/handshake', function(message)" +
"{" +
" cometd.subscribe(channelName, function(message) {});" +
"});" +
"" +
"cometd.addListener('/meta/subscribe', function(message)" +
"{" +
" if (!message.successful)" +
" failed = true;" +
" subscribeLatch.countDown();" +
"});" +
"" +
"cometd.addListener('/meta/publish', function(message)" +
"{" +
" if (!message.successful)" +
" publishFailed = true;" +
" publishLatch.countDown();" +
"});" +
"" +
"cometd.init({ url: '" + cometdURL + "', logLevel: '" + getLogLevel() + "' });" +
"");
Assert.assertTrue(subscribeLatch.await(5000));
boolean subscribeFailed = (Boolean)get("subscribeFailed");
Assert.assertFalse(subscribeFailed);
evaluateScript("" +
"cometd.publish(channelName, {});" +
"");
Assert.assertTrue(publishLatch.await(5000));
boolean publishFailed = (Boolean)get("publishFailed");
// Denied by policy
Assert.assertTrue(publishFailed);
evaluateScript("cometd.disconnect(true);");
}
| public void testSubscribeWithPublishDenied() throws Exception
{
bayeuxServer.setSecurityPolicy(new Policy());
defineClass(Latch.class);
evaluateScript("var subscribeLatch = new Latch(1);");
Latch subscribeLatch = get("subscribeLatch");
evaluateScript("var publishLatch = new Latch(1);");
Latch publishLatch = get("publishLatch");
evaluateScript("" +
"var subscribeFailed = false;" +
"var publishFailed = false;" +
"" +
"var channelName = '/foo';" +
"cometd.addListener('/meta/handshake', function(message)" +
"{" +
" cometd.subscribe(channelName, function(message) {});" +
"});" +
"" +
"cometd.addListener('/meta/subscribe', function(message)" +
"{" +
" if (!message.successful)" +
" subscribeFailed = true;" +
" subscribeLatch.countDown();" +
"});" +
"" +
"cometd.addListener('/meta/publish', function(message)" +
"{" +
" if (!message.successful)" +
" publishFailed = true;" +
" publishLatch.countDown();" +
"});" +
"" +
"cometd.init({ url: '" + cometdURL + "', logLevel: '" + getLogLevel() + "' });" +
"");
Assert.assertTrue(subscribeLatch.await(5000));
boolean subscribeFailed = (Boolean)get("subscribeFailed");
Assert.assertFalse(subscribeFailed);
evaluateScript("" +
"cometd.publish(channelName, {});" +
"");
Assert.assertTrue(publishLatch.await(5000));
boolean publishFailed = (Boolean)get("publishFailed");
// Denied by policy
Assert.assertTrue(publishFailed);
evaluateScript("cometd.disconnect(true);");
}
|
diff --git a/htroot/ConfigLanguage_p.java b/htroot/ConfigLanguage_p.java
index a975a444c..f9fa8b83d 100644
--- a/htroot/ConfigLanguage_p.java
+++ b/htroot/ConfigLanguage_p.java
@@ -1,163 +1,163 @@
//ConfigLanguage_p.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 Alexander Schier
//
//$LastChangedDate$
//$LastChangedRevision$
//$LastChangedBy$
//
//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
//You must compile this file with
//javac -classpath .:../Classes Blacklist_p.java
//if the shell's current path is HTROOT
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.util.FileUtils;
import de.anomic.data.WorkTables;
import de.anomic.data.translator;
import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import java.util.Collections;
import java.util.Map;
public class ConfigLanguage_p {
private final static String LANG_FILENAME_FILTER = "^.*\\.lng$";
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final serverObjects prop = new serverObjects();
final String langPath = env.getDataPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
//Fallback
//prop.put("currentlang", ""); //is done by Translationtemplate
prop.put("status", "0");//nothing
List<String> langFiles = FileUtils.getDirListing(langPath, LANG_FILENAME_FILTER);
if(langFiles == null){
return prop;
}
if (post != null){
String selectedLanguage = post.get("language");
// store this call as api call
- ((Switchboard) env).tables.recordAPICall(post, "ConfigLanguage.html", WorkTables.TABLE_API_TYPE_CONFIGURATION, "language settings: " + selectedLanguage);
+ ((Switchboard) env).tables.recordAPICall(post, "ConfigLanguage_p.html", WorkTables.TABLE_API_TYPE_CONFIGURATION, "language settings: " + selectedLanguage);
//change language
if(post.containsKey("use_button") && selectedLanguage != null){
/* Only change language if filename is contained in list of filesnames
* read from the language directory. This is very important to prevent
* directory traversal attacks!
*/
if (langFiles.contains(selectedLanguage) || selectedLanguage.startsWith("default")) {
translator.changeLang(env, langPath, selectedLanguage);
}
//delete language file
}else if(post.containsKey("delete")){
/* Only delete file if filename is contained in list of filesnames
* read from the language directory. This is very important to prevent
* directory traversal attacks!
*/
if (langFiles.contains(selectedLanguage)) {
final File langfile= new File(langPath, selectedLanguage);
FileUtils.deletedelete(langfile);
}
//load language file from URL
} else if (post.containsKey("url")){
final String url = post.get("url");
Iterator<String> it;
try{
final DigestURI u = new DigestURI(url, null);
it = FileUtils.strings(u.get(MultiProtocolURI.yacybotUserAgent, 10000));
}catch(final IOException e){
prop.put("status", "1");//unable to get url
prop.put("status_url", url);
return prop;
}
try{
final File langFile = new File(langPath, url.substring(url.lastIndexOf('/'), url.length()));
final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
while (it.hasNext()) {
bw.write(it.next() + "\n");
}
bw.close();
}catch(final IOException e){
prop.put("status", "2");//error saving the language file
return prop;
}
if(post.containsKey("use_lang") && (post.get("use_lang")).equals("on")){
translator.changeLang(env, langPath, url.substring(url.lastIndexOf('/'), url.length()));
}
}
}
//reread language files
langFiles = FileUtils.getDirListing(langPath, LANG_FILENAME_FILTER);
Collections.sort(langFiles);
final Map<String, String> langNames = translator.langMap(env);
String langKey, langName;
//virtual entry
prop.put("langlist_0_file", "default");
prop.put("langlist_0_name", ((langNames.get("default") == null) ? "default" : langNames.get("default")));
prop.put("langlist_0_selected", "selected=\"selected\"");
int count = 0;
for(final String langFile : langFiles){
//+1 because of the virtual entry "default" at top
langKey = langFile.substring(0, langFile.length() -4);
langName = langNames.get(langKey);
prop.put("langlist_" + (count + 1) + "_file", langFile);
prop.put("langlist_" + (count + 1) + "_name", ((langName == null) ? langKey : langName));
if(env.getConfig("locale.language", "default").equals(langKey)) {
prop.put("langlist_" + (count + 1) + "_selected", "selected=\"selected\"");
prop.put("langlist_0_selected", " "); // reset Default
} else {
prop.put("langlist_" + (count + 1) + "_selected", " ");
}
count++;
}
prop.put("langlist", (count + 1));
//is done by Translationtemplate
//langName = (String) langNames.get(env.getConfig("locale.language", "default"));
//prop.put("currentlang", ((langName == null) ? "default" : langName));
return prop;
}
}
| true | true | public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final serverObjects prop = new serverObjects();
final String langPath = env.getDataPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
//Fallback
//prop.put("currentlang", ""); //is done by Translationtemplate
prop.put("status", "0");//nothing
List<String> langFiles = FileUtils.getDirListing(langPath, LANG_FILENAME_FILTER);
if(langFiles == null){
return prop;
}
if (post != null){
String selectedLanguage = post.get("language");
// store this call as api call
((Switchboard) env).tables.recordAPICall(post, "ConfigLanguage.html", WorkTables.TABLE_API_TYPE_CONFIGURATION, "language settings: " + selectedLanguage);
//change language
if(post.containsKey("use_button") && selectedLanguage != null){
/* Only change language if filename is contained in list of filesnames
* read from the language directory. This is very important to prevent
* directory traversal attacks!
*/
if (langFiles.contains(selectedLanguage) || selectedLanguage.startsWith("default")) {
translator.changeLang(env, langPath, selectedLanguage);
}
//delete language file
}else if(post.containsKey("delete")){
/* Only delete file if filename is contained in list of filesnames
* read from the language directory. This is very important to prevent
* directory traversal attacks!
*/
if (langFiles.contains(selectedLanguage)) {
final File langfile= new File(langPath, selectedLanguage);
FileUtils.deletedelete(langfile);
}
//load language file from URL
} else if (post.containsKey("url")){
final String url = post.get("url");
Iterator<String> it;
try{
final DigestURI u = new DigestURI(url, null);
it = FileUtils.strings(u.get(MultiProtocolURI.yacybotUserAgent, 10000));
}catch(final IOException e){
prop.put("status", "1");//unable to get url
prop.put("status_url", url);
return prop;
}
try{
final File langFile = new File(langPath, url.substring(url.lastIndexOf('/'), url.length()));
final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
while (it.hasNext()) {
bw.write(it.next() + "\n");
}
bw.close();
}catch(final IOException e){
prop.put("status", "2");//error saving the language file
return prop;
}
if(post.containsKey("use_lang") && (post.get("use_lang")).equals("on")){
translator.changeLang(env, langPath, url.substring(url.lastIndexOf('/'), url.length()));
}
}
}
//reread language files
langFiles = FileUtils.getDirListing(langPath, LANG_FILENAME_FILTER);
Collections.sort(langFiles);
final Map<String, String> langNames = translator.langMap(env);
String langKey, langName;
//virtual entry
prop.put("langlist_0_file", "default");
prop.put("langlist_0_name", ((langNames.get("default") == null) ? "default" : langNames.get("default")));
prop.put("langlist_0_selected", "selected=\"selected\"");
int count = 0;
for(final String langFile : langFiles){
//+1 because of the virtual entry "default" at top
langKey = langFile.substring(0, langFile.length() -4);
langName = langNames.get(langKey);
prop.put("langlist_" + (count + 1) + "_file", langFile);
prop.put("langlist_" + (count + 1) + "_name", ((langName == null) ? langKey : langName));
if(env.getConfig("locale.language", "default").equals(langKey)) {
prop.put("langlist_" + (count + 1) + "_selected", "selected=\"selected\"");
prop.put("langlist_0_selected", " "); // reset Default
} else {
prop.put("langlist_" + (count + 1) + "_selected", " ");
}
count++;
}
prop.put("langlist", (count + 1));
//is done by Translationtemplate
//langName = (String) langNames.get(env.getConfig("locale.language", "default"));
//prop.put("currentlang", ((langName == null) ? "default" : langName));
return prop;
}
| public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final serverObjects prop = new serverObjects();
final String langPath = env.getDataPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
//Fallback
//prop.put("currentlang", ""); //is done by Translationtemplate
prop.put("status", "0");//nothing
List<String> langFiles = FileUtils.getDirListing(langPath, LANG_FILENAME_FILTER);
if(langFiles == null){
return prop;
}
if (post != null){
String selectedLanguage = post.get("language");
// store this call as api call
((Switchboard) env).tables.recordAPICall(post, "ConfigLanguage_p.html", WorkTables.TABLE_API_TYPE_CONFIGURATION, "language settings: " + selectedLanguage);
//change language
if(post.containsKey("use_button") && selectedLanguage != null){
/* Only change language if filename is contained in list of filesnames
* read from the language directory. This is very important to prevent
* directory traversal attacks!
*/
if (langFiles.contains(selectedLanguage) || selectedLanguage.startsWith("default")) {
translator.changeLang(env, langPath, selectedLanguage);
}
//delete language file
}else if(post.containsKey("delete")){
/* Only delete file if filename is contained in list of filesnames
* read from the language directory. This is very important to prevent
* directory traversal attacks!
*/
if (langFiles.contains(selectedLanguage)) {
final File langfile= new File(langPath, selectedLanguage);
FileUtils.deletedelete(langfile);
}
//load language file from URL
} else if (post.containsKey("url")){
final String url = post.get("url");
Iterator<String> it;
try{
final DigestURI u = new DigestURI(url, null);
it = FileUtils.strings(u.get(MultiProtocolURI.yacybotUserAgent, 10000));
}catch(final IOException e){
prop.put("status", "1");//unable to get url
prop.put("status_url", url);
return prop;
}
try{
final File langFile = new File(langPath, url.substring(url.lastIndexOf('/'), url.length()));
final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
while (it.hasNext()) {
bw.write(it.next() + "\n");
}
bw.close();
}catch(final IOException e){
prop.put("status", "2");//error saving the language file
return prop;
}
if(post.containsKey("use_lang") && (post.get("use_lang")).equals("on")){
translator.changeLang(env, langPath, url.substring(url.lastIndexOf('/'), url.length()));
}
}
}
//reread language files
langFiles = FileUtils.getDirListing(langPath, LANG_FILENAME_FILTER);
Collections.sort(langFiles);
final Map<String, String> langNames = translator.langMap(env);
String langKey, langName;
//virtual entry
prop.put("langlist_0_file", "default");
prop.put("langlist_0_name", ((langNames.get("default") == null) ? "default" : langNames.get("default")));
prop.put("langlist_0_selected", "selected=\"selected\"");
int count = 0;
for(final String langFile : langFiles){
//+1 because of the virtual entry "default" at top
langKey = langFile.substring(0, langFile.length() -4);
langName = langNames.get(langKey);
prop.put("langlist_" + (count + 1) + "_file", langFile);
prop.put("langlist_" + (count + 1) + "_name", ((langName == null) ? langKey : langName));
if(env.getConfig("locale.language", "default").equals(langKey)) {
prop.put("langlist_" + (count + 1) + "_selected", "selected=\"selected\"");
prop.put("langlist_0_selected", " "); // reset Default
} else {
prop.put("langlist_" + (count + 1) + "_selected", " ");
}
count++;
}
prop.put("langlist", (count + 1));
//is done by Translationtemplate
//langName = (String) langNames.get(env.getConfig("locale.language", "default"));
//prop.put("currentlang", ((langName == null) ? "default" : langName));
return prop;
}
|
diff --git a/web/src/main/java/de/betterform/agent/web/servlet/XFormsErrorServlet.java b/web/src/main/java/de/betterform/agent/web/servlet/XFormsErrorServlet.java
index 5166f4e9..33303a5d 100644
--- a/web/src/main/java/de/betterform/agent/web/servlet/XFormsErrorServlet.java
+++ b/web/src/main/java/de/betterform/agent/web/servlet/XFormsErrorServlet.java
@@ -1,132 +1,132 @@
package de.betterform.agent.web.servlet;
import de.betterform.xml.config.Config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
/**
* Created by IntelliJ IDEA.
* User: zwobit
* Date: 24.10.11
* Time: 14:37
* To change this template use File | Settings | File Templates.
*/
public class XFormsErrorServlet extends HttpServlet {
private static final Log LOGGER = LogFactory.getLog(XFormsErrorServlet.class);
private static final String HTMLHEAD ="" +
"<html>" +
"<head>" +
"<title>Error Page</title>" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"../../bfResources/styles/error.css\"/>" +
"</head>" +
"<body>" +
"<div class=\"errorContent\">" +
"<img src=\"../../bfResources/images/error.png\" width=\"24\" height=\"24\" alt=\"Error\" style=\"float:left;padding-right:5px;\"/>" +
"<div class=\"message1\">Oops, an error occured...<br/></div>";
private static final String HTMLFOOT ="" +
"</div>" +
"</body>" +
"</html>";
private String getHTML(HttpServletRequest request) {
StringBuffer html = new StringBuffer();
String msg = (String) request.getSession().getAttribute("betterform.exception.message");
String xpath ="unknown";
String cause= " ";
if (msg != null) {
int start = msg.indexOf("::");
if(start > 3){
xpath = msg.substring(start+2);
msg=msg.substring(0,start);
}
}
Exception ex = (Exception) request.getSession().getAttribute("betterform.exception");
if(ex != null && ex.getCause() != null && ex.getCause().getMessage() != null){
cause = ex.getCause().getMessage();
}
request.getSession().removeAttribute("betterform.exception");
request.getSession().removeAttribute("betterform.exception.message");
- html.append("<div class=\"message2\">");
+ html.append("<div class=\"message2\" id=\"msg\">");
html.append(msg);
html.append("</div>");
html.append("<div class=\"message3\"><strong>URL:</strong><br/>");
html.append(request.getSession().getAttribute("betterform.referer"));
html.append("</div>");
html.append("<div class=\"message3\"><strong>Element causing Exception:</strong><br/>");
html.append(xpath);
html.append("</div>");
html.append("<div class=\"message3\"><strong>Caused by:</strong><br/>");
html.append(cause);
html.append("</div>");
html.append("<form><input type=\"button\" value=\"Back\" onClick=\"history.back()\"/></form>");
try {
String mail = Config.getInstance().getProperty("admin.mail");
StringBuffer mailbody = new StringBuffer();
html.append("<div class=\"message3\">");
html.append("<a href=\"mailto:");
html.append(mail);
mailbody.append("?subject='XForms Problem at ");
mailbody.append(request.getSession().getAttribute("betterform.referer"));
mailbody.append("'");
mailbody.append("&Body='Message:\n");
mailbody.append(msg);
mailbody.append("\n\nElement causing Exception:\n");
mailbody.append(xpath);
mailbody.append("\n\nCaused by:\n");
mailbody.append(cause);
mailbody.append("'");
html.append(URLEncoder.encode(mailbody.toString(), "UTF-8"));
html.append("\">");
html.append("Report this problem...</a>");
html.append("</div>");
} catch (Exception e) {
LOGGER.debug(e);
}
LOGGER.error(html.toString());
return html.toString();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
new BufferedWriter(new OutputStreamWriter(response.getOutputStream())).write(getHTML(request));
response.getOutputStream().flush();
response.getOutputStream().close();
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.reset();
response.resetBuffer();
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println(HTMLHEAD);
writer.println(getHTML(request));
writer.println(HTMLFOOT);
writer.flush();
response.getOutputStream().close();
}
}
| true | true | private String getHTML(HttpServletRequest request) {
StringBuffer html = new StringBuffer();
String msg = (String) request.getSession().getAttribute("betterform.exception.message");
String xpath ="unknown";
String cause= " ";
if (msg != null) {
int start = msg.indexOf("::");
if(start > 3){
xpath = msg.substring(start+2);
msg=msg.substring(0,start);
}
}
Exception ex = (Exception) request.getSession().getAttribute("betterform.exception");
if(ex != null && ex.getCause() != null && ex.getCause().getMessage() != null){
cause = ex.getCause().getMessage();
}
request.getSession().removeAttribute("betterform.exception");
request.getSession().removeAttribute("betterform.exception.message");
html.append("<div class=\"message2\">");
html.append(msg);
html.append("</div>");
html.append("<div class=\"message3\"><strong>URL:</strong><br/>");
html.append(request.getSession().getAttribute("betterform.referer"));
html.append("</div>");
html.append("<div class=\"message3\"><strong>Element causing Exception:</strong><br/>");
html.append(xpath);
html.append("</div>");
html.append("<div class=\"message3\"><strong>Caused by:</strong><br/>");
html.append(cause);
html.append("</div>");
html.append("<form><input type=\"button\" value=\"Back\" onClick=\"history.back()\"/></form>");
try {
String mail = Config.getInstance().getProperty("admin.mail");
StringBuffer mailbody = new StringBuffer();
html.append("<div class=\"message3\">");
html.append("<a href=\"mailto:");
html.append(mail);
mailbody.append("?subject='XForms Problem at ");
mailbody.append(request.getSession().getAttribute("betterform.referer"));
mailbody.append("'");
mailbody.append("&Body='Message:\n");
mailbody.append(msg);
mailbody.append("\n\nElement causing Exception:\n");
mailbody.append(xpath);
mailbody.append("\n\nCaused by:\n");
mailbody.append(cause);
mailbody.append("'");
html.append(URLEncoder.encode(mailbody.toString(), "UTF-8"));
html.append("\">");
html.append("Report this problem...</a>");
html.append("</div>");
} catch (Exception e) {
LOGGER.debug(e);
}
LOGGER.error(html.toString());
return html.toString();
}
| private String getHTML(HttpServletRequest request) {
StringBuffer html = new StringBuffer();
String msg = (String) request.getSession().getAttribute("betterform.exception.message");
String xpath ="unknown";
String cause= " ";
if (msg != null) {
int start = msg.indexOf("::");
if(start > 3){
xpath = msg.substring(start+2);
msg=msg.substring(0,start);
}
}
Exception ex = (Exception) request.getSession().getAttribute("betterform.exception");
if(ex != null && ex.getCause() != null && ex.getCause().getMessage() != null){
cause = ex.getCause().getMessage();
}
request.getSession().removeAttribute("betterform.exception");
request.getSession().removeAttribute("betterform.exception.message");
html.append("<div class=\"message2\" id=\"msg\">");
html.append(msg);
html.append("</div>");
html.append("<div class=\"message3\"><strong>URL:</strong><br/>");
html.append(request.getSession().getAttribute("betterform.referer"));
html.append("</div>");
html.append("<div class=\"message3\"><strong>Element causing Exception:</strong><br/>");
html.append(xpath);
html.append("</div>");
html.append("<div class=\"message3\"><strong>Caused by:</strong><br/>");
html.append(cause);
html.append("</div>");
html.append("<form><input type=\"button\" value=\"Back\" onClick=\"history.back()\"/></form>");
try {
String mail = Config.getInstance().getProperty("admin.mail");
StringBuffer mailbody = new StringBuffer();
html.append("<div class=\"message3\">");
html.append("<a href=\"mailto:");
html.append(mail);
mailbody.append("?subject='XForms Problem at ");
mailbody.append(request.getSession().getAttribute("betterform.referer"));
mailbody.append("'");
mailbody.append("&Body='Message:\n");
mailbody.append(msg);
mailbody.append("\n\nElement causing Exception:\n");
mailbody.append(xpath);
mailbody.append("\n\nCaused by:\n");
mailbody.append(cause);
mailbody.append("'");
html.append(URLEncoder.encode(mailbody.toString(), "UTF-8"));
html.append("\">");
html.append("Report this problem...</a>");
html.append("</div>");
} catch (Exception e) {
LOGGER.debug(e);
}
LOGGER.error(html.toString());
return html.toString();
}
|
diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/BasicLocation.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/BasicLocation.java
index de4abff5..3994bc54 100644
--- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/BasicLocation.java
+++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/BasicLocation.java
@@ -1,137 +1,139 @@
/*******************************************************************************
* Copyright (c) 2004 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.core.runtime.adaptor;
import java.io.*;
import java.net.URL;
import java.nio.channels.FileLock;
import org.eclipse.osgi.service.datalocation.Location;
public class BasicLocation implements Location {
private boolean isReadOnly;
private URL location = null;
private Location parent;
private URL defaultValue;
private String property;
// locking related fields
private FileLock fileLock;
private FileOutputStream fileStream;
private File lockFile;
private static String LOCK_FILENAME = ".metadata/.lock";
public BasicLocation(String property, URL defaultValue, boolean isReadOnly) {
super();
this.property = property;
this.defaultValue = defaultValue;
this.isReadOnly = isReadOnly;
}
public boolean allowsDefault() {
return defaultValue != null;
}
public URL getDefault() {
return defaultValue;
}
public Location getParentLocation() {
return parent;
}
public URL getURL() {
if (location == null && defaultValue != null)
setURL(defaultValue);
return location;
}
public boolean isSet() {
return location != null;
}
public boolean isReadOnly() {
return isReadOnly;
}
/**
* @deprecated
*/
public void setURL(URL value) throws IllegalStateException {
setURL(value , false);
}
public synchronized boolean setURL(URL value, boolean lock) throws IllegalStateException {
if (location != null)
throw new IllegalStateException("Cannot change the location once it is set");
File file = null;
if (value.getProtocol().equalsIgnoreCase("file")) {
file = new File(value.getPath(), LOCK_FILENAME);
- boolean creation = file.mkdirs();
- if (! creation)
- return false;
+ file = file.getParentFile();
+ if (!file.exists()) {
+ if (!file.mkdirs())
+ return false;
+ }
}
if (lock) {
try {
if (!lock(file))
return false;
} catch (IOException e) {
return false;
}
}
lockFile = file;
location = value;
System.getProperties().put(property, location.toExternalForm());
return true;
}
public void setParent(Location value) {
parent = value;
}
public synchronized boolean lock() throws IOException {
if (!isSet())
return false;
return lock(lockFile);
}
private boolean lock(File lock) throws IOException {
if (lock == null)
return false;
fileStream = new FileOutputStream(lock, true);
fileLock = fileStream.getChannel().tryLock();
if (fileLock != null)
return true;
fileStream.close();
fileStream = null;
fileLock = null;
return false;
}
public void release() {
if (fileLock != null) {
try {
fileLock.release();
} catch (IOException e) {
//don't complain, we're making a best effort to clean up
}
fileLock = null;
}
if (fileStream != null) {
try {
fileStream.close();
} catch (IOException e) {
//don't complain, we're making a best effort to clean up
}
fileStream = null;
}
}
}
| true | true | public synchronized boolean setURL(URL value, boolean lock) throws IllegalStateException {
if (location != null)
throw new IllegalStateException("Cannot change the location once it is set");
File file = null;
if (value.getProtocol().equalsIgnoreCase("file")) {
file = new File(value.getPath(), LOCK_FILENAME);
boolean creation = file.mkdirs();
if (! creation)
return false;
}
if (lock) {
try {
if (!lock(file))
return false;
} catch (IOException e) {
return false;
}
}
lockFile = file;
location = value;
System.getProperties().put(property, location.toExternalForm());
return true;
}
| public synchronized boolean setURL(URL value, boolean lock) throws IllegalStateException {
if (location != null)
throw new IllegalStateException("Cannot change the location once it is set");
File file = null;
if (value.getProtocol().equalsIgnoreCase("file")) {
file = new File(value.getPath(), LOCK_FILENAME);
file = file.getParentFile();
if (!file.exists()) {
if (!file.mkdirs())
return false;
}
}
if (lock) {
try {
if (!lock(file))
return false;
} catch (IOException e) {
return false;
}
}
lockFile = file;
location = value;
System.getProperties().put(property, location.toExternalForm());
return true;
}
|
diff --git a/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java b/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java
index 04889531..2db8c94e 100644
--- a/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java
+++ b/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java
@@ -1,784 +1,784 @@
/*
Copyright (C) 2012 Haowen Ning
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 org.liberty.android.fantastischmemo.ui;
import java.util.EnumSet;
import java.util.List;
import javax.inject.Inject;
import org.amr.arabic.ArabicUtilities;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.liberty.android.fantastischmemo.AMActivity;
import org.liberty.android.fantastischmemo.AnyMemoDBOpenHelper;
import org.liberty.android.fantastischmemo.AnyMemoDBOpenHelperManager;
import org.liberty.android.fantastischmemo.R;
import org.liberty.android.fantastischmemo.dao.SettingDao;
import org.liberty.android.fantastischmemo.domain.Card;
import org.liberty.android.fantastischmemo.domain.Option;
import org.liberty.android.fantastischmemo.domain.Setting;
import org.liberty.android.fantastischmemo.service.AnyMemoService;
import org.liberty.android.fantastischmemo.utils.AMGUIUtility;
import org.liberty.android.fantastischmemo.utils.AMStringUtils;
import org.liberty.android.fantastischmemo.utils.AnyMemoExecutor;
import org.liberty.android.fantastischmemo.utils.CardTTSUtil;
import org.liberty.android.fantastischmemo.utils.CardTTSUtilFactory;
import org.xml.sax.XMLReader;
import roboguice.RoboGuice;
import roboguice.inject.ContextScope;
import roboguice.util.RoboAsyncTask;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
@SuppressWarnings("deprecation")
public abstract class QACardActivity extends AMActivity {
public static String EXTRA_DBPATH = "dbpath";
private String dbPath;
private String dbName;
private AnyMemoDBOpenHelper dbOpenHelper;
/* DAOs */
private SettingDao settingDao;
private Card currentCard;
private int animationInResId = 0;
private int animationOutResId = 0;
private Option option;
private Setting setting;
private InitTask initTask = null;
private WaitDbTask waitDbTask = null;
private boolean isAnswerShown = true;
private TextView smallTitleBar;
private CardTTSUtilFactory cardTTSUtilFactory;
private CardTTSUtil cardTTSUtil;
private GestureLibrary gestureLibrary;
private volatile boolean initFinished = false;
@Inject
public void setOption(Option option) {
this.option = option;
}
@Inject
public void setCardTTSUtilFactory(CardTTSUtilFactory cardTTSUtilFactory) {
this.cardTTSUtilFactory = cardTTSUtilFactory;
}
public CardTTSUtil getCardTTSUtil() {
return cardTTSUtil;
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
Bundle extras = getIntent().getExtras();
if (extras != null) {
dbPath = extras.getString(EXTRA_DBPATH);
}
dbOpenHelper = AnyMemoDBOpenHelperManager.getHelper(this, dbPath);
dbName = FilenameUtils.getName(dbPath);
dbPath = extras.getString(EXTRA_DBPATH);
setContentView(getContentView());
// Set teh default animation
animationInResId = R.anim.slide_left_in;
animationOutResId = R.anim.slide_left_out;
imageGetter = new CardImageGetter(this, dbPath);
// Load gestures
loadGestures();
initTask = new InitTask(this);
initTask.execute();
}
public int getContentView() {
return R.layout.qa_card_layout;
}
protected void setCurrentCard(Card card) {
currentCard = card;
}
protected Card getCurrentCard() {
return currentCard;
}
protected String getDbPath() {
return dbPath;
}
protected String getDbName() {
return dbName;
}
// Important class that display the card using fragment
// the showAnswer parameter is handled differently on single
// sided card and double sided card.
protected void displayCard(boolean showAnswer) {
// First prepare the text to display
String questionTypeface = setting.getQuestionFont();
String answerTypeface = setting.getAnswerFont();
boolean enableThirdPartyArabic = option.getEnableArabicEngine();
Setting.Align questionAlign = setting.getQuestionTextAlign();
Setting.Align answerAlign = setting.getAnswerTextAlign();
EnumSet<Setting.CardField> htmlDisplay = setting.getDisplayInHTMLEnum();
String itemQuestion = currentCard.getQuestion();
String itemAnswer = currentCard.getAnswer();
String itemCategory = currentCard.getCategory().getName();
String itemNote = currentCard.getNote();
if (enableThirdPartyArabic) {
itemQuestion = ArabicUtilities.reshape(itemQuestion);
itemAnswer = ArabicUtilities.reshape(itemAnswer);
itemCategory = ArabicUtilities.reshape(itemCategory);
itemNote = ArabicUtilities.reshape(itemNote);
}
// For question field (field1)
SpannableStringBuilder sq = new SpannableStringBuilder();
// For answer field (field2)
SpannableStringBuilder sa = new SpannableStringBuilder();
/* Show the field that is enabled in settings */
EnumSet<Setting.CardField> field1 = setting.getQuestionFieldEnum();
EnumSet<Setting.CardField> field2 = setting.getAnswerFieldEnum();
/* Iterate all fields */
for (Setting.CardField cf : Setting.CardField.values()) {
String str = "";
if (cf == Setting.CardField.QUESTION) {
str = itemQuestion;
} else if (cf == Setting.CardField.ANSWER) {
str = itemAnswer;
} else if (cf == Setting.CardField.NOTE) {
str = itemNote;
} else {
throw new AssertionError(
"This is a bug! New CardField enum has been added but the display field haven't been nupdated");
}
SpannableStringBuilder buffer = new SpannableStringBuilder();
/* Automatic check HTML */
if (AMStringUtils.isHTML(str) && (htmlDisplay.contains(cf))) {
if (setting.getHtmlLineBreakConversion() == true) {
String s = str.replace("\n", "<br />");
buffer.append(Html.fromHtml(s, imageGetter, tagHandler));
} else {
buffer.append(Html.fromHtml(str, imageGetter, tagHandler));
}
} else {
if (buffer.length() != 0) {
buffer.append("\n\n");
}
buffer.append(str);
}
if (field1.contains(cf)) {
if (sq.length() != 0) {
sq.append(Html.fromHtml("<br /><br />", imageGetter,
tagHandler));
}
sq.append(buffer);
}
if (field2.contains(cf)) {
if (sa.length() != 0) {
sa.append(Html.fromHtml("<br /><br />", imageGetter,
tagHandler));
}
sa.append(buffer);
}
}
String questionTypefaceValue = null;
String answerTypefaceValue = null;
/* Set the typeface of question and answer */
if (StringUtils.isNotEmpty(questionTypeface)) {
questionTypefaceValue = questionTypeface;
}
if (StringUtils.isNotEmpty(answerTypeface)) {
answerTypefaceValue = answerTypeface;
}
// Handle the QA ratio
LinearLayout questionLayout = (LinearLayout) findViewById(R.id.question);
LinearLayout answerLayout = (LinearLayout) findViewById(R.id.answer);
float qRatio = setting.getQaRatio();
if (qRatio > 99.0f) {
answerLayout.setVisibility(View.GONE);
questionLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
answerLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
} else if (qRatio < 1.0f) {
questionLayout.setVisibility(View.GONE);
questionLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
answerLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
} else {
float aRatio = 100.0f - qRatio;
qRatio /= 50.0;
aRatio /= 50.0;
questionLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, qRatio));
answerLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, aRatio));
}
// Double sided card has no animation and no horizontal line
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) {
if (showAnswer) {
findViewById(R.id.question).setVisibility(View.GONE);
findViewById(R.id.answer).setVisibility(View.VISIBLE);
// Also the buttons should match the color.
View buttonsView = findViewById(R.id.buttons_root);
if (buttonsView != null) {
buttonsView.setBackgroundColor(setting.getAnswerBackgroundColor());
}
} else {
findViewById(R.id.question).setVisibility(View.VISIBLE);
findViewById(R.id.answer).setVisibility(View.GONE);
// Also the buttons should match the color.
View buttonsView = findViewById(R.id.buttons_root);
if (buttonsView != null) {
buttonsView.setBackgroundColor(setting.getQuestionBackgroundColor());
}
}
findViewById(R.id.horizontal_line).setVisibility(View.GONE);
}
// Set the color of the horizontal line
View horizontalLine = findViewById(R.id.horizontal_line);
horizontalLine.setBackgroundColor(setting.getSeparatorColor());
// Finally we generate the fragments
CardFragment questionFragment = new CardFragment.Builder(sq)
.setTextAlignment(questionAlign)
.setTypefaceFromFile(questionTypefaceValue)
.setTextOnClickListener(onQuestionTextClickListener)
.setCardOnClickListener(onQuestionViewClickListener)
.setTextFontSize(setting.getQuestionFontSize())
.setTypefaceFromFile(setting.getQuestionFont())
.setTextColor(setting.getQuestionTextColor())
.setBackgroundColor(setting.getQuestionBackgroundColor())
.build();
CardFragment answerFragment = null;
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED
|| showAnswer) {
answerFragment = new CardFragment.Builder(sa)
.setTextAlignment(answerAlign)
.setTypefaceFromFile(answerTypefaceValue)
.setTextOnClickListener(onAnswerTextClickListener)
.setCardOnClickListener(onAnswerViewClickListener)
.setTextFontSize(setting.getAnswerFontSize())
.setTextColor(setting.getAnswerTextColor())
.setBackgroundColor(setting.getAnswerBackgroundColor())
.setTypefaceFromFile(setting.getAnswerFont())
.build();
} else {
// For "Show answer" text, we do not use the
// alignment from the settings.
// It is always center aligned
answerFragment = new CardFragment.Builder(
getString(R.string.memo_show_answer))
.setTextAlignment(Setting.Align.CENTER)
.setTypefaceFromFile(answerTypefaceValue)
.setTextOnClickListener(onAnswerTextClickListener)
.setCardOnClickListener(onAnswerViewClickListener)
.setTextFontSize(setting.getAnswerFontSize())
.setTextColor(setting.getAnswerTextColor())
.setBackgroundColor(setting.getAnswerBackgroundColor())
.setTypefaceFromFile(setting.getAnswerFont())
.build();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED
&& option.getEnableAnimation()) {
if (isAnswerShown == false && showAnswer == true) {
// No animation here.
} else {
ft.setCustomAnimations(animationInResId, animationOutResId);
}
}
ft.replace(R.id.question, questionFragment);
ft.commit();
ft = getSupportFragmentManager().beginTransaction();
if (option.getEnableAnimation()) {
if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED) {
if (isAnswerShown == false && showAnswer == true) {
ft.setCustomAnimations(0, R.anim.slide_down);
} else {
ft.setCustomAnimations(animationInResId, animationOutResId);
}
} else {
// Animation for double sided cards
// Current no animation
}
}
ft.replace(R.id.answer, answerFragment);
ft.commit();
isAnswerShown = showAnswer;
// Set up the small title bar
// It is defualt "GONE" so it won't take any space
// if there is no text
smallTitleBar = (TextView) findViewById(R.id.small_title_bar);
// Copy the question to clickboard.
if (option.getCopyClipboard()) {
ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
// Some Samsung device doesn't have ClipboardManager. So check
// the null here to prevent crash.
- if (cm != null) {
+ if (cm != null && currentCard != null) {
cm.setText(currentCard.getQuestion());
}
}
onPostDisplayCard();
}
protected boolean isAnswerShown() {
return isAnswerShown;
}
protected AnyMemoDBOpenHelper getDbOpenHelper() {
return dbOpenHelper;
}
protected Setting getSetting() {
return setting;
}
protected Option getOption() {
return option;
}
// Call when initializing thing
abstract protected void onInit() throws Exception;
// Called when the initalizing finished.
protected void onPostInit() {
// Do nothing
}
// Set the card animation, 0 = no animation
protected void setAnimation(int animationInResId, int animationOutResId) {
this.animationInResId = animationInResId;
this.animationOutResId = animationOutResId;
}
private class InitTask extends RoboAsyncTask<Void> {
private ProgressDialog progressDialog;
private Context context;
public InitTask(Context context) {
super(context);
this.context = context;
}
@Override
public void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setTitle(getString(R.string.loading_please_wait));
progressDialog.setMessage(getString(R.string.loading_database));
progressDialog.setCancelable(false);
progressDialog.show();
// Get the context scope in UI thread (Who hold the ThreadLocal context scope
}
@Override
public Void call() throws Exception {
settingDao = dbOpenHelper.getSettingDao();
setting = settingDao.queryForId(1);
ContextScope scope = RoboGuice.getInjector(context).getInstance(ContextScope.class);
// Make sure the method is running under the context
// The AsyncTask thread does not have the context, so we need
// to manually enter the scope.
synchronized(ContextScope.class) {
scope.enter(context);
try {
cardTTSUtil = cardTTSUtilFactory.create(dbPath);
// Init of common functions here
// Call customized init funciton defined in
// the subclass
onInit();
} finally {
scope.exit(context);
}
}
return null;
}
@Override
public void onSuccess(Void result) {
// Make sure the background color of grade buttons matches the answer's backgroud color.
// buttonsView can be null if the layout does not have buttons_root
View buttonsView = findViewById(R.id.buttons_root);
if (buttonsView != null) {
buttonsView.setBackgroundColor(setting.getAnswerBackgroundColor());
}
// Call customized method when init completed
onPostInit();
}
@Override
public void onException(Exception e) throws RuntimeException {
AMGUIUtility.displayError(QACardActivity.this,
getString(R.string.exception_text),
getString(R.string.exception_message), e);
}
@Override
public void onFinally() {
progressDialog.dismiss();
initFinished = true;
}
}
@Override
public void onResume() {
super.onResume();
// Only if the initTask has been finished and no waitDbTask is waiting.
if (initFinished && (waitDbTask == null || !AsyncTask.Status.RUNNING
.equals(waitDbTask.getStatus()))) {
waitDbTask = new WaitDbTask();
waitDbTask.execute((Void) null);
} else {
Log.i(TAG, "There is another task running. Do not run tasks");
}
}
@Override
public void onDestroy() {
super.onDestroy();
AnyMemoDBOpenHelperManager.releaseHelper(dbOpenHelper);
cardTTSUtil.release();
/* Update the widget because StudyActivity can be accessed though widget*/
Intent myIntent = new Intent(this, AnyMemoService.class);
myIntent.putExtra("request_code", AnyMemoService.CANCEL_NOTIFICATION
| AnyMemoService.UPDATE_WIDGET);
startService(myIntent);
}
// Set the small title to display additional informaiton
public void setSmallTitle(CharSequence text) {
if (StringUtils.isNotEmpty(text)) {
smallTitleBar.setText(text);
smallTitleBar.setVisibility(View.VISIBLE);
} else {
smallTitleBar.setVisibility(View.GONE);
}
}
/*
* Use AsyncTask to make sure there is no running task for a db
*/
private class WaitDbTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
@Override
public void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(QACardActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setTitle(getString(R.string.loading_please_wait));
progressDialog.setMessage(getString(R.string.loading_save));
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
public Void doInBackground(Void... nothing) {
AnyMemoExecutor.waitAllTasks();
return null;
}
@Override
public void onCancelled() {
return;
}
@Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
/* Called when the card is displayed. */
protected void onPostDisplayCard() {
// Nothing
}
private ImageGetter imageGetter;
protected boolean speakQuestion() {
cardTTSUtil.speakCardQuestion(getCurrentCard());
return true;
}
protected boolean speakAnswer() {
cardTTSUtil.speakCardAnswer(getCurrentCard());
return true;
}
private void loadGestures() {
gestureLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!gestureLibrary.load()) {
Log.e(TAG, "Gestures can not be load");
}
GestureOverlayView gestureOverlay = (GestureOverlayView) findViewById(R.id.gesture_overlay);
gestureOverlay.addOnGesturePerformedListener(onGesturePerformedListener);
// Set if gestures are enabled if set on preference
gestureOverlay.setEnabled(option.getGestureEnabled());
}
private TagHandler tagHandler = new TagHandler() {
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
return;
}
};
// Default implementation is to handle the double sided card correctly.
// Return true if the event is handled, else return false
protected boolean onClickQuestionView() {
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) {
displayCard(true);
return true;
}
return false;
}
protected boolean onClickAnswerView() {
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) {
displayCard(false);
return true;
}
return false;
}
protected boolean onClickQuestionText() {
return onClickQuestionView();
}
protected boolean onClickAnswerText() {
return onClickAnswerView();
}
protected void onGestureDetected(GestureName gestureName) {
// Nothing
}
// Return true if handled. Default not handle it.
// This method will only be called if the volume key shortcut option is enabled.
protected boolean onVolumeUpKeyPressed() {
return false;
}
// Return true if handled. Default not handle it.
protected boolean onVolumeDownKeyPressed() {
return false;
}
// Do not handle the key down event. We handle it in onKeyUp
// This method will only be called if the volume key shortcut option is enabled.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (option.getVolumeKeyShortcut()) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
return true;
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
return true;
}
}
return super.onKeyDown(keyCode, event);
}
// handle the key event
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if(option.getVolumeKeyShortcut()) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
return onVolumeUpKeyPressed();
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
return onVolumeDownKeyPressed();
}
}
return super.onKeyUp(keyCode, event);
}
private CardFragment.OnClickListener onQuestionTextClickListener = new CardFragment.OnClickListener() {
@Override
public void onClick(View v) {
onClickQuestionText();
}
};
private CardFragment.OnClickListener onAnswerTextClickListener = new CardFragment.OnClickListener() {
@Override
public void onClick(View v) {
onClickAnswerText();
}
};
private CardFragment.OnClickListener onQuestionViewClickListener = new CardFragment.OnClickListener() {
@Override
public void onClick(View v) {
onClickQuestionView();
}
};
private CardFragment.OnClickListener onAnswerViewClickListener = new CardFragment.OnClickListener() {
@Override
public void onClick(View v) {
onClickAnswerView();
}
};
private GestureOverlayView.OnGesturePerformedListener onGesturePerformedListener = new GestureOverlayView.OnGesturePerformedListener() {
@Override
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
List<Prediction> predictions = gestureLibrary.recognize(gesture);
if (predictions.size() > 0 && predictions.get(0).score > 3.0) {
GestureName name = GestureName.parse(predictions.get(0).name);
// Run the callback on the Activity.
onGestureDetected(name);
}
}
};
// The gesture name for known gestures
public static enum GestureName {
LEFT_SWIPE("left-swipe"),
RIGHT_SWIPE("right-swipe"),
S_SHAPE("s-shape"),
O_SHAPE("o-shape");
private String gestureName;
private GestureName(String name) {
this.gestureName = name;
}
public String getName() {
return gestureName;
}
public static GestureName parse(String name) {
for (GestureName gn : GestureName.values()) {
if (name.equals(gn.getName())) {
return gn;
}
}
throw new IllegalArgumentException("The input gesture name is invalid");
}
}
}
| true | true | protected void displayCard(boolean showAnswer) {
// First prepare the text to display
String questionTypeface = setting.getQuestionFont();
String answerTypeface = setting.getAnswerFont();
boolean enableThirdPartyArabic = option.getEnableArabicEngine();
Setting.Align questionAlign = setting.getQuestionTextAlign();
Setting.Align answerAlign = setting.getAnswerTextAlign();
EnumSet<Setting.CardField> htmlDisplay = setting.getDisplayInHTMLEnum();
String itemQuestion = currentCard.getQuestion();
String itemAnswer = currentCard.getAnswer();
String itemCategory = currentCard.getCategory().getName();
String itemNote = currentCard.getNote();
if (enableThirdPartyArabic) {
itemQuestion = ArabicUtilities.reshape(itemQuestion);
itemAnswer = ArabicUtilities.reshape(itemAnswer);
itemCategory = ArabicUtilities.reshape(itemCategory);
itemNote = ArabicUtilities.reshape(itemNote);
}
// For question field (field1)
SpannableStringBuilder sq = new SpannableStringBuilder();
// For answer field (field2)
SpannableStringBuilder sa = new SpannableStringBuilder();
/* Show the field that is enabled in settings */
EnumSet<Setting.CardField> field1 = setting.getQuestionFieldEnum();
EnumSet<Setting.CardField> field2 = setting.getAnswerFieldEnum();
/* Iterate all fields */
for (Setting.CardField cf : Setting.CardField.values()) {
String str = "";
if (cf == Setting.CardField.QUESTION) {
str = itemQuestion;
} else if (cf == Setting.CardField.ANSWER) {
str = itemAnswer;
} else if (cf == Setting.CardField.NOTE) {
str = itemNote;
} else {
throw new AssertionError(
"This is a bug! New CardField enum has been added but the display field haven't been nupdated");
}
SpannableStringBuilder buffer = new SpannableStringBuilder();
/* Automatic check HTML */
if (AMStringUtils.isHTML(str) && (htmlDisplay.contains(cf))) {
if (setting.getHtmlLineBreakConversion() == true) {
String s = str.replace("\n", "<br />");
buffer.append(Html.fromHtml(s, imageGetter, tagHandler));
} else {
buffer.append(Html.fromHtml(str, imageGetter, tagHandler));
}
} else {
if (buffer.length() != 0) {
buffer.append("\n\n");
}
buffer.append(str);
}
if (field1.contains(cf)) {
if (sq.length() != 0) {
sq.append(Html.fromHtml("<br /><br />", imageGetter,
tagHandler));
}
sq.append(buffer);
}
if (field2.contains(cf)) {
if (sa.length() != 0) {
sa.append(Html.fromHtml("<br /><br />", imageGetter,
tagHandler));
}
sa.append(buffer);
}
}
String questionTypefaceValue = null;
String answerTypefaceValue = null;
/* Set the typeface of question and answer */
if (StringUtils.isNotEmpty(questionTypeface)) {
questionTypefaceValue = questionTypeface;
}
if (StringUtils.isNotEmpty(answerTypeface)) {
answerTypefaceValue = answerTypeface;
}
// Handle the QA ratio
LinearLayout questionLayout = (LinearLayout) findViewById(R.id.question);
LinearLayout answerLayout = (LinearLayout) findViewById(R.id.answer);
float qRatio = setting.getQaRatio();
if (qRatio > 99.0f) {
answerLayout.setVisibility(View.GONE);
questionLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
answerLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
} else if (qRatio < 1.0f) {
questionLayout.setVisibility(View.GONE);
questionLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
answerLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
} else {
float aRatio = 100.0f - qRatio;
qRatio /= 50.0;
aRatio /= 50.0;
questionLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, qRatio));
answerLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, aRatio));
}
// Double sided card has no animation and no horizontal line
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) {
if (showAnswer) {
findViewById(R.id.question).setVisibility(View.GONE);
findViewById(R.id.answer).setVisibility(View.VISIBLE);
// Also the buttons should match the color.
View buttonsView = findViewById(R.id.buttons_root);
if (buttonsView != null) {
buttonsView.setBackgroundColor(setting.getAnswerBackgroundColor());
}
} else {
findViewById(R.id.question).setVisibility(View.VISIBLE);
findViewById(R.id.answer).setVisibility(View.GONE);
// Also the buttons should match the color.
View buttonsView = findViewById(R.id.buttons_root);
if (buttonsView != null) {
buttonsView.setBackgroundColor(setting.getQuestionBackgroundColor());
}
}
findViewById(R.id.horizontal_line).setVisibility(View.GONE);
}
// Set the color of the horizontal line
View horizontalLine = findViewById(R.id.horizontal_line);
horizontalLine.setBackgroundColor(setting.getSeparatorColor());
// Finally we generate the fragments
CardFragment questionFragment = new CardFragment.Builder(sq)
.setTextAlignment(questionAlign)
.setTypefaceFromFile(questionTypefaceValue)
.setTextOnClickListener(onQuestionTextClickListener)
.setCardOnClickListener(onQuestionViewClickListener)
.setTextFontSize(setting.getQuestionFontSize())
.setTypefaceFromFile(setting.getQuestionFont())
.setTextColor(setting.getQuestionTextColor())
.setBackgroundColor(setting.getQuestionBackgroundColor())
.build();
CardFragment answerFragment = null;
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED
|| showAnswer) {
answerFragment = new CardFragment.Builder(sa)
.setTextAlignment(answerAlign)
.setTypefaceFromFile(answerTypefaceValue)
.setTextOnClickListener(onAnswerTextClickListener)
.setCardOnClickListener(onAnswerViewClickListener)
.setTextFontSize(setting.getAnswerFontSize())
.setTextColor(setting.getAnswerTextColor())
.setBackgroundColor(setting.getAnswerBackgroundColor())
.setTypefaceFromFile(setting.getAnswerFont())
.build();
} else {
// For "Show answer" text, we do not use the
// alignment from the settings.
// It is always center aligned
answerFragment = new CardFragment.Builder(
getString(R.string.memo_show_answer))
.setTextAlignment(Setting.Align.CENTER)
.setTypefaceFromFile(answerTypefaceValue)
.setTextOnClickListener(onAnswerTextClickListener)
.setCardOnClickListener(onAnswerViewClickListener)
.setTextFontSize(setting.getAnswerFontSize())
.setTextColor(setting.getAnswerTextColor())
.setBackgroundColor(setting.getAnswerBackgroundColor())
.setTypefaceFromFile(setting.getAnswerFont())
.build();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED
&& option.getEnableAnimation()) {
if (isAnswerShown == false && showAnswer == true) {
// No animation here.
} else {
ft.setCustomAnimations(animationInResId, animationOutResId);
}
}
ft.replace(R.id.question, questionFragment);
ft.commit();
ft = getSupportFragmentManager().beginTransaction();
if (option.getEnableAnimation()) {
if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED) {
if (isAnswerShown == false && showAnswer == true) {
ft.setCustomAnimations(0, R.anim.slide_down);
} else {
ft.setCustomAnimations(animationInResId, animationOutResId);
}
} else {
// Animation for double sided cards
// Current no animation
}
}
ft.replace(R.id.answer, answerFragment);
ft.commit();
isAnswerShown = showAnswer;
// Set up the small title bar
// It is defualt "GONE" so it won't take any space
// if there is no text
smallTitleBar = (TextView) findViewById(R.id.small_title_bar);
// Copy the question to clickboard.
if (option.getCopyClipboard()) {
ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
// Some Samsung device doesn't have ClipboardManager. So check
// the null here to prevent crash.
if (cm != null) {
cm.setText(currentCard.getQuestion());
}
}
onPostDisplayCard();
}
| protected void displayCard(boolean showAnswer) {
// First prepare the text to display
String questionTypeface = setting.getQuestionFont();
String answerTypeface = setting.getAnswerFont();
boolean enableThirdPartyArabic = option.getEnableArabicEngine();
Setting.Align questionAlign = setting.getQuestionTextAlign();
Setting.Align answerAlign = setting.getAnswerTextAlign();
EnumSet<Setting.CardField> htmlDisplay = setting.getDisplayInHTMLEnum();
String itemQuestion = currentCard.getQuestion();
String itemAnswer = currentCard.getAnswer();
String itemCategory = currentCard.getCategory().getName();
String itemNote = currentCard.getNote();
if (enableThirdPartyArabic) {
itemQuestion = ArabicUtilities.reshape(itemQuestion);
itemAnswer = ArabicUtilities.reshape(itemAnswer);
itemCategory = ArabicUtilities.reshape(itemCategory);
itemNote = ArabicUtilities.reshape(itemNote);
}
// For question field (field1)
SpannableStringBuilder sq = new SpannableStringBuilder();
// For answer field (field2)
SpannableStringBuilder sa = new SpannableStringBuilder();
/* Show the field that is enabled in settings */
EnumSet<Setting.CardField> field1 = setting.getQuestionFieldEnum();
EnumSet<Setting.CardField> field2 = setting.getAnswerFieldEnum();
/* Iterate all fields */
for (Setting.CardField cf : Setting.CardField.values()) {
String str = "";
if (cf == Setting.CardField.QUESTION) {
str = itemQuestion;
} else if (cf == Setting.CardField.ANSWER) {
str = itemAnswer;
} else if (cf == Setting.CardField.NOTE) {
str = itemNote;
} else {
throw new AssertionError(
"This is a bug! New CardField enum has been added but the display field haven't been nupdated");
}
SpannableStringBuilder buffer = new SpannableStringBuilder();
/* Automatic check HTML */
if (AMStringUtils.isHTML(str) && (htmlDisplay.contains(cf))) {
if (setting.getHtmlLineBreakConversion() == true) {
String s = str.replace("\n", "<br />");
buffer.append(Html.fromHtml(s, imageGetter, tagHandler));
} else {
buffer.append(Html.fromHtml(str, imageGetter, tagHandler));
}
} else {
if (buffer.length() != 0) {
buffer.append("\n\n");
}
buffer.append(str);
}
if (field1.contains(cf)) {
if (sq.length() != 0) {
sq.append(Html.fromHtml("<br /><br />", imageGetter,
tagHandler));
}
sq.append(buffer);
}
if (field2.contains(cf)) {
if (sa.length() != 0) {
sa.append(Html.fromHtml("<br /><br />", imageGetter,
tagHandler));
}
sa.append(buffer);
}
}
String questionTypefaceValue = null;
String answerTypefaceValue = null;
/* Set the typeface of question and answer */
if (StringUtils.isNotEmpty(questionTypeface)) {
questionTypefaceValue = questionTypeface;
}
if (StringUtils.isNotEmpty(answerTypeface)) {
answerTypefaceValue = answerTypeface;
}
// Handle the QA ratio
LinearLayout questionLayout = (LinearLayout) findViewById(R.id.question);
LinearLayout answerLayout = (LinearLayout) findViewById(R.id.answer);
float qRatio = setting.getQaRatio();
if (qRatio > 99.0f) {
answerLayout.setVisibility(View.GONE);
questionLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
answerLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
} else if (qRatio < 1.0f) {
questionLayout.setVisibility(View.GONE);
questionLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
answerLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
} else {
float aRatio = 100.0f - qRatio;
qRatio /= 50.0;
aRatio /= 50.0;
questionLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, qRatio));
answerLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, aRatio));
}
// Double sided card has no animation and no horizontal line
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) {
if (showAnswer) {
findViewById(R.id.question).setVisibility(View.GONE);
findViewById(R.id.answer).setVisibility(View.VISIBLE);
// Also the buttons should match the color.
View buttonsView = findViewById(R.id.buttons_root);
if (buttonsView != null) {
buttonsView.setBackgroundColor(setting.getAnswerBackgroundColor());
}
} else {
findViewById(R.id.question).setVisibility(View.VISIBLE);
findViewById(R.id.answer).setVisibility(View.GONE);
// Also the buttons should match the color.
View buttonsView = findViewById(R.id.buttons_root);
if (buttonsView != null) {
buttonsView.setBackgroundColor(setting.getQuestionBackgroundColor());
}
}
findViewById(R.id.horizontal_line).setVisibility(View.GONE);
}
// Set the color of the horizontal line
View horizontalLine = findViewById(R.id.horizontal_line);
horizontalLine.setBackgroundColor(setting.getSeparatorColor());
// Finally we generate the fragments
CardFragment questionFragment = new CardFragment.Builder(sq)
.setTextAlignment(questionAlign)
.setTypefaceFromFile(questionTypefaceValue)
.setTextOnClickListener(onQuestionTextClickListener)
.setCardOnClickListener(onQuestionViewClickListener)
.setTextFontSize(setting.getQuestionFontSize())
.setTypefaceFromFile(setting.getQuestionFont())
.setTextColor(setting.getQuestionTextColor())
.setBackgroundColor(setting.getQuestionBackgroundColor())
.build();
CardFragment answerFragment = null;
if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED
|| showAnswer) {
answerFragment = new CardFragment.Builder(sa)
.setTextAlignment(answerAlign)
.setTypefaceFromFile(answerTypefaceValue)
.setTextOnClickListener(onAnswerTextClickListener)
.setCardOnClickListener(onAnswerViewClickListener)
.setTextFontSize(setting.getAnswerFontSize())
.setTextColor(setting.getAnswerTextColor())
.setBackgroundColor(setting.getAnswerBackgroundColor())
.setTypefaceFromFile(setting.getAnswerFont())
.build();
} else {
// For "Show answer" text, we do not use the
// alignment from the settings.
// It is always center aligned
answerFragment = new CardFragment.Builder(
getString(R.string.memo_show_answer))
.setTextAlignment(Setting.Align.CENTER)
.setTypefaceFromFile(answerTypefaceValue)
.setTextOnClickListener(onAnswerTextClickListener)
.setCardOnClickListener(onAnswerViewClickListener)
.setTextFontSize(setting.getAnswerFontSize())
.setTextColor(setting.getAnswerTextColor())
.setBackgroundColor(setting.getAnswerBackgroundColor())
.setTypefaceFromFile(setting.getAnswerFont())
.build();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED
&& option.getEnableAnimation()) {
if (isAnswerShown == false && showAnswer == true) {
// No animation here.
} else {
ft.setCustomAnimations(animationInResId, animationOutResId);
}
}
ft.replace(R.id.question, questionFragment);
ft.commit();
ft = getSupportFragmentManager().beginTransaction();
if (option.getEnableAnimation()) {
if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED) {
if (isAnswerShown == false && showAnswer == true) {
ft.setCustomAnimations(0, R.anim.slide_down);
} else {
ft.setCustomAnimations(animationInResId, animationOutResId);
}
} else {
// Animation for double sided cards
// Current no animation
}
}
ft.replace(R.id.answer, answerFragment);
ft.commit();
isAnswerShown = showAnswer;
// Set up the small title bar
// It is defualt "GONE" so it won't take any space
// if there is no text
smallTitleBar = (TextView) findViewById(R.id.small_title_bar);
// Copy the question to clickboard.
if (option.getCopyClipboard()) {
ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
// Some Samsung device doesn't have ClipboardManager. So check
// the null here to prevent crash.
if (cm != null && currentCard != null) {
cm.setText(currentCard.getQuestion());
}
}
onPostDisplayCard();
}
|
diff --git a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPSemantics.java b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPSemantics.java
index 246c40a9f..d93b1fc0b 100644
--- a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPSemantics.java
+++ b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPSemantics.java
@@ -1,2280 +1,2274 @@
/**********************************************************************
* Copyright (c) 2004 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 - Initial API and implementation
**********************************************************************/
/*
* Created on Dec 8, 2004
*/
package org.eclipse.cdt.internal.core.dom.parser.cpp;
import org.eclipse.cdt.core.dom.ast.ASTNodeProperty;
import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IASTBinaryExpression;
import org.eclipse.cdt.core.dom.ast.IASTCastExpression;
import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarationStatement;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTExpressionList;
import org.eclipse.cdt.core.dom.ast.IASTFieldReference;
import org.eclipse.cdt.core.dom.ast.IASTForStatement;
import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTInitializerExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNamedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTReturnStatement;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IASTTypeId;
import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression;
import org.eclipse.cdt.core.dom.ast.IBasicType;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IEnumeration;
import org.eclipse.cdt.core.dom.ast.IEnumerator;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.dom.ast.IFunctionType;
import org.eclipse.cdt.core.dom.ast.IParameter;
import org.eclipse.cdt.core.dom.ast.IPointerType;
import org.eclipse.cdt.core.dom.ast.IProblemBinding;
import org.eclipse.cdt.core.dom.ast.IQualifierType;
import org.eclipse.cdt.core.dom.ast.IScope;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.ITypedef;
import org.eclipse.cdt.core.dom.ast.IVariable;
import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier.IASTEnumerator;
import org.eclipse.cdt.core.dom.ast.c.ICASTFieldDesignator;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTConstructorChainInitializer;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFieldReference;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTLinkageSpecification;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceAlias;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNewExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDeclaration;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDirective;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBasicType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPCompositeBinding;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPPointerToMemberType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPReferenceType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.core.parser.util.CharArrayObjectMap;
import org.eclipse.cdt.core.parser.util.CharArrayUtils;
import org.eclipse.cdt.core.parser.util.ObjectMap;
import org.eclipse.cdt.core.parser.util.ObjectSet;
import org.eclipse.cdt.core.parser.util.ArrayUtil.ArrayWrapper;
import org.eclipse.cdt.internal.core.dom.parser.ASTNode;
import org.eclipse.cdt.internal.core.dom.parser.ProblemBinding;
/**
* @author aniefer
*/
public class CPPSemantics {
public static final char[] EMPTY_NAME_ARRAY = new char[0];
public static final String EMPTY_NAME = ""; //$NON-NLS-1$
public static final char[] OPERATOR_ = new char[] {'o','p','e','r','a','t','o','r',' '}; //$NON-NLS-1$
public static final IType VOID_TYPE = new CPPBasicType( IBasicType.t_void, 0 );
static protected class LookupData
{
protected IASTName astName;
public char[] name;
public ObjectMap usingDirectives = ObjectMap.EMPTY_MAP;
public ObjectSet visited = ObjectSet.EMPTY_SET; //used to ensure we don't visit things more than once
public ObjectSet inheritanceChain; //used to detect circular inheritance
public ObjectSet associated = ObjectSet.EMPTY_SET;
public boolean ignoreUsingDirectives = false;
public boolean usingDirectivesOnly = false;
public boolean forceQualified = false;
public boolean forUserDefinedConversion = false;
public boolean forAssociatedScopes = false;
public boolean prefixLookup = false;
public Object foundItems = null;
public Object [] functionParameters;
public ProblemBinding problem;
public LookupData( IASTName n ){
astName = n;
this.name = n.toCharArray();
}
public LookupData( char [] n ){
astName = null;
this.name = n;
}
public boolean includeBlockItem( IASTNode item ){
if( ( astName != null && astName.getParent() instanceof IASTIdExpression ) ||
item instanceof IASTNamespaceDefinition ||
(item instanceof IASTSimpleDeclaration && ((IASTSimpleDeclaration)item).getDeclSpecifier() instanceof IASTCompositeTypeSpecifier ) )
{
return true;
}
return false;
}
public boolean typesOnly(){
if( astName == null ) return false;
IASTNode parent = astName.getParent();
if( parent instanceof ICPPASTBaseSpecifier || parent instanceof ICPPASTElaboratedTypeSpecifier ||
parent instanceof ICPPASTCompositeTypeSpecifier )
return true;
if( parent instanceof ICPPASTQualifiedName ){
IASTName [] ns = ((ICPPASTQualifiedName)parent).getNames();
return ( astName != ns[ ns.length -1 ] );
}
return false;
}
public boolean forUsingDeclaration(){
if( astName == null ) return false;
IASTNode p1 = astName.getParent();
if( p1 instanceof ICPPASTUsingDeclaration )
return true;
if( p1 instanceof ICPPASTQualifiedName ){
IASTNode p2 = p1.getParent();
if( p2 instanceof ICPPASTUsingDeclaration ){
IASTName [] ns = ((ICPPASTQualifiedName) p1 ).getNames();
return (ns[ ns.length - 1 ] == astName);
}
}
return false;
}
public boolean forDefinition(){
if( astName == null ) return false;
IASTNode p1 = astName.getParent();
IASTNode p2 = p1.getParent();
return ( ( p1 instanceof ICPPASTQualifiedName && p2 instanceof IASTDeclarator ) ||
( p1 instanceof IASTDeclarator && p2 instanceof IASTSimpleDeclaration) ||
( p1 instanceof IASTDeclarator && p2 instanceof IASTFunctionDefinition));
}
public boolean considerConstructors(){
if( astName == null ) return false;
IASTNode p1 = astName.getParent();
IASTNode p2 = p1.getParent();
if( p1 instanceof ICPPASTNamedTypeSpecifier && p2 instanceof IASTTypeId )
return p2.getParent() instanceof ICPPASTNewExpression;
else if( p1 instanceof ICPPASTQualifiedName && p2 instanceof ICPPASTFunctionDeclarator ){
IASTName[] names = ((ICPPASTQualifiedName)p1).getNames();
if( names.length >= 2 && names[ names.length - 1 ] == astName )
return CPPVisitor.isConstructor( names[ names.length - 2 ], (IASTDeclarator) p2 );
} else if( p1 instanceof ICPPASTQualifiedName && p2 instanceof ICPPASTNamedTypeSpecifier ){
IASTNode p3 = p2.getParent();
return p3 instanceof IASTTypeId && p3.getParent() instanceof ICPPASTNewExpression;
}
return false;
}
public boolean qualified(){
if( forceQualified ) return true;
if( astName == null ) return false;
IASTNode p1 = astName.getParent();
if( p1 instanceof ICPPASTQualifiedName ){
return ((ICPPASTQualifiedName)p1).getNames()[0] != astName;
}
return p1 instanceof ICPPASTFieldReference;
}
public boolean functionCall(){
if( astName == null ) return false;
IASTNode p1 = astName.getParent();
if( p1 instanceof ICPPASTQualifiedName )
p1 = p1.getParent();
return ( p1 instanceof IASTIdExpression && p1.getPropertyInParent() == IASTFunctionCallExpression.FUNCTION_NAME );
}
public boolean checkWholeClassScope() {
if( astName == null ) return false;
ASTNodeProperty prop = astName.getPropertyInParent();
if( prop == IASTIdExpression.ID_NAME ||
prop == IASTFieldReference.FIELD_NAME ||
prop == ICASTFieldDesignator.FIELD_NAME ||
prop == ICPPASTUsingDirective.QUALIFIED_NAME ||
prop == ICPPASTUsingDeclaration.NAME ||
prop == IASTFunctionCallExpression.FUNCTION_NAME ||
prop == ICPPASTUsingDeclaration.NAME ||
prop == IASTNamedTypeSpecifier.NAME )
{
return true;
}
return false;
}
public boolean hasResults(){
if( foundItems == null )
return false;
if( foundItems instanceof Object [] )
return ((Object[])foundItems).length != 0;
if( foundItems instanceof CharArrayObjectMap )
return ((CharArrayObjectMap)foundItems).size() != 0;
return false;
}
}
static protected class Cost
{
public Cost( IType s, IType t ){
source = s;
target = t;
}
public IType source;
public IType target;
public boolean targetHadReference = false;
public int lvalue;
public int promotion;
public int conversion;
public int qualification;
public int userDefined;
public int rank = -1;
public int detail;
//Some constants to help clarify things
public static final int AMBIGUOUS_USERDEFINED_CONVERSION = 1;
public static final int NO_MATCH_RANK = -1;
public static final int IDENTITY_RANK = 0;
public static final int LVALUE_OR_QUALIFICATION_RANK = 0;
public static final int PROMOTION_RANK = 1;
public static final int CONVERSION_RANK = 2;
public static final int DERIVED_TO_BASE_CONVERSION = 3;
public static final int USERDEFINED_CONVERSION_RANK = 4;
public static final int ELLIPSIS_CONVERSION = 5;
public int compare( Cost cost ) throws DOMException{
int result = 0;
if( rank != cost.rank ){
return cost.rank - rank;
}
if( userDefined != 0 || cost.userDefined != 0 ){
if( userDefined == 0 || cost.userDefined == 0 ){
return cost.userDefined - userDefined;
}
if( (userDefined == AMBIGUOUS_USERDEFINED_CONVERSION || cost.userDefined == AMBIGUOUS_USERDEFINED_CONVERSION) ||
(userDefined != cost.userDefined ) )
return 0;
// else they are the same constructor/conversion operator and are ranked
//on the standard conversion sequence
}
if( promotion > 0 || cost.promotion > 0 ){
result = cost.promotion - promotion;
}
if( conversion > 0 || cost.conversion > 0 ){
if( detail == cost.detail ){
result = cost.conversion - conversion;
} else {
result = cost.detail - detail;
}
}
if( result == 0 ){
if( cost.qualification != qualification ){
return cost.qualification - qualification;
} else if( (cost.qualification == qualification) && qualification == 0 ){
return 0;
} else {
IPointerType op1, op2;
IType t1 = cost.target, t2 = target;
int subOrSuper = 0;
while( true ){
op1 = null;
op2 = null;
while( true ){
if( t1 instanceof ITypedef )
try {
t1 = ((ITypedef)t1).getType();
} catch ( DOMException e ) {
t1 = e.getProblem();
}
else {
if( t1 instanceof IPointerType )
op1 = (IPointerType) t1;
break;
}
}
while( true ){
if( t2 instanceof ITypedef )
try {
t2 = ((ITypedef)t2).getType();
} catch ( DOMException e ) {
t2 = e.getProblem();
}
else {
if( t2 instanceof IPointerType )
op1 = (IPointerType) t2;
break;
}
}
if( op1 == null || op2 == null )
break;
int cmp = ( op1.isConst() ? 1 : 0 ) + ( op1.isVolatile() ? 1 : 0 ) -
( op2.isConst() ? 1 : 0 ) + ( op2.isVolatile() ? 1 : 0 );
if( subOrSuper == 0 )
subOrSuper = cmp;
else if( subOrSuper > 0 ^ cmp > 0) {
result = -1;
break;
}
}
if( result == -1 ){
result = 0;
} else {
if( op1 == op2 ){
result = subOrSuper;
} else {
result = op1 != null ? 1 : -1;
}
}
}
}
return result;
}
}
static protected IBinding resolveBinding( IASTName name ){
//1: get some context info off of the name to figure out what kind of lookup we want
LookupData data = createLookupData( name, true );
try {
//2: lookup
lookup( data, name );
} catch ( DOMException e1 ) {
data.problem = (ProblemBinding) e1.getProblem();
}
if( data.problem != null )
return data.problem;
//3: resolve ambiguities
IBinding binding;
try {
binding = resolveAmbiguities( data, name );
} catch ( DOMException e2 ) {
binding = e2.getProblem();
}
//4: post processing
binding = postResolution( binding, data );
return binding;
}
/**
* @param binding
* @param data
* @param name
* @return
*/
private static IBinding postResolution( IBinding binding, LookupData data ) {
if( !(data.astName instanceof ICPPASTQualifiedName) && data.functionCall() ){
//3.4.2 argument dependent name lookup, aka Koenig lookup
try {
IScope scope = (binding != null ) ? binding.getScope() : null;
if( data.associated.size() > 0 && ( scope == null|| !(scope instanceof ICPPClassScope) ) ){
Object [] assoc = new Object[ data.associated.size() ];
System.arraycopy( data.associated.keyArray(), 0, assoc, 0, assoc.length );
data.ignoreUsingDirectives = true;
data.forceQualified = true;
for( int i = 0; i < assoc.length; i++ ){
if( data.associated.containsKey( assoc[i] ) )
lookup( data, assoc[i] );
}
binding = resolveAmbiguities( data, data.astName );
}
} catch ( DOMException e ) {
binding = e.getProblem();
}
}
if( binding instanceof ICPPClassType && data.considerConstructors() ){
ICPPClassType cls = (ICPPClassType) binding;
try {
//force resolution of constructor bindings
cls.getConstructors();
//then use the class scope to resolve which one.
binding = ((ICPPClassScope)cls.getCompositeScope()).getBinding( data.astName );
} catch ( DOMException e ) {
binding = e.getProblem();
}
}
if( data.astName.getPropertyInParent() == IASTNamedTypeSpecifier.NAME && !( binding instanceof IType || binding instanceof ICPPConstructor) ){
binding = new ProblemBinding( IProblemBinding.SEMANTIC_INVALID_TYPE, data.name );
}
if( binding != null && !( binding instanceof IProblemBinding ) ){
if( data.forDefinition() ){
addDefinition( binding, data.astName );
} else if( data.forUsingDeclaration() ){
IASTNode node = CPPVisitor.getContainingBlockItem( data.astName );
ICPPScope scope = (ICPPScope) CPPVisitor.getContainingScope( node );
try {
if( binding instanceof ICPPCompositeBinding ){
IBinding [] bs = ((ICPPCompositeBinding)binding).getBindings();
for( int i = 0; i < bs.length; i++ ) {
scope.addBinding( bs[i] );
}
} else {
scope.addBinding( binding );
}
} catch ( DOMException e ) {
}
}
}
if( binding == null )
binding = new ProblemBinding(IProblemBinding.SEMANTIC_NAME_NOT_FOUND, data.name );
return binding;
}
static private CPPSemantics.LookupData createLookupData( IASTName name, boolean considerAssociatedScopes ){
CPPSemantics.LookupData data = new CPPSemantics.LookupData( name );
IASTNode parent = name.getParent();
if( parent instanceof ICPPASTQualifiedName ){
parent = parent.getParent();
}
if( parent instanceof ICPPASTFunctionDeclarator ){
data.functionParameters = ((ICPPASTFunctionDeclarator)parent).getParameters();
} else if( parent instanceof IASTIdExpression ){
parent = parent.getParent();
if( parent instanceof IASTFunctionCallExpression ){
IASTExpression exp = ((IASTFunctionCallExpression)parent).getParameterExpression();
if( exp instanceof IASTExpressionList )
data.functionParameters = ((IASTExpressionList) exp ).getExpressions();
else if( exp != null )
data.functionParameters = new IASTExpression [] { exp };
else
data.functionParameters = IASTExpression.EMPTY_EXPRESSION_ARRAY;
}
} else if( parent instanceof ICPPASTFieldReference && parent.getParent() instanceof IASTFunctionCallExpression ){
IASTExpression exp = ((IASTFunctionCallExpression)parent.getParent()).getParameterExpression();
if( exp instanceof IASTExpressionList )
data.functionParameters = ((IASTExpressionList) exp ).getExpressions();
else if( exp != null )
data.functionParameters = new IASTExpression [] { exp };
else
data.functionParameters = IASTExpression.EMPTY_EXPRESSION_ARRAY;
} else if( parent instanceof ICPPASTNamedTypeSpecifier && parent.getParent() instanceof IASTTypeId ){
IASTTypeId typeId = (IASTTypeId) parent.getParent();
if( typeId.getParent() instanceof ICPPASTNewExpression ){
ICPPASTNewExpression newExp = (ICPPASTNewExpression) typeId.getParent();
IASTExpression init = newExp.getNewInitializer();
if( init instanceof IASTExpressionList )
data.functionParameters = ((IASTExpressionList) init ).getExpressions();
else if( init != null )
data.functionParameters = new IASTExpression [] { init };
else
data.functionParameters = IASTExpression.EMPTY_EXPRESSION_ARRAY;
}
}
if( considerAssociatedScopes && !(name.getParent() instanceof ICPPASTQualifiedName) && data.functionCall() ){
data.associated = getAssociatedScopes( data );
}
return data;
}
static private ObjectSet getAssociatedScopes( LookupData data ) {
Object [] ps = data.functionParameters;
ObjectSet namespaces = new ObjectSet(2);
ObjectSet classes = new ObjectSet(2);
for( int i = 0; i < ps.length; i++ ){
IType p = getSourceParameterType( ps, i );
p = getUltimateType( p, true );
try {
getAssociatedScopes( p, namespaces, classes );
} catch ( DOMException e ) {
}
}
return namespaces;
}
static private void getAssociatedScopes( IType t, ObjectSet namespaces, ObjectSet classes ) throws DOMException{
//3.4.2-2
if( t instanceof ICPPClassType ){
if( !classes.containsKey( t ) ){
classes.put( t );
namespaces.put( getContainingNamespaceScope( (IBinding) t ) );
ICPPClassType cls = (ICPPClassType) t;
ICPPBase[] bases = cls.getBases();
for( int i = 0; i < bases.length; i++ ){
if( bases[i] instanceof IProblemBinding )
continue;
getAssociatedScopes( bases[i].getBaseClass(), namespaces, classes );
}
}
} else if( t instanceof IEnumeration ){
namespaces.put( getContainingNamespaceScope( (IBinding) t ) );
} else if( t instanceof IFunctionType ){
IFunctionType ft = (IFunctionType) t;
getAssociatedScopes( getUltimateType( ft.getReturnType(), true ), namespaces, classes );
IType [] ps = ft.getParameterTypes();
for( int i = 0; i < ps.length; i++ ){
getAssociatedScopes( getUltimateType( ps[i], true ), namespaces, classes );
}
} else if( t instanceof ICPPPointerToMemberType ){
IBinding binding = ((ICPPPointerToMemberType)t).getMemberOfClass();
if( binding instanceof IType )
getAssociatedScopes( (IType)binding, namespaces, classes );
getAssociatedScopes( getUltimateType( ((ICPPPointerToMemberType)t).getType(), true ), namespaces, classes );
}
return;
}
static private ICPPNamespaceScope getContainingNamespaceScope( IBinding binding ) throws DOMException{
if( binding == null ) return null;
IScope scope = binding.getScope();
while( scope != null && !(scope instanceof ICPPNamespaceScope) ){
scope = scope.getParent();
}
return (ICPPNamespaceScope) scope;
}
static private ICPPScope getLookupScope( IASTName name ) throws DOMException{
IASTNode parent = name.getParent();
if( parent instanceof ICPPASTBaseSpecifier ) {
IASTNode n = CPPVisitor.getContainingBlockItem( parent );
return (ICPPScope) CPPVisitor.getContainingScope( n );
} else if( parent instanceof ICPPASTConstructorChainInitializer ){
ICPPASTConstructorChainInitializer initializer = (ICPPASTConstructorChainInitializer) parent;
IASTFunctionDeclarator dtor = (IASTFunctionDeclarator) initializer.getParent();
return (ICPPScope) dtor.getName().resolveBinding().getScope();
}
return (ICPPScope) CPPVisitor.getContainingScope( name );
}
private static void mergeResults( LookupData data, Object results, boolean scoped ){
if( !data.prefixLookup ){
if( results instanceof IBinding ){
data.foundItems = ArrayUtil.append( Object.class, (Object[]) data.foundItems, results );
} else if( results instanceof Object[] ){
data.foundItems = ArrayUtil.addAll( Object.class, (Object[])data.foundItems, (Object[])results );
}
} else {
Object [] objs = (Object[]) results;
CharArrayObjectMap resultMap = (CharArrayObjectMap) data.foundItems;
if( objs != null ) {
for( int i = 0; i < objs.length && objs[i] != null; i++ ){
char [] n = null;
if( objs[i] instanceof IBinding )
n = ((IBinding)objs[i]).getNameCharArray();
else
n = ((IASTName)objs[i]).toCharArray();
if( !resultMap.containsKey( n ) ){
resultMap.put( n, objs[i] );
} else if( !scoped ) {
Object obj = resultMap.get( n );
if( obj instanceof Object [] ) {
if( objs[i] instanceof IBinding )
obj = ArrayUtil.append( Object.class, (Object[]) obj, objs[i] );
else
obj = ArrayUtil.addAll( Object.class, (Object[])obj, (Object[]) objs[i] );
} else {
if( objs[i] instanceof IBinding )
obj = new Object [] { obj, objs[i] };
else {
Object [] temp = new Object [ ((Object[])objs[i]).length + 1 ];
temp[0] = obj;
obj = ArrayUtil.addAll( Object.class, temp, (Object[]) objs[i] );
}
}
}
}
}
}
}
static private void lookup( CPPSemantics.LookupData data, Object start ) throws DOMException{
IASTNode node = data.astName;
ICPPScope scope = null;
if( start instanceof ICPPScope )
scope = (ICPPScope) start;
else
scope = getLookupScope( (IASTName) start );
while( scope != null ){
IASTNode blockItem = CPPVisitor.getContainingBlockItem( node );
if( scope.getPhysicalNode() != blockItem.getParent() && !(scope instanceof ICPPNamespaceScope) )
blockItem = node;
ArrayWrapper directives = null;
if( !data.usingDirectivesOnly ){
IBinding binding = data.prefixLookup ? null : scope.getBinding( data.astName );
if( binding == null ||
(scope instanceof ICPPNamespaceScope && !((ICPPNamespaceScope) scope).isFullyResolved( data.astName ) ) ||
!( CPPSemantics.declaredBefore( binding, data.astName ) ||
(scope instanceof ICPPClassScope && data.checkWholeClassScope()) ) )
{
directives = new ArrayWrapper();
mergeResults( data, lookupInScope( data, scope, blockItem, directives ), true );
} else {
mergeResults( data, binding, true );
}
}
if( !data.ignoreUsingDirectives ) {
data.visited.clear();
if( data.prefixLookup || !data.hasResults() ){
Object[] transitives = lookupInNominated( data, scope, null );
processDirectives( data, scope, transitives );
if( directives != null && directives.array != null && directives.array.length != 0 )
processDirectives( data, scope, directives.array );
while( !data.usingDirectives.isEmpty() && data.usingDirectives.get( scope ) != null ){
transitives = lookupInNominated( data, scope, transitives );
if( !data.qualified() || ( data.prefixLookup || !data.hasResults()) ){
processDirectives( data, scope, transitives );
}
}
}
}
if( !data.prefixLookup && (data.problem != null || data.hasResults()) )
return;
if( !data.usingDirectivesOnly && scope instanceof ICPPClassScope ){
mergeResults( data, lookupInParents( data, (ICPPClassScope) scope ), true );
}
if( !data.prefixLookup && (data.problem != null || data.hasResults()) )
return;
//if still not found, loop and check our containing scope
if( data.qualified() && !data.usingDirectives.isEmpty() )
data.usingDirectivesOnly = true;
if( blockItem != null )
node = blockItem;
scope = (ICPPScope) scope.getParent();
}
}
private static IASTName[] lookupInParents( CPPSemantics.LookupData data, ICPPClassScope lookIn ) throws DOMException{
ICPPASTCompositeTypeSpecifier compositeTypeSpec = (ICPPASTCompositeTypeSpecifier) lookIn.getPhysicalNode();
ICPPASTBaseSpecifier [] bases = compositeTypeSpec.getBaseSpecifiers();
IASTName[] inherited = null;
IASTName[] result = null;
if( bases.length == 0 )
return null;
//use data to detect circular inheritance
if( data.inheritanceChain == null )
data.inheritanceChain = new ObjectSet( 2 );
data.inheritanceChain.put( lookIn );
int size = bases.length;
for( int i = 0; i < size; i++ )
{
ICPPClassType cls = null;
IBinding binding = bases[i].getName().resolveBinding();
while( binding instanceof ITypedef && ((ITypedef)binding).getType() instanceof IBinding ){
binding = (IBinding) ((ITypedef)binding).getType();
}
if( binding instanceof ICPPClassType )
cls = (ICPPClassType) binding;
else
continue;
ICPPClassScope parent = (ICPPClassScope) cls.getCompositeScope();
if( parent == null )
continue;
if( !bases[i].isVirtual() || !data.visited.containsKey( parent ) ){
if( bases[i].isVirtual() ){
if( data.visited == ObjectSet.EMPTY_SET )
data.visited = new ObjectSet(2);
data.visited.put( parent );
}
//if the inheritanceChain already contains the parent, then that
//is circular inheritance
if( ! data.inheritanceChain.containsKey( parent ) ){
//is this name define in this scope?
inherited = lookupInScope( data, parent, null, null );
if( inherited == null || inherited.length == 0 ){
inherited = lookupInParents( data, parent );
}
} else {
data.problem = new ProblemBinding( IProblemBinding.SEMANTIC_CIRCULAR_INHERITANCE, bases[i].getName().toCharArray() );
return null;
}
}
if( inherited != null && inherited.length != 0 ){
if( result == null || result.length == 0 ){
result = inherited;
} else if ( inherited != null && inherited.length != 0 ) {
for( int j = 0; j < result.length && result[j] != null; j++ ) {
IASTName n = result[j];
if( checkAmbiguity( n, inherited ) ){
data.problem = new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, n.toCharArray() );
return null;
}
}
}
} else {
inherited = null; //reset temp for next iteration
}
}
data.inheritanceChain.remove( lookIn );
return result;
}
private static boolean checkAmbiguity( IASTName n, IASTName []names ) throws DOMException{
names = (IASTName[]) ArrayUtil.trim( IASTName.class, names );
if( names.length == 0 )
return false;
//it is not ambiguous if they are the same thing and it is static or an enumerator
IBinding binding = n.resolveBinding();
for( int i = 0; i < names.length && names[i] != null; i++ ){
IBinding b = names[i].resolveBinding();
if( binding != b )
return true;
if( binding instanceof IEnumerator )
continue;
else if( (binding instanceof IFunction && ((IFunction)binding).isStatic()) ||
(binding instanceof IVariable && ((IVariable)binding).isStatic()) )
continue;
return true;
}
return false;
}
static private void processDirectives( CPPSemantics.LookupData data, IScope scope, Object[] directives ) throws DOMException{
if( directives == null || directives.length == 0 )
return;
ICPPScope enclosing = null;
IScope temp = null;
int size = directives.length;
for( int i = 0; i < size && directives[i] != null; i++ ){
Object d = directives[i];
IBinding binding = null;
if( d instanceof ICPPASTUsingDirective ){
binding = ((ICPPASTUsingDirective)d).getQualifiedName().resolveBinding();
} else if( d instanceof ICPPASTNamespaceDefinition ){
binding = ((ICPPASTNamespaceDefinition)d).getName().resolveBinding();
}
if( binding instanceof ICPPNamespace ){
temp = ((ICPPNamespace)binding).getNamespaceScope();
} else
continue;
//namespace are searched at most once
if( !data.visited.containsKey( temp ) ){
enclosing = getClosestEnclosingScope( scope, temp );
//data.usingDirectives is a map from enclosing scope to a IScope[]
//of namespaces to consider when we reach that enclosing scope
IScope [] scopes = (IScope[]) ( data.usingDirectives.isEmpty() ? null : data.usingDirectives.get( enclosing ) );
scopes = (IScope[]) ArrayUtil.append( IScope.class, scopes, temp );
if( data.usingDirectives == ObjectMap.EMPTY_MAP ){
data.usingDirectives = new ObjectMap(2);
}
data.usingDirectives.put( enclosing, scopes );
}
}
}
static private ICPPScope getClosestEnclosingScope( IScope scope1, IScope scope2 ) throws DOMException{
ObjectSet set = new ObjectSet( 2 );
IScope parent = scope1;
while( parent != null ){
set.put( parent );
parent = parent.getParent();
}
parent = scope2;
while( parent != null && !set.containsKey( parent ) ){
parent = parent.getParent();
}
return (ICPPScope) parent;
}
/**
*
* @param scope
* @return List of encountered using directives
* @throws DOMException
*/
static protected IASTName[] lookupInScope( CPPSemantics.LookupData data, ICPPScope scope, IASTNode blockItem, ArrayWrapper usingDirectives ) throws DOMException {
IASTName possible = null;
IASTNode [] nodes = null;
IASTNode parent = scope.getPhysicalNode();
IASTName [] namespaceDefs = null;
int namespaceIdx = -1;
if( data.associated.containsKey( scope ) ){
//we are looking in scope, remove it from the associated scopes list
data.associated.remove( scope );
}
IASTName[] found = null;
if( parent instanceof IASTCompoundStatement ){
if( parent.getParent() instanceof IASTFunctionDefinition ){
ICPPASTFunctionDeclarator dtor = (ICPPASTFunctionDeclarator) ((IASTFunctionDefinition)parent.getParent()).getDeclarator();
nodes = dtor.getParameters();
}
if( nodes == null || nodes.length == 0 ){
IASTCompoundStatement compound = (IASTCompoundStatement) parent;
nodes = compound.getStatements();
}
} else if ( parent instanceof IASTTranslationUnit ){
IASTTranslationUnit translation = (IASTTranslationUnit) parent;
nodes = translation.getDeclarations();
} else if ( parent instanceof ICPPASTCompositeTypeSpecifier ){
ICPPASTCompositeTypeSpecifier comp = (ICPPASTCompositeTypeSpecifier) parent;
nodes = comp.getMembers();
} else if ( parent instanceof ICPPASTNamespaceDefinition ){
//need binding because namespaces can be split
CPPNamespace namespace = (CPPNamespace) ((ICPPASTNamespaceDefinition)parent).getName().resolveBinding();
namespaceDefs = namespace.getNamespaceDefinitions();
nodes = ((ICPPASTNamespaceDefinition)namespaceDefs[0].getParent()).getDeclarations();
namespaceIdx = 0;
} else if( parent instanceof ICPPASTFunctionDeclarator ){
ICPPASTFunctionDeclarator dtor = (ICPPASTFunctionDeclarator) parent;
nodes = dtor.getParameters();
}
int idx = -1;
boolean checkWholeClassScope = ( scope instanceof ICPPClassScope ) && data.checkWholeClassScope();
IASTNode item = ( nodes != null ? (nodes.length > 0 ? nodes[++idx] : null ) : parent );
IASTNode [][] nodeStack = null;
int [] nodeIdxStack = null;
int nodeStackPos = -1;
while( item != null ) {
if( item instanceof ICPPASTLinkageSpecification ){
IASTDeclaration [] decls = ((ICPPASTLinkageSpecification)item).getDeclarations();
if( decls != null && decls.length > 0 ){
nodeStack = (IASTNode[][]) ArrayUtil.append( IASTNode[].class, nodeStack, nodes );
nodeIdxStack = ArrayUtil.setInt( nodeIdxStack, ++nodeStackPos, idx );
nodes = ((ICPPASTLinkageSpecification)item).getDeclarations();
idx = 0;
item = nodes[idx];
}
}
if( !checkWholeClassScope && blockItem != null && ((ASTNode)item).getOffset() > ((ASTNode) blockItem).getOffset() )
break;
if( item != blockItem || data.includeBlockItem( item ) ){
if( !data.ignoreUsingDirectives &&
( item instanceof ICPPASTUsingDirective ||
(item instanceof ICPPASTNamespaceDefinition &&
((ICPPASTNamespaceDefinition)item).getName().toCharArray().length == 0) ) )
{
if( usingDirectives != null )
usingDirectives.array = ArrayUtil.append( usingDirectives.array, item );
} else {
possible = collectResult( data, scope, item, (item == parent) );
if( possible != null && (checkWholeClassScope || declaredBefore( possible, data.astName )) ){
found = (IASTName[]) ArrayUtil.append( IASTName.class, found, possible );
}
}
}
if( item == blockItem && !checkWholeClassScope )
break;
if( idx > -1 && ++idx < nodes.length ){
item = nodes[idx];
} else {
item = null;
nullItem: while( item == null ){
if( namespaceIdx > -1 ) {
//check all definitions of this namespace
while( namespaceIdx > -1 && namespaceDefs.length > ++namespaceIdx ){
nodes = ((ICPPASTNamespaceDefinition)namespaceDefs[namespaceIdx].getParent()).getDeclarations();
if( nodes.length > 0 ){
idx = 0;
item = nodes[0];
break;
}
}
} else if( parent instanceof IASTCompoundStatement && nodes instanceof IASTParameterDeclaration [] ){
//function body, we were looking at parameters, now check the body itself
IASTCompoundStatement compound = (IASTCompoundStatement) parent;
nodes = compound.getStatements();
if( nodes.length > 0 ){
idx = 0;
item = nodes[0];
break;
}
}
if( item == null && nodeStackPos >= 0 ){
nodes = nodeStack[nodeStackPos];
nodeStack[nodeStackPos] = null;
idx = nodeIdxStack[nodeStackPos--];
if( ++idx >= nodes.length )
continue;
item = nodes[idx];
}
break;
}
}
}
return found;
}
static private Object[] lookupInNominated( CPPSemantics.LookupData data, ICPPScope scope, Object[] transitives ) throws DOMException{
if( data.usingDirectives.isEmpty() )
return transitives;
ICPPScope temp = null;
IScope [] directives = (IScope[]) data.usingDirectives.remove( scope );
if( directives == null || directives.length == 0 ) {
return transitives;
}
for( int i = 0; i < directives.length && directives[i] != null; i++ ){
temp = (ICPPScope) directives[i];
if( !data.visited.containsKey( temp ) ){
if( data.visited == ObjectSet.EMPTY_SET ) {
data.visited = new ObjectSet(2);
}
data.visited.put( temp );
ArrayWrapper usings = new ArrayWrapper();
IASTName[] found = lookupInScope( data, temp, null, usings );
mergeResults( data, found, false );
//only consider the transitive using directives if we are an unqualified
//lookup, or we didn't find the name in decl
if( usings.array != null && usings.array.length > 0 && (!data.qualified() || found == null ) ){
transitives = ArrayUtil.addAll( Object.class, transitives, usings.array );
}
}
}
return transitives;
}
static private IASTName collectResult( CPPSemantics.LookupData data, ICPPScope scope, IASTNode node, boolean checkAux ){
IASTDeclaration declaration = null;
if( node instanceof IASTDeclaration )
declaration = (IASTDeclaration) node;
else if( node instanceof IASTDeclarationStatement )
declaration = ((IASTDeclarationStatement)node).getDeclaration();
else if( node instanceof IASTForStatement && checkAux )
declaration = ((IASTForStatement)node).getInitDeclaration();
else if( node instanceof IASTParameterDeclaration && !data.typesOnly() ){
IASTParameterDeclaration parameterDeclaration = (IASTParameterDeclaration) node;
IASTDeclarator dtor = parameterDeclaration.getDeclarator();
while( dtor.getNestedDeclarator() != null )
dtor = dtor.getNestedDeclarator();
IASTName declName = dtor.getName();
if( nameMatches( data, declName.toCharArray() ) ) {
return declName;
}
}
if( declaration == null )
return null;
if( declaration instanceof IASTSimpleDeclaration ){
IASTSimpleDeclaration simpleDeclaration = (IASTSimpleDeclaration) declaration;
if( !data.typesOnly() || simpleDeclaration.getDeclSpecifier().getStorageClass() == IASTDeclSpecifier.sc_typedef ) {
IASTDeclarator [] declarators = simpleDeclaration.getDeclarators();
for( int i = 0; i < declarators.length; i++ ){
IASTDeclarator declarator = declarators[i];
while( declarator.getNestedDeclarator() != null )
declarator = declarator.getNestedDeclarator();
if( data.considerConstructors() || !CPPVisitor.isConstructor( scope, declarator ) ){
IASTName declaratorName = declarator.getName();
if( nameMatches( data, declaratorName.toCharArray() ) ) {
return declaratorName;
}
}
}
}
//decl spec
IASTDeclSpecifier declSpec = simpleDeclaration.getDeclSpecifier();
if( declSpec instanceof IASTElaboratedTypeSpecifier ){
IASTName elabName = ((IASTElaboratedTypeSpecifier)declSpec).getName();
if( nameMatches( data, elabName.toCharArray() ) ) {
return elabName;
}
} else if( declSpec instanceof ICPPASTCompositeTypeSpecifier ){
IASTName compName = ((IASTCompositeTypeSpecifier)declSpec).getName();
if( nameMatches( data, compName.toCharArray() ) ) {
return compName;
}
} else if( declSpec instanceof IASTEnumerationSpecifier ){
IASTEnumerationSpecifier enumeration = (IASTEnumerationSpecifier) declSpec;
IASTName eName = enumeration.getName();
if( nameMatches( data, eName.toCharArray() ) ) {
return eName;
}
if( !data.typesOnly() ) {
//check enumerators too
IASTEnumerator [] list = enumeration.getEnumerators();
for( int i = 0; i < list.length; i++ ) {
IASTEnumerator enumerator = list[i];
if( enumerator == null ) break;
eName = enumerator.getName();
if( nameMatches( data, eName.toCharArray() ) ) {
return eName;
}
}
}
}
} else if( declaration instanceof ICPPASTUsingDeclaration ){
ICPPASTUsingDeclaration using = (ICPPASTUsingDeclaration) declaration;
IASTName name = using.getName();
if( name instanceof ICPPASTQualifiedName ){
IASTName [] ns = ((ICPPASTQualifiedName)name).getNames();
name = ns[ ns.length - 1 ];
}
if( nameMatches( data, name.toCharArray() ) ) {
return name;
}
} else if( declaration instanceof ICPPASTNamespaceDefinition ){
IASTName namespaceName = ((ICPPASTNamespaceDefinition) declaration).getName();
if( nameMatches( data, namespaceName.toCharArray() ) )
return namespaceName;
} else if( declaration instanceof ICPPASTNamespaceAlias ){
IASTName alias = ((ICPPASTNamespaceAlias) declaration).getAlias();
if( nameMatches( data, alias.toCharArray() ) )
return alias;
}
if( data.typesOnly() )
return null;
if( declaration instanceof IASTFunctionDefinition ){
IASTFunctionDefinition functionDef = (IASTFunctionDefinition) declaration;
IASTFunctionDeclarator declarator = functionDef.getDeclarator();
//check the function itself
IASTName declName = declarator.getName();
if( data.considerConstructors() || !CPPVisitor.isConstructor( scope, declarator ) ){
if( nameMatches( data, declName.toCharArray() ) ) {
return declName;
}
}
if( checkAux ) {
//check the parameters
if ( declarator instanceof IASTStandardFunctionDeclarator ) {
IASTParameterDeclaration [] parameters = ((IASTStandardFunctionDeclarator)declarator).getParameters();
for( int i = 0; i < parameters.length; i++ ){
IASTParameterDeclaration parameterDeclaration = parameters[i];
if( parameterDeclaration == null ) break;
IASTDeclarator dtor = parameterDeclaration.getDeclarator();
while( dtor.getNestedDeclarator() != null )
dtor = dtor.getNestedDeclarator();
declName = dtor.getName();
if( nameMatches( data, declName.toCharArray() ) ) {
return declName;
}
}
}
}
}
return null;
}
private static final boolean nameMatches( LookupData data, char[] potential ){
return ( (data.prefixLookup && CharArrayUtils.equals( potential, 0, data.name.length, data.name )) ||
(!data.prefixLookup && CharArrayUtils.equals( potential, data.name )) );
}
private static void addDefinition( IBinding binding, IASTName name ){
if( binding instanceof IFunction ){
IASTNode node = name.getParent();
if( node instanceof ICPPASTQualifiedName )
node = node.getParent();
if( node instanceof ICPPASTFunctionDeclarator ){
((CPPFunction)binding).addDefinition( (ICPPASTFunctionDeclarator) node );
}
}
}
static protected IBinding resolveAmbiguities( IASTName name, IBinding[] bindings ){
bindings = (IBinding[]) ArrayUtil.trim( IBinding.class, bindings );
if( bindings == null || bindings.length == 0 )
return null;
else if( bindings.length == 1 )
return bindings[ 0 ];
LookupData data = createLookupData( name, false );
data.foundItems = bindings;
try {
return resolveAmbiguities( data, name );
} catch ( DOMException e ) {
return e.getProblem();
}
}
static public boolean declaredBefore( Object obj, IASTNode node ){
if( node == null ) return true;
ASTNode nd = null;
if( obj instanceof ICPPBinding ){
ICPPBinding cpp = (ICPPBinding) obj;
IASTNode[] n = cpp.getDeclarations();
if( n != null && n.length > 0 )
nd = (ASTNode) n[0];
else if( cpp.getDefinition() != null )
nd = (ASTNode) cpp.getDefinition();
else
return true;
} else if( obj instanceof IASTName ) {
nd = (ASTNode) obj;
}
if( nd != null ){
int pointOfDecl = 0;
ASTNodeProperty prop = nd.getPropertyInParent();
if( prop == IASTDeclarator.DECLARATOR_NAME ){
pointOfDecl = nd.getOffset() + nd.getLength();
} else if( prop == IASTEnumerator.ENUMERATOR_NAME) {
IASTEnumerator enumtor = (IASTEnumerator) nd.getParent();
if( enumtor.getValue() != null ){
ASTNode exp = (ASTNode) enumtor.getValue();
pointOfDecl = exp.getOffset() + exp.getLength();
} else {
pointOfDecl = nd.getOffset() + nd.getLength();
}
} else
pointOfDecl = nd.getOffset();
return ( pointOfDecl <= ((ASTNode)node).getOffset() );
}
return false;
}
static private IBinding resolveAmbiguities( CPPSemantics.LookupData data, IASTName name ) throws DOMException {
if( !data.hasResults() || data.prefixLookup )
return null;
IBinding type = null;
IBinding obj = null;
IBinding temp = null;
IFunction[] fns = null;
Object [] items = (Object[]) data.foundItems;
for( int i = 0; i < items.length && items[i] != null; i++ ){
Object o = items[i];
if( o instanceof IASTName ){
temp = ((IASTName) o).resolveBinding();
if( temp == null )
continue;
IScope scope = temp.getScope();
if( scope instanceof CPPNamespaceScope ){
((CPPNamespaceScope)scope).setFullyResolved( (IASTName) o );
}
} else if( o instanceof IBinding ){
temp = (IBinding) o;
if( !( temp instanceof ICPPMember ) && !declaredBefore( temp, name ) )
continue;
} else
continue;
if( temp instanceof ICPPCompositeBinding ){
IBinding [] bindings = ((ICPPCompositeBinding) temp).getBindings();
//data.foundItems = ArrayUtil.addAll( Object.class, data.foundItems, bindings );
mergeResults( data, bindings, false );
items = (Object[]) data.foundItems;
continue;
} else if( temp instanceof IType ){
if( type == null ){
type = temp;
} else if( type != temp ) {
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
}
} else if( temp instanceof IFunction ){
fns = (IFunction[]) ArrayUtil.append( IFunction.class, fns, temp );
} else {
if( obj == null )
obj = temp;
else if( obj != temp ){
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
}
}
}
if( data.forUsingDeclaration() ){
IBinding [] bindings = null;
if( obj != null ){
if( fns != null ) return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
if( type == null ) return obj;
bindings = (IBinding[]) ArrayUtil.append( IBinding.class, bindings, obj );
bindings = (IBinding[]) ArrayUtil.append( IBinding.class, bindings, type );
} else {
if( fns == null ) return type;
bindings = (IBinding[]) ArrayUtil.addAll( IBinding.class, bindings, fns );
bindings = (IBinding[]) ArrayUtil.append( IBinding.class, bindings, type );
}
bindings = (IBinding[]) ArrayUtil.trim( IBinding.class, bindings );
if( bindings.length == 1 ) return bindings[0];
ICPPCompositeBinding composite = new CPPCompositeBinding( bindings );
return composite;
}
if( type != null ) {
if( data.typesOnly() || (obj == null && fns == null) )
return type;
// IScope typeScope = type.getScope();
// if( obj != null && obj.getScope() != typeScope ){
// return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
// } else if( fns != null ){
// for( int i = 0; i < fns.length && fns[i] != null; i++ ){
// if( ((IBinding)fns[i]).getScope() != typeScope )
// return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
// }
// }
}
if( fns != null){
if( obj != null )
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
return resolveFunction( data, fns );
}
return obj;
}
static private boolean functionHasParameters( IFunction function, IASTParameterDeclaration [] params ) throws DOMException{
IFunctionType ftype = function.getType();
if( params.length == 0 ){
return ftype.getParameterTypes().length == 0;
}
IASTNode node = params[0].getParent();
if( node instanceof ICPPASTFunctionDeclarator ){
IFunctionType t2 = (IFunctionType) CPPVisitor.createType( (ICPPASTFunctionDeclarator) node );
return ftype.equals( t2 );
}
return false;
}
static private void reduceToViable( LookupData data, IBinding[] functions ) throws DOMException{
if( functions == null || functions.length == 0 )
return;
Object [] fParams = data.functionParameters;
int numParameters = ( fParams != null ) ? fParams.length : 0;
int num;
//Trim the list down to the set of viable functions
IFunction fName;
ICPPASTFunctionDeclarator function = null;
int size = functions.length;
for( int i = 0; i < size && functions[i] != null; i++ ){
fName = (IFunction) functions[i];
function = (ICPPASTFunctionDeclarator) ((ICPPBinding)fName).getDefinition();
if( function == null ){
IASTNode [] nodes = ((ICPPBinding) fName).getDeclarations();
if( nodes != null && nodes.length > 0 )
function = (ICPPASTFunctionDeclarator) nodes[0];
}
if( function == null ){
//implicit member function, for now, not supporting default values or var args
num = fName.getParameters().length;
} else {
num = function.getParameters().length;
}
//if there are m arguments in the list, all candidate functions having m parameters
//are viable
if( num == numParameters ){
if( data.forDefinition() && !functionHasParameters( fName, (IASTParameterDeclaration[]) data.functionParameters ) ){
functions[i] = null;
}
continue;
} else if( function == null ){
functions[i] = null;
continue;
}
//check for void
else if( numParameters == 0 && num == 1 ){
IASTParameterDeclaration param = function.getParameters()[0];
IASTDeclSpecifier declSpec = param.getDeclSpecifier();
if( declSpec instanceof IASTSimpleDeclSpecifier ){
if( ((IASTSimpleDeclSpecifier)declSpec).getType() == IASTSimpleDeclSpecifier.t_void &&
param.getDeclarator().getPointerOperators().length == 0 )
{
continue;
}
}
}
//A candidate function having fewer than m parameters is viable only if it has an
//ellipsis in its parameter list.
if( num < numParameters ){
if( function.takesVarArgs() ) {
continue;
}
//not enough parameters, remove it
functions[i] = null;
}
//a candidate function having more than m parameters is viable only if the (m+1)-st
//parameter has a default argument
else {
IASTParameterDeclaration [] params = function.getParameters();
for( int j = num - 1; j >= numParameters; j-- ){
if( params[j].getDeclarator().getInitializer() == null ){
functions[i] = null;
size--;
break;
}
}
}
}
}
static private IType getSourceParameterType( Object [] params, int idx ){
if( params instanceof IType[] ){
IType [] types = (IType[]) params;
if( idx < types.length )
return types[idx];
return (idx == 0 ) ? VOID_TYPE : null;
} else if( params instanceof IASTExpression [] ){
IASTExpression [] exps = (IASTExpression[]) params;
if( idx < exps.length)
return CPPVisitor.getExpressionType( exps[ idx ] );
return ( idx == 0 ) ? VOID_TYPE : null;
} else if( params instanceof IASTParameterDeclaration[] ){
IASTParameterDeclaration [] decls = (IASTParameterDeclaration[]) params;
if( idx < decls.length)
return CPPVisitor.createType( decls[idx].getDeclarator() );
return ( idx == 0 ) ? VOID_TYPE : null;
} else if( params == null && idx == 0 )
return VOID_TYPE;
return null;
}
static private IBinding resolveFunction( CPPSemantics.LookupData data, IBinding[] fns ) throws DOMException{
fns = (IBinding[]) ArrayUtil.trim( IBinding.class, fns, true );
if( fns == null || fns.length == 0 )
return null;
if( data.forUsingDeclaration() ){
if( fns.length == 1 )
return fns[ 0 ];
return new CPPCompositeBinding( fns );
}
//we don't have any arguments with which to resolve the function
if( data.functionParameters == null ){
return resolveTargetedFunction( data, fns );
}
//reduce our set of candidate functions to only those who have the right number of parameters
reduceToViable( data, fns );
IFunction bestFn = null; //the best function
IFunction currFn = null; //the function currently under consideration
Cost [] bestFnCost = null; //the cost of the best function
Cost [] currFnCost = null; //the cost for the current function
IType source = null; //parameter we are called with
IType target = null; //function's parameter
// ITypeInfo voidInfo = null; //used to compare f() and f(void)
int comparison;
Cost cost = null; //the cost of converting source to target
Cost temp = null; //the cost of using a user defined conversion to convert source to target
boolean hasWorse = false; //currFn has a worse parameter fit than bestFn
boolean hasBetter = false; //currFn has a better parameter fit than bestFn
boolean ambiguous = false; //ambiguity, 2 functions are equally good
boolean currHasAmbiguousParam = false; //currFn has an ambiguous parameter conversion (ok if not bestFn)
boolean bestHasAmbiguousParam = false; //bestFn has an ambiguous parameter conversion (not ok, ambiguous)
Object [] sourceParameters = null; //the parameters the function is being called with
IASTParameterDeclaration [] targetParameters = null; //the current function's parameters
IParameter [] targetBindings = null;
int targetLength = 0;
int numFns = fns.length;
int numSourceParams = ( data.functionParameters != null ) ? data.functionParameters.length : 0;
if( data.functionParameters != null && numSourceParams == 0 )
numSourceParams = 1;
sourceParameters = data.functionParameters;
outer: for( int fnIdx = 0; fnIdx < numFns; fnIdx++ ){
currFn = (IFunction) fns[fnIdx];
if( currFn == null || bestFn == currFn )
continue;
ICPPASTFunctionDeclarator currDtor = (ICPPASTFunctionDeclarator) ((ICPPBinding)currFn).getDefinition();
if( currDtor == null ){
IASTNode[] nodes = ((ICPPBinding) currFn).getDeclarations();
if( nodes != null && nodes.length > 0 )
currDtor = (ICPPASTFunctionDeclarator) nodes[0];
}
targetParameters = ( currDtor != null ) ? currDtor.getParameters() : null;
if( targetParameters == null ){
targetBindings = currFn.getParameters();
targetLength = targetBindings.length;
} else {
targetLength = targetParameters.length;
}
int numTargetParams = ( targetLength == 0 ) ? 1 : targetLength;
if( currFnCost == null ){
currFnCost = new Cost [ (numSourceParams == 0) ? 1 : numSourceParams ];
}
comparison = 0;
boolean varArgs = false;
for( int j = 0; j < numSourceParams || j == 0; j++ ){
source = getSourceParameterType( sourceParameters, j );
if( source == null )
continue outer;
- if( source instanceof IProblemBinding )
- return (IBinding) source;
if( j < numTargetParams ){
if( targetLength == 0 && j == 0 ){
target = VOID_TYPE;
} else if( targetParameters != null ) {
IParameter param = (IParameter) targetParameters[j].getDeclarator().getName().resolveBinding();
target = param.getType();
} else {
target = targetBindings[j].getType();
}
} else
varArgs = true;
if( varArgs ){
cost = new Cost( source, null );
cost.rank = Cost.ELLIPSIS_CONVERSION;
- } /*else if ( target.getHasDefault() && source.isType( ITypeInfo.t_void ) && !source.hasPtrOperators() ){
- //source is just void, ie no parameter, if target had a default, then use that
- cost = new Cost( source, target );
- cost.rank = Cost.IDENTITY_RANK;
- }*/ else if( source.equals( target ) ){
+ } else if( source.equals( target ) ){
cost = new Cost( source, target );
cost.rank = Cost.IDENTITY_RANK; //exact match, no cost
} else {
cost = checkStandardConversionSequence( source, target );
//12.3-4 At most one user-defined conversion is implicitly applied to
//a single value. (also prevents infinite loop)
if( cost.rank == Cost.NO_MATCH_RANK && !data.forUserDefinedConversion ){
temp = checkUserDefinedConversionSequence( source, target );
if( temp != null ){
cost = temp;
}
}
}
currFnCost[ j ] = cost;
}
hasWorse = false;
hasBetter = false;
//In order for this function to be better than the previous best, it must
//have at least one parameter match that is better that the corresponding
//match for the other function, and none that are worse.
for( int j = 0; j < numSourceParams || j == 0; j++ ){
if( currFnCost[ j ].rank < 0 ){
hasWorse = true;
hasBetter = false;
break;
}
//an ambiguity in the user defined conversion sequence is only a problem
//if this function turns out to be the best.
currHasAmbiguousParam = ( currFnCost[ j ].userDefined == 1 );
if( bestFnCost != null ){
comparison = currFnCost[ j ].compare( bestFnCost[ j ] );
hasWorse |= ( comparison < 0 );
hasBetter |= ( comparison > 0 );
} else {
hasBetter = true;
}
}
//If function has a parameter match that is better than the current best,
//and another that is worse (or everything was just as good, neither better nor worse).
//then this is an ambiguity (unless we find something better than both later)
ambiguous |= ( hasWorse && hasBetter ) || ( !hasWorse && !hasBetter );
if( !hasWorse ){
if( hasBetter ){
//the new best function.
ambiguous = false;
bestFnCost = currFnCost;
bestHasAmbiguousParam = currHasAmbiguousParam;
currFnCost = null;
bestFn = currFn;
}
}
}
if( ambiguous || bestHasAmbiguousParam ){
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
}
return bestFn;
}
/**
* 13.4-1 A use of an overloaded function without arguments is resolved in certain contexts to a function
* @param data
* @param fns
* @return
*/
private static IBinding resolveTargetedFunction( LookupData data, IBinding[] fns ) {
if( fns.length == 1 )
return fns[0];
if( data.forAssociatedScopes ){
return new CPPCompositeBinding( fns );
}
IBinding result = null;
Object o = getTargetType( data );
IType type, types[] = null;
int idx = -1;
if( o instanceof IType [] ){
types = (IType[]) o;
type = types[ ++idx ];
} else
type = (IType) o;
while( type != null ){
type = (type != null) ? getUltimateType( type, false ) : null;
if( type == null || !( type instanceof IFunctionType ) )
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
for( int i = 0; i < fns.length; i++ ){
IFunction fn = (IFunction) fns[i];
IType ft = null;
try {
ft = fn.getType();
} catch ( DOMException e ) {
ft = e.getProblem();
}
if( type.equals( ft ) ){
if( result == null )
result = fn;
else
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
}
}
if( idx > 0 && ++idx < types.length ){
type = types[idx];
} else {
type = null;
}
}
return ( result != null ) ? result : new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
}
private static Object getTargetType( LookupData data ){
IASTName name = data.astName;
if( name.getPropertyInParent() == ICPPASTQualifiedName.SEGMENT_NAME )
name = (IASTName) name.getParent();
if( name.getPropertyInParent() != IASTIdExpression.ID_NAME )
return null;
IASTIdExpression idExp = (IASTIdExpression) name.getParent();
IASTNode node = idExp.getParent();
ASTNodeProperty prop = null;
while( node != null ){
prop = node.getPropertyInParent();
//target is an object or reference being initialized
if( prop == IASTInitializerExpression.INITIALIZER_EXPRESSION ){
IASTInitializerExpression initExp = (IASTInitializerExpression) node.getParent();
IASTDeclarator dtor = (IASTDeclarator) initExp.getParent();
return CPPVisitor.createType( dtor );
}
//target is the left side of an assignment
else if( prop == IASTBinaryExpression.OPERAND_TWO &&
((IASTBinaryExpression)node.getParent()).getOperator() == IASTBinaryExpression.op_assign )
{
IASTBinaryExpression binaryExp = (IASTBinaryExpression) node.getParent();
IASTExpression exp = binaryExp.getOperand1();
return CPPVisitor.getExpressionType( exp );
}
//target is a parameter of a function
else if( prop == IASTFunctionCallExpression.PARAMETERS ||
(prop == IASTExpressionList.NESTED_EXPRESSION && node.getParent().getPropertyInParent() == IASTFunctionCallExpression.PARAMETERS ) )
{
//if this function call refers to an overloaded function, there is more than one possiblity
//for the target type
IASTFunctionCallExpression fnCall = null;
int idx = -1;
if( prop == IASTFunctionCallExpression.PARAMETERS ){
fnCall = (IASTFunctionCallExpression) node.getParent();
idx = 0;
} else {
IASTExpressionList list = (IASTExpressionList) node.getParent();
fnCall = (IASTFunctionCallExpression) list.getParent();
IASTExpression [] exps = list.getExpressions();
for( int i = 0; i < exps.length; i++ ){
if( exps[i] == node ){
idx = i;
break;
}
}
}
IFunctionType [] types = getPossibleFunctions( fnCall );
if( types == null ) return null;
IType [] result = null;
for( int i = 0; i < types.length && types[i] != null; i++ ){
IType [] pts = null;
try {
pts = types[i].getParameterTypes();
} catch ( DOMException e ) {
continue;
}
if( pts.length > idx )
result = (IType[]) ArrayUtil.append( IType.class, result, pts[idx] );
}
return result;
}
//target is an explicit type conversion
// else if( prop == ICPPASTSimpleTypeConstructorExpression.INITIALIZER_VALUE )
// {
//
// }
//target is an explicit type conversion
else if( prop == IASTCastExpression.OPERAND )
{
IASTCastExpression cast = (IASTCastExpression) node.getParent();
return CPPVisitor.createType( cast.getTypeId().getAbstractDeclarator() );
}
//target is the return value of a function, operator or conversion
else if( prop == IASTReturnStatement.RETURNVALUE )
{
while( !( node instanceof IASTFunctionDefinition ) ){
node = node.getParent();
}
IASTDeclarator dtor = ((IASTFunctionDefinition)node).getDeclarator();
while( dtor.getNestedDeclarator() != null )
dtor = dtor.getNestedDeclarator();
IBinding binding = dtor.getName().resolveBinding();
if( binding instanceof IFunction ){
try {
IFunctionType ft = ((IFunction)binding).getType();
return ft.getReturnType();
} catch ( DOMException e ) {
}
}
}
else if( prop == IASTUnaryExpression.OPERAND ){
IASTUnaryExpression parent = (IASTUnaryExpression) node.getParent();
if( parent.getOperator() == IASTUnaryExpression.op_bracketedPrimary ||
parent.getOperator() == IASTUnaryExpression.op_amper)
{
node = parent;
continue;
}
}
break;
}
return null;
}
static private IFunctionType [] getPossibleFunctions( IASTFunctionCallExpression call ){
IFunctionType [] result = null;
IASTExpression exp = call.getFunctionNameExpression();
if( exp instanceof IASTIdExpression ){
IASTIdExpression idExp = (IASTIdExpression) exp;
IASTName name = idExp.getName();
LookupData data = createLookupData( name, false );
try {
lookup( data, name );
} catch ( DOMException e1 ) {
return null;
}
if( data.hasResults() ){
Object [] items = (Object[]) data.foundItems;
IBinding temp = null;
for( int i = 0; i < items.length; i++ ){
Object o = items[i];
if( o == null ) break;
if( o instanceof IASTName )
temp = ((IASTName) o).resolveBinding();
else if( o instanceof IBinding ){
temp = (IBinding) o;
if( !declaredBefore( temp, name ) )
continue;
} else
continue;
try {
if( temp instanceof IFunction ){
result = (IFunctionType[]) ArrayUtil.append( IFunctionType.class, result, ((IFunction)temp).getType() );
} else if( temp instanceof IVariable ){
IType type = getUltimateType( ((IVariable) temp).getType(), false );
if( type instanceof IFunctionType )
result = (IFunctionType[]) ArrayUtil.append( IFunctionType.class, result, type );
}
} catch( DOMException e ){
}
}
}
} else {
IType type = CPPVisitor.getExpressionType( exp );
type = getUltimateType( type, false );
if( type instanceof IFunctionType ){
result = new IFunctionType[] { (IFunctionType) type };
}
}
return result;
}
static private Cost checkStandardConversionSequence( IType source, IType target ) throws DOMException {
Cost cost = lvalue_to_rvalue( source, target );
if( cost.source == null || cost.target == null ){
return cost;
}
if( cost.source.equals( cost.target ) ){
cost.rank = Cost.IDENTITY_RANK;
return cost;
}
qualificationConversion( cost );
//if we can't convert the qualifications, then we can't do anything
if( cost.qualification == 0 ){
return cost;
}
//was the qualification conversion enough?
IType s = getUltimateType( cost.source, true );
IType t = getUltimateType( cost.target, true );
if( s.equals( t ) ){
return cost;
}
promotion( cost );
if( cost.promotion > 0 || cost.rank > -1 ){
return cost;
}
conversion( cost );
if( cost.rank > -1 )
return cost;
derivedToBaseConversion( cost );
return cost;
}
static private Cost checkUserDefinedConversionSequence( IType source, IType target ) throws DOMException {
Cost cost = null;
Cost constructorCost = null;
Cost conversionCost = null;
IType s = getUltimateType( source, true );
IType t = getUltimateType( target, true );
ICPPConstructor constructor = null;
ICPPMethod conversion = null;
//constructors
if( t instanceof ICPPClassType ){
LookupData data = new LookupData( EMPTY_NAME_ARRAY );
data.forUserDefinedConversion = true;
data.functionParameters = new IType [] { source };
ICPPConstructor [] constructors = ((ICPPClassType)t).getConstructors();
if( constructors.length > 0 ){
if( constructors.length == 1 && constructors[0] instanceof IProblemBinding )
constructor = null;
else {
//the list out of Arrays.asList does not support remove, which we need
constructor = (ICPPConstructor) resolveFunction( data, constructors );
}
}
if( constructor != null && constructor.isExplicit() ){
constructor = null;
}
}
//conversion operators
if( s instanceof ICPPClassType ){
char[] name = EMPTY_NAME_ARRAY;//TODO target.toCharArray();
if( !CharArrayUtils.equals( name, EMPTY_NAME_ARRAY) ){
LookupData data = new LookupData( CharArrayUtils.concat( OPERATOR_, name ));
data.functionParameters = IASTExpression.EMPTY_EXPRESSION_ARRAY;
data.forUserDefinedConversion = true;
ICPPScope scope = (ICPPScope) ((ICPPClassType) s).getCompositeScope();
data.foundItems = lookupInScope( data, scope, null, null );
IBinding [] fns = (IBinding[]) ArrayUtil.append( IBinding.class, null, data.foundItems );
conversion = (ICPPMethod) ( (data.foundItems != null ) ? resolveFunction( data, fns ) : null );
}
}
if( constructor != null ){
constructorCost = checkStandardConversionSequence( t, target );
}
if( conversion != null ){
conversionCost = checkStandardConversionSequence( conversion.getType().getReturnType(), target );
}
//if both are valid, then the conversion is ambiguous
if( constructorCost != null && constructorCost.rank != Cost.NO_MATCH_RANK &&
conversionCost != null && conversionCost.rank != Cost.NO_MATCH_RANK )
{
cost = constructorCost;
cost.userDefined = Cost.AMBIGUOUS_USERDEFINED_CONVERSION;
cost.rank = Cost.USERDEFINED_CONVERSION_RANK;
} else {
if( constructorCost != null && constructorCost.rank != Cost.NO_MATCH_RANK ){
cost = constructorCost;
cost.userDefined = constructor.hashCode();
cost.rank = Cost.USERDEFINED_CONVERSION_RANK;
} else if( conversionCost != null && conversionCost.rank != Cost.NO_MATCH_RANK ){
cost = conversionCost;
cost.userDefined = conversion.hashCode();
cost.rank = Cost.USERDEFINED_CONVERSION_RANK;
}
}
return cost;
}
static protected IType getUltimateType( IType type, boolean stopAtPointerToMember ){
try {
while( true ){
if( type instanceof ITypedef )
type = ((ITypedef)type).getType();
else if( type instanceof IQualifierType )
type = ((IQualifierType)type).getType();
else if( stopAtPointerToMember && type instanceof ICPPPointerToMemberType )
return type;
else if( type instanceof IPointerType )
type = ((IPointerType) type).getType();
else if( type instanceof ICPPReferenceType )
type = ((ICPPReferenceType)type).getType();
else
return type;
}
} catch ( DOMException e ) {
return e.getProblem();
}
}
static private boolean isCompleteType( IType type ){
type = getUltimateType( type, false );
if( type instanceof ICPPClassType && ((ICPPBinding)type).getDefinition() == null ){
return false;
}
return true;
}
static private Cost lvalue_to_rvalue( IType source, IType target ) throws DOMException{
Cost cost = new Cost( source, target );
if( ! isCompleteType( source ) ){
cost.rank = Cost.NO_MATCH_RANK;
return cost;
}
if( source instanceof ICPPReferenceType ){
source = ((ICPPReferenceType) source).getType();
}
if( target instanceof ICPPReferenceType ){
target = ((ICPPReferenceType) target).getType();
cost.targetHadReference = true;
}
cost.source = source;
cost.target = target;
return cost;
}
static private void qualificationConversion( Cost cost ) throws DOMException{
boolean canConvert = true;
IPointerType op1, op2;
IType s = cost.source, t = cost.target;
boolean constInEveryCV2k = true;
while( true ){
op1 = null;
op2 = null;
while( true ){
if( s instanceof ITypedef )
s = ((ITypedef)s).getType();
else {
if( s instanceof IPointerType )
op1 = (IPointerType) s;
break;
}
}
while( true ){
if( t instanceof ITypedef )
t = ((ITypedef)t).getType();
else {
if( t instanceof IPointerType )
op2 = (IPointerType) t;
break;
}
}
if( op1 == null && op2 == null )
break;
else if( op1 == null ^ op2 == null) {
canConvert = false;
break;
} else if( op1 instanceof ICPPPointerToMemberType ^ op2 instanceof ICPPPointerToMemberType ){
canConvert = false;
break;
}
//if const is in cv1,j then const is in cv2,j. Similary for volatile
if( ( op1.isConst() && !op2.isConst() ) || ( op1.isVolatile() && !op2.isVolatile() ) ) {
canConvert = false;
break;
}
//if cv1,j and cv2,j are different then const is in every cv2,k for 0<k<j
if( !constInEveryCV2k && ( op1.isConst() != op2.isConst() ||
op1.isVolatile() != op2.isVolatile() ) )
{
canConvert = false;
break;
}
constInEveryCV2k &= op2.isConst();
s = op1.getType();
t = op2.getType();
}
if( s instanceof IQualifierType ^ t instanceof IQualifierType ){
if( t instanceof IQualifierType )
canConvert = true;
else
canConvert = false;
} else if( s instanceof IQualifierType && t instanceof IQualifierType ){
IQualifierType qs = (IQualifierType) s, qt = (IQualifierType) t;
if( qs.isConst() && !qt.isConst() || qs.isVolatile() && !qt.isVolatile() )
canConvert = false;
}
if( canConvert == true ){
cost.qualification = 1;
cost.rank = Cost.LVALUE_OR_QUALIFICATION_RANK;
} else {
cost.qualification = 0;
}
}
/**
*
* @param source
* @param target
* @return int
*
* 4.5-1 char, signed char, unsigned char, short int or unsigned short int
* can be converted to int if int can represent all the values of the source
* type, otherwise they can be converted to unsigned int.
* 4.5-2 wchar_t or an enumeration can be converted to the first of the
* following that can hold it: int, unsigned int, long unsigned long.
* 4.5-4 bool can be promoted to int
* 4.6 float can be promoted to double
* @throws DOMException
*/
static private void promotion( Cost cost ) throws DOMException{
IType src = getUltimateType( cost.source, true );
IType trg = getUltimateType( cost.target, true );
if( src.equals( trg ) )
return;
if( src instanceof IBasicType && trg instanceof IBasicType ){
int sType = ((IBasicType)src).getType();
int tType = ((IBasicType)trg).getType();
if( ( tType == IBasicType.t_int && ( sType == IBasicType.t_char ||
sType == ICPPBasicType.t_bool ||
sType == ICPPBasicType.t_wchar_t ) ) ||
( tType == IBasicType.t_double && sType == IBasicType.t_float ) )
{
cost.promotion = 1;
}
} else if( src instanceof IEnumeration && trg instanceof IBasicType &&
((IBasicType) trg).getType() == IBasicType.t_int )
{
cost.promotion = 1;
}
cost.rank = (cost.promotion > 0 ) ? Cost.PROMOTION_RANK : Cost.NO_MATCH_RANK;
}
static private void conversion( Cost cost ) throws DOMException{
IType src = cost.source;
IType trg = cost.target;
int temp = -1;
cost.conversion = 0;
cost.detail = 0;
IType s = getUltimateType( src, true );
IType t = getUltimateType( trg, true );
if( s instanceof ICPPClassType ){
//4.10-2 an rvalue of type "pointer to cv T", where T is an object type can be
//converted to an rvalue of type "pointer to cv void"
if( t instanceof IBasicType && ((IBasicType)t).getType() == IBasicType.t_void ){
cost.rank = Cost.CONVERSION_RANK;
cost.conversion = 1;
cost.detail = 2;
return;
}
//4.10-3 An rvalue of type "pointer to cv D", where D is a class type can be converted
//to an rvalue of type "pointer to cv B", where B is a base class of D.
else if( t instanceof ICPPClassType ){
temp = hasBaseClass( (ICPPClassType)s, (ICPPClassType) t, true );
cost.rank = ( temp > -1 ) ? Cost.CONVERSION_RANK : Cost.NO_MATCH_RANK;
cost.conversion = ( temp > -1 ) ? temp : 0;
cost.detail = 1;
return;
}
} else if( t instanceof IBasicType && s instanceof IBasicType || s instanceof IEnumeration ){
//4.7 An rvalue of an integer type can be converted to an rvalue of another integer type.
//An rvalue of an enumeration type can be converted to an rvalue of an integer type.
cost.rank = Cost.CONVERSION_RANK;
cost.conversion = 1;
} else if( s instanceof ICPPPointerToMemberType && t instanceof ICPPPointerToMemberType ){
//4.11-2 An rvalue of type "pointer to member of B of type cv T", where B is a class type,
//can be converted to an rvalue of type "pointer to member of D of type cv T" where D is a
//derived class of B
ICPPPointerToMemberType spm = (ICPPPointerToMemberType) s;
ICPPPointerToMemberType tpm = (ICPPPointerToMemberType) t;
if( spm.getType().equals( tpm.getType() ) ){
temp = hasBaseClass( tpm.getMemberOfClass(), spm.getMemberOfClass(), false );
cost.rank = ( temp > -1 ) ? Cost.CONVERSION_RANK : Cost.NO_MATCH_RANK;
cost.conversion = ( temp > -1 ) ? temp : 0;
cost.detail = 1;
}
}
}
static private void derivedToBaseConversion( Cost cost ) throws DOMException {
IType s = getUltimateType( cost.source, true );
IType t = getUltimateType( cost.target, true );
if( cost.targetHadReference && s instanceof ICPPClassType && t instanceof ICPPClassType ){
int temp = hasBaseClass( (ICPPClassType) s, (ICPPClassType) t, true );
if( temp > -1 ){
cost.rank = Cost.DERIVED_TO_BASE_CONVERSION;
cost.conversion = temp;
}
}
}
static private int hasBaseClass( IBinding symbol, IBinding base, boolean needVisibility ) throws DOMException {
if( symbol == base ){
return 0;
}
ICPPClassType clsSymbol = null;
ICPPClassType clsBase = null;
IType temp = null;
while( symbol instanceof ITypedef ){
temp = ((ITypedef)symbol).getType();
if( temp instanceof IBinding )
symbol = (IBinding) temp;
else return -1;
}
if( symbol instanceof ICPPClassType )
clsSymbol = (ICPPClassType) symbol;
else return -1;
while( base instanceof ITypedef ){
temp = ((ITypedef)base).getType();
if( temp instanceof IBinding )
base= (IBinding) temp;
else return -1;
}
if( base instanceof ICPPClassType )
clsBase = (ICPPClassType) base;
else return -1;
ICPPClassType parent = null;
ICPPBase [] bases = clsSymbol.getBases();
for( int i = 0; i < bases.length; i ++ ){
ICPPBase wrapper = bases[i];
parent = bases[i].getBaseClass();
boolean isVisible = ( wrapper.getVisibility() == ICPPBase.v_public);
if( parent == clsBase ){
if( needVisibility && !isVisible )
return -1;
return 1;
}
int n = hasBaseClass( parent, clsBase, needVisibility );
if( n > 0 )
return n + 1;
}
return -1;
}
/**
* Find the binding for the type for the given name, if the given name is not a type, or can not
* be resolved, null is returned.
* @param mostRelevantScope
* @param name
* @return
*/
public static IBinding findTypeBinding( IASTNode mostRelevantScope, IASTName name ){
IScope scope = null;
if( mostRelevantScope instanceof IASTCompoundStatement )
scope = ((IASTCompoundStatement) mostRelevantScope).getScope();
else if ( mostRelevantScope instanceof IASTTranslationUnit )
scope = ((IASTTranslationUnit) mostRelevantScope).getScope();
else if ( mostRelevantScope instanceof ICPPASTNamespaceDefinition )
scope = ((ICPPASTNamespaceDefinition) mostRelevantScope).getScope();
else if( mostRelevantScope instanceof ICPPASTCompositeTypeSpecifier )
scope = ((ICPPASTCompositeTypeSpecifier) mostRelevantScope).getScope();
if( scope == null )
return null;
LookupData data = new LookupData( name ){
public boolean typesOnly(){ return true; }
public boolean forUsingDeclaration(){ return false; }
public boolean forDefinition(){ return false; }
public boolean considerConstructors(){ return false; }
public boolean functionCall(){ return false; }
public boolean qualified(){
IASTNode p1 = astName.getParent();
if( p1 instanceof ICPPASTQualifiedName ){
return ((ICPPASTQualifiedName)p1).getNames()[0] != astName;
}
return false;
}
};
try {
lookup( data, scope );
} catch (DOMException e) {
return null;
}
IBinding binding = null;
try {
binding = resolveAmbiguities( data, name );
} catch ( DOMException e2 ) {
}
return binding;
}
public static IBinding [] prefixLookup( IASTName name ){
LookupData data = createLookupData( name, true );
data.prefixLookup = true;
data.foundItems = new CharArrayObjectMap( 2 );
try {
lookup( data, name );
} catch ( DOMException e ) {
}
CharArrayObjectMap map = (CharArrayObjectMap) data.foundItems;
IBinding [] result = null;
if( !map.isEmpty() ){
char [] key = null;
Object obj = null;
int size = map.size();
for( int i = 0; i < size; i++ ) {
key = map.keyAt( i );
obj = map.get( key );
if( obj instanceof IBinding )
result = (IBinding[]) ArrayUtil.append( IBinding.class, result, obj );
else {
Object item = null;
if( obj instanceof Object[] ){
Object[] objs = (Object[]) obj;
if( objs.length > 1 && objs[1] != null )
continue;
item = objs[0];
} else {
item = obj;
}
if( item instanceof IBinding )
result = (IBinding[]) ArrayUtil.append( IBinding.class, result, item );
else {
IBinding binding = ((IASTName) item).resolveBinding();
if( binding != null && !(binding instanceof IProblemBinding))
result = (IBinding[]) ArrayUtil.append( IBinding.class, result, binding );
}
}
}
}
return (IBinding[]) ArrayUtil.trim( IBinding.class, result );
}
}
| false | true | static private IBinding resolveFunction( CPPSemantics.LookupData data, IBinding[] fns ) throws DOMException{
fns = (IBinding[]) ArrayUtil.trim( IBinding.class, fns, true );
if( fns == null || fns.length == 0 )
return null;
if( data.forUsingDeclaration() ){
if( fns.length == 1 )
return fns[ 0 ];
return new CPPCompositeBinding( fns );
}
//we don't have any arguments with which to resolve the function
if( data.functionParameters == null ){
return resolveTargetedFunction( data, fns );
}
//reduce our set of candidate functions to only those who have the right number of parameters
reduceToViable( data, fns );
IFunction bestFn = null; //the best function
IFunction currFn = null; //the function currently under consideration
Cost [] bestFnCost = null; //the cost of the best function
Cost [] currFnCost = null; //the cost for the current function
IType source = null; //parameter we are called with
IType target = null; //function's parameter
// ITypeInfo voidInfo = null; //used to compare f() and f(void)
int comparison;
Cost cost = null; //the cost of converting source to target
Cost temp = null; //the cost of using a user defined conversion to convert source to target
boolean hasWorse = false; //currFn has a worse parameter fit than bestFn
boolean hasBetter = false; //currFn has a better parameter fit than bestFn
boolean ambiguous = false; //ambiguity, 2 functions are equally good
boolean currHasAmbiguousParam = false; //currFn has an ambiguous parameter conversion (ok if not bestFn)
boolean bestHasAmbiguousParam = false; //bestFn has an ambiguous parameter conversion (not ok, ambiguous)
Object [] sourceParameters = null; //the parameters the function is being called with
IASTParameterDeclaration [] targetParameters = null; //the current function's parameters
IParameter [] targetBindings = null;
int targetLength = 0;
int numFns = fns.length;
int numSourceParams = ( data.functionParameters != null ) ? data.functionParameters.length : 0;
if( data.functionParameters != null && numSourceParams == 0 )
numSourceParams = 1;
sourceParameters = data.functionParameters;
outer: for( int fnIdx = 0; fnIdx < numFns; fnIdx++ ){
currFn = (IFunction) fns[fnIdx];
if( currFn == null || bestFn == currFn )
continue;
ICPPASTFunctionDeclarator currDtor = (ICPPASTFunctionDeclarator) ((ICPPBinding)currFn).getDefinition();
if( currDtor == null ){
IASTNode[] nodes = ((ICPPBinding) currFn).getDeclarations();
if( nodes != null && nodes.length > 0 )
currDtor = (ICPPASTFunctionDeclarator) nodes[0];
}
targetParameters = ( currDtor != null ) ? currDtor.getParameters() : null;
if( targetParameters == null ){
targetBindings = currFn.getParameters();
targetLength = targetBindings.length;
} else {
targetLength = targetParameters.length;
}
int numTargetParams = ( targetLength == 0 ) ? 1 : targetLength;
if( currFnCost == null ){
currFnCost = new Cost [ (numSourceParams == 0) ? 1 : numSourceParams ];
}
comparison = 0;
boolean varArgs = false;
for( int j = 0; j < numSourceParams || j == 0; j++ ){
source = getSourceParameterType( sourceParameters, j );
if( source == null )
continue outer;
if( source instanceof IProblemBinding )
return (IBinding) source;
if( j < numTargetParams ){
if( targetLength == 0 && j == 0 ){
target = VOID_TYPE;
} else if( targetParameters != null ) {
IParameter param = (IParameter) targetParameters[j].getDeclarator().getName().resolveBinding();
target = param.getType();
} else {
target = targetBindings[j].getType();
}
} else
varArgs = true;
if( varArgs ){
cost = new Cost( source, null );
cost.rank = Cost.ELLIPSIS_CONVERSION;
} /*else if ( target.getHasDefault() && source.isType( ITypeInfo.t_void ) && !source.hasPtrOperators() ){
//source is just void, ie no parameter, if target had a default, then use that
cost = new Cost( source, target );
cost.rank = Cost.IDENTITY_RANK;
}*/ else if( source.equals( target ) ){
cost = new Cost( source, target );
cost.rank = Cost.IDENTITY_RANK; //exact match, no cost
} else {
cost = checkStandardConversionSequence( source, target );
//12.3-4 At most one user-defined conversion is implicitly applied to
//a single value. (also prevents infinite loop)
if( cost.rank == Cost.NO_MATCH_RANK && !data.forUserDefinedConversion ){
temp = checkUserDefinedConversionSequence( source, target );
if( temp != null ){
cost = temp;
}
}
}
currFnCost[ j ] = cost;
}
hasWorse = false;
hasBetter = false;
//In order for this function to be better than the previous best, it must
//have at least one parameter match that is better that the corresponding
//match for the other function, and none that are worse.
for( int j = 0; j < numSourceParams || j == 0; j++ ){
if( currFnCost[ j ].rank < 0 ){
hasWorse = true;
hasBetter = false;
break;
}
//an ambiguity in the user defined conversion sequence is only a problem
//if this function turns out to be the best.
currHasAmbiguousParam = ( currFnCost[ j ].userDefined == 1 );
if( bestFnCost != null ){
comparison = currFnCost[ j ].compare( bestFnCost[ j ] );
hasWorse |= ( comparison < 0 );
hasBetter |= ( comparison > 0 );
} else {
hasBetter = true;
}
}
//If function has a parameter match that is better than the current best,
//and another that is worse (or everything was just as good, neither better nor worse).
//then this is an ambiguity (unless we find something better than both later)
ambiguous |= ( hasWorse && hasBetter ) || ( !hasWorse && !hasBetter );
if( !hasWorse ){
if( hasBetter ){
//the new best function.
ambiguous = false;
bestFnCost = currFnCost;
bestHasAmbiguousParam = currHasAmbiguousParam;
currFnCost = null;
bestFn = currFn;
}
}
}
if( ambiguous || bestHasAmbiguousParam ){
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
}
return bestFn;
}
| static private IBinding resolveFunction( CPPSemantics.LookupData data, IBinding[] fns ) throws DOMException{
fns = (IBinding[]) ArrayUtil.trim( IBinding.class, fns, true );
if( fns == null || fns.length == 0 )
return null;
if( data.forUsingDeclaration() ){
if( fns.length == 1 )
return fns[ 0 ];
return new CPPCompositeBinding( fns );
}
//we don't have any arguments with which to resolve the function
if( data.functionParameters == null ){
return resolveTargetedFunction( data, fns );
}
//reduce our set of candidate functions to only those who have the right number of parameters
reduceToViable( data, fns );
IFunction bestFn = null; //the best function
IFunction currFn = null; //the function currently under consideration
Cost [] bestFnCost = null; //the cost of the best function
Cost [] currFnCost = null; //the cost for the current function
IType source = null; //parameter we are called with
IType target = null; //function's parameter
// ITypeInfo voidInfo = null; //used to compare f() and f(void)
int comparison;
Cost cost = null; //the cost of converting source to target
Cost temp = null; //the cost of using a user defined conversion to convert source to target
boolean hasWorse = false; //currFn has a worse parameter fit than bestFn
boolean hasBetter = false; //currFn has a better parameter fit than bestFn
boolean ambiguous = false; //ambiguity, 2 functions are equally good
boolean currHasAmbiguousParam = false; //currFn has an ambiguous parameter conversion (ok if not bestFn)
boolean bestHasAmbiguousParam = false; //bestFn has an ambiguous parameter conversion (not ok, ambiguous)
Object [] sourceParameters = null; //the parameters the function is being called with
IASTParameterDeclaration [] targetParameters = null; //the current function's parameters
IParameter [] targetBindings = null;
int targetLength = 0;
int numFns = fns.length;
int numSourceParams = ( data.functionParameters != null ) ? data.functionParameters.length : 0;
if( data.functionParameters != null && numSourceParams == 0 )
numSourceParams = 1;
sourceParameters = data.functionParameters;
outer: for( int fnIdx = 0; fnIdx < numFns; fnIdx++ ){
currFn = (IFunction) fns[fnIdx];
if( currFn == null || bestFn == currFn )
continue;
ICPPASTFunctionDeclarator currDtor = (ICPPASTFunctionDeclarator) ((ICPPBinding)currFn).getDefinition();
if( currDtor == null ){
IASTNode[] nodes = ((ICPPBinding) currFn).getDeclarations();
if( nodes != null && nodes.length > 0 )
currDtor = (ICPPASTFunctionDeclarator) nodes[0];
}
targetParameters = ( currDtor != null ) ? currDtor.getParameters() : null;
if( targetParameters == null ){
targetBindings = currFn.getParameters();
targetLength = targetBindings.length;
} else {
targetLength = targetParameters.length;
}
int numTargetParams = ( targetLength == 0 ) ? 1 : targetLength;
if( currFnCost == null ){
currFnCost = new Cost [ (numSourceParams == 0) ? 1 : numSourceParams ];
}
comparison = 0;
boolean varArgs = false;
for( int j = 0; j < numSourceParams || j == 0; j++ ){
source = getSourceParameterType( sourceParameters, j );
if( source == null )
continue outer;
if( j < numTargetParams ){
if( targetLength == 0 && j == 0 ){
target = VOID_TYPE;
} else if( targetParameters != null ) {
IParameter param = (IParameter) targetParameters[j].getDeclarator().getName().resolveBinding();
target = param.getType();
} else {
target = targetBindings[j].getType();
}
} else
varArgs = true;
if( varArgs ){
cost = new Cost( source, null );
cost.rank = Cost.ELLIPSIS_CONVERSION;
} else if( source.equals( target ) ){
cost = new Cost( source, target );
cost.rank = Cost.IDENTITY_RANK; //exact match, no cost
} else {
cost = checkStandardConversionSequence( source, target );
//12.3-4 At most one user-defined conversion is implicitly applied to
//a single value. (also prevents infinite loop)
if( cost.rank == Cost.NO_MATCH_RANK && !data.forUserDefinedConversion ){
temp = checkUserDefinedConversionSequence( source, target );
if( temp != null ){
cost = temp;
}
}
}
currFnCost[ j ] = cost;
}
hasWorse = false;
hasBetter = false;
//In order for this function to be better than the previous best, it must
//have at least one parameter match that is better that the corresponding
//match for the other function, and none that are worse.
for( int j = 0; j < numSourceParams || j == 0; j++ ){
if( currFnCost[ j ].rank < 0 ){
hasWorse = true;
hasBetter = false;
break;
}
//an ambiguity in the user defined conversion sequence is only a problem
//if this function turns out to be the best.
currHasAmbiguousParam = ( currFnCost[ j ].userDefined == 1 );
if( bestFnCost != null ){
comparison = currFnCost[ j ].compare( bestFnCost[ j ] );
hasWorse |= ( comparison < 0 );
hasBetter |= ( comparison > 0 );
} else {
hasBetter = true;
}
}
//If function has a parameter match that is better than the current best,
//and another that is worse (or everything was just as good, neither better nor worse).
//then this is an ambiguity (unless we find something better than both later)
ambiguous |= ( hasWorse && hasBetter ) || ( !hasWorse && !hasBetter );
if( !hasWorse ){
if( hasBetter ){
//the new best function.
ambiguous = false;
bestFnCost = currFnCost;
bestHasAmbiguousParam = currHasAmbiguousParam;
currFnCost = null;
bestFn = currFn;
}
}
}
if( ambiguous || bestHasAmbiguousParam ){
return new ProblemBinding( IProblemBinding.SEMANTIC_AMBIGUOUS_LOOKUP, data.name );
}
return bestFn;
}
|
diff --git a/Yace-war/src/java/net/yace/web/servlets/ServletItemDetails.java b/Yace-war/src/java/net/yace/web/servlets/ServletItemDetails.java
index 34d58a7..c66d4eb 100644
--- a/Yace-war/src/java/net/yace/web/servlets/ServletItemDetails.java
+++ b/Yace-war/src/java/net/yace/web/servlets/ServletItemDetails.java
@@ -1,121 +1,121 @@
package net.yace.web.servlets;
import java.io.IOException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.yace.entity.Yattributevalue;
import net.yace.entity.Yitem;
import net.yace.entity.Yuser;
import net.yace.facade.YitemFacade;
import net.yace.web.utils.ServicesLocator;
import net.yace.web.utils.YaceUtils;
public class ServletItemDetails extends HttpServlet {
private final static String VUE_ITEM = "WEB-INF/view/user/item-attributevalues.jsp";
private final static String VUE_HOME = "WEB-INF/view/user/home.jsp";
//url pattern : /details
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//droits d'acces de l'utilisateur à l'item
//cas user proprietaire item privé
//cas consultation item publique
YitemFacade itemFac = ServicesLocator.getItemFacade();
String idItem = "";
idItem = request.getParameter("item");
if (idItem == null || idItem.isEmpty()) {
YaceUtils.displayItemError(request, response);
} else {
int idIt = Integer.parseInt(idItem);
//gestion permission : public ou privé
//savoir deja si l'item existe
Yitem item = itemFac.find(idIt);
HttpSession session = request.getSession(false);
Yuser yuser = null;
if (session != null) {
yuser = (Yuser) session.getAttribute("user");
}
if (YaceUtils.CanDisplayItem(item, yuser)) {
//liste des attributs de l'item
List<Yattributevalue> valList = itemFac.getItemsAttrValues(idIt);
if (valList != null) {
String clrword = request.getParameter("clr");//parametre à surligner
if (clrword != null && !clrword.equals("")) {
request.setAttribute("clr", clrword);
for (Yattributevalue av : valList) {
- if (!av.getAttribute().getType().equals("Image") || !av.getAttribute().getType().equals("URL")) {
+ if (!av.getAttribute().getType().equals("Image") && !av.getAttribute().getType().equals("URL")) {
String lowInput = av.getValStr().toUpperCase();
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
lowInput = pattern.matcher(Normalizer.normalize(lowInput, Normalizer.Form.NFD)).replaceAll("");
String lowSub = clrword.toUpperCase();
lowSub = pattern.matcher(Normalizer.normalize(lowSub, Normalizer.Form.NFD)).replaceAll("");
if (lowInput.matches("(?i).*" + lowSub + ".*")) {
av.setValStr(YaceUtils.envelopSubStrings(av.getValStr(), lowInput, lowSub, "<span class=\"search-line\">", "</span>"));
}
}
}
}
Map<String, List<String>> asideHelp = new HashMap<String, List<String>>();
List<String> infoBoxes = new ArrayList<String>();
List<String> tipBoxes = new ArrayList<String>();
infoBoxes.add("Sur cette page, vous voyez le descriptif complet d'un objet.");
tipBoxes.add("Les flèches bleues permettent de naviguer parmi les éléments de la collection courante");
tipBoxes.add("Si vous venez d'effectuer une recherche, l'élément correspondant est surligné");
asideHelp.put("tip", tipBoxes);
asideHelp.put("info", infoBoxes);
int[]tab = YaceUtils.getPrevNextItemId(item);//prev et next
request.setAttribute("asideHelp", YaceUtils.getAsideHelp(asideHelp));
request.setAttribute("canEdit", YaceUtils.canEditItem(item, yuser));
request.setAttribute("canDelete", YaceUtils.canDeleteItem(item, yuser));
request.setAttribute("curItem", item);
request.setAttribute("attributevalues", valList);
request.setAttribute("prevIt", tab[0]);
request.setAttribute("nextIt", tab[1]);
request.setAttribute("pageTitle", "Détails d'un objet de " + item.getCollection().getTheme());
request.setAttribute("pageHeaderTitle", "Détails d'un objet de <strong>" + item.getCollection().getTheme() + "</strong>");
request.getRequestDispatcher(VUE_ITEM).forward(request, response);
}
}
else
{
//l'user ne peut pas consulter cet item
YaceUtils.displayItemError(request, response);
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
public String getServletInfo() {
return "Affichage du détail d'un objet";
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//droits d'acces de l'utilisateur à l'item
//cas user proprietaire item privé
//cas consultation item publique
YitemFacade itemFac = ServicesLocator.getItemFacade();
String idItem = "";
idItem = request.getParameter("item");
if (idItem == null || idItem.isEmpty()) {
YaceUtils.displayItemError(request, response);
} else {
int idIt = Integer.parseInt(idItem);
//gestion permission : public ou privé
//savoir deja si l'item existe
Yitem item = itemFac.find(idIt);
HttpSession session = request.getSession(false);
Yuser yuser = null;
if (session != null) {
yuser = (Yuser) session.getAttribute("user");
}
if (YaceUtils.CanDisplayItem(item, yuser)) {
//liste des attributs de l'item
List<Yattributevalue> valList = itemFac.getItemsAttrValues(idIt);
if (valList != null) {
String clrword = request.getParameter("clr");//parametre à surligner
if (clrword != null && !clrword.equals("")) {
request.setAttribute("clr", clrword);
for (Yattributevalue av : valList) {
if (!av.getAttribute().getType().equals("Image") || !av.getAttribute().getType().equals("URL")) {
String lowInput = av.getValStr().toUpperCase();
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
lowInput = pattern.matcher(Normalizer.normalize(lowInput, Normalizer.Form.NFD)).replaceAll("");
String lowSub = clrword.toUpperCase();
lowSub = pattern.matcher(Normalizer.normalize(lowSub, Normalizer.Form.NFD)).replaceAll("");
if (lowInput.matches("(?i).*" + lowSub + ".*")) {
av.setValStr(YaceUtils.envelopSubStrings(av.getValStr(), lowInput, lowSub, "<span class=\"search-line\">", "</span>"));
}
}
}
}
Map<String, List<String>> asideHelp = new HashMap<String, List<String>>();
List<String> infoBoxes = new ArrayList<String>();
List<String> tipBoxes = new ArrayList<String>();
infoBoxes.add("Sur cette page, vous voyez le descriptif complet d'un objet.");
tipBoxes.add("Les flèches bleues permettent de naviguer parmi les éléments de la collection courante");
tipBoxes.add("Si vous venez d'effectuer une recherche, l'élément correspondant est surligné");
asideHelp.put("tip", tipBoxes);
asideHelp.put("info", infoBoxes);
int[]tab = YaceUtils.getPrevNextItemId(item);//prev et next
request.setAttribute("asideHelp", YaceUtils.getAsideHelp(asideHelp));
request.setAttribute("canEdit", YaceUtils.canEditItem(item, yuser));
request.setAttribute("canDelete", YaceUtils.canDeleteItem(item, yuser));
request.setAttribute("curItem", item);
request.setAttribute("attributevalues", valList);
request.setAttribute("prevIt", tab[0]);
request.setAttribute("nextIt", tab[1]);
request.setAttribute("pageTitle", "Détails d'un objet de " + item.getCollection().getTheme());
request.setAttribute("pageHeaderTitle", "Détails d'un objet de <strong>" + item.getCollection().getTheme() + "</strong>");
request.getRequestDispatcher(VUE_ITEM).forward(request, response);
}
}
else
{
//l'user ne peut pas consulter cet item
YaceUtils.displayItemError(request, response);
}
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//droits d'acces de l'utilisateur à l'item
//cas user proprietaire item privé
//cas consultation item publique
YitemFacade itemFac = ServicesLocator.getItemFacade();
String idItem = "";
idItem = request.getParameter("item");
if (idItem == null || idItem.isEmpty()) {
YaceUtils.displayItemError(request, response);
} else {
int idIt = Integer.parseInt(idItem);
//gestion permission : public ou privé
//savoir deja si l'item existe
Yitem item = itemFac.find(idIt);
HttpSession session = request.getSession(false);
Yuser yuser = null;
if (session != null) {
yuser = (Yuser) session.getAttribute("user");
}
if (YaceUtils.CanDisplayItem(item, yuser)) {
//liste des attributs de l'item
List<Yattributevalue> valList = itemFac.getItemsAttrValues(idIt);
if (valList != null) {
String clrword = request.getParameter("clr");//parametre à surligner
if (clrword != null && !clrword.equals("")) {
request.setAttribute("clr", clrword);
for (Yattributevalue av : valList) {
if (!av.getAttribute().getType().equals("Image") && !av.getAttribute().getType().equals("URL")) {
String lowInput = av.getValStr().toUpperCase();
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
lowInput = pattern.matcher(Normalizer.normalize(lowInput, Normalizer.Form.NFD)).replaceAll("");
String lowSub = clrword.toUpperCase();
lowSub = pattern.matcher(Normalizer.normalize(lowSub, Normalizer.Form.NFD)).replaceAll("");
if (lowInput.matches("(?i).*" + lowSub + ".*")) {
av.setValStr(YaceUtils.envelopSubStrings(av.getValStr(), lowInput, lowSub, "<span class=\"search-line\">", "</span>"));
}
}
}
}
Map<String, List<String>> asideHelp = new HashMap<String, List<String>>();
List<String> infoBoxes = new ArrayList<String>();
List<String> tipBoxes = new ArrayList<String>();
infoBoxes.add("Sur cette page, vous voyez le descriptif complet d'un objet.");
tipBoxes.add("Les flèches bleues permettent de naviguer parmi les éléments de la collection courante");
tipBoxes.add("Si vous venez d'effectuer une recherche, l'élément correspondant est surligné");
asideHelp.put("tip", tipBoxes);
asideHelp.put("info", infoBoxes);
int[]tab = YaceUtils.getPrevNextItemId(item);//prev et next
request.setAttribute("asideHelp", YaceUtils.getAsideHelp(asideHelp));
request.setAttribute("canEdit", YaceUtils.canEditItem(item, yuser));
request.setAttribute("canDelete", YaceUtils.canDeleteItem(item, yuser));
request.setAttribute("curItem", item);
request.setAttribute("attributevalues", valList);
request.setAttribute("prevIt", tab[0]);
request.setAttribute("nextIt", tab[1]);
request.setAttribute("pageTitle", "Détails d'un objet de " + item.getCollection().getTheme());
request.setAttribute("pageHeaderTitle", "Détails d'un objet de <strong>" + item.getCollection().getTheme() + "</strong>");
request.getRequestDispatcher(VUE_ITEM).forward(request, response);
}
}
else
{
//l'user ne peut pas consulter cet item
YaceUtils.displayItemError(request, response);
}
}
}
|
diff --git a/fawkez-code-report-main/src/main/java/org/jcoderz/phoenix/report/FindBugsReportReader.java b/fawkez-code-report-main/src/main/java/org/jcoderz/phoenix/report/FindBugsReportReader.java
index a7e5115..912602a 100644
--- a/fawkez-code-report-main/src/main/java/org/jcoderz/phoenix/report/FindBugsReportReader.java
+++ b/fawkez-code-report-main/src/main/java/org/jcoderz/phoenix/report/FindBugsReportReader.java
@@ -1,270 +1,270 @@
/*
* $Id: FindBugsReportReader.java 1011 2008-06-16 17:57:36Z amandel $
*
* Copyright 2006, The jCoderZ.org Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the jCoderZ.org Project nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jcoderz.phoenix.report;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.xml.bind.JAXBException;
import org.jcoderz.phoenix.findbugs.jaxb.BugCollection;
import org.jcoderz.phoenix.findbugs.jaxb.BugInstance;
import org.jcoderz.phoenix.findbugs.jaxb.Class;
import org.jcoderz.phoenix.findbugs.jaxb.Field;
import org.jcoderz.phoenix.findbugs.jaxb.Int;
import org.jcoderz.phoenix.findbugs.jaxb.Method;
import org.jcoderz.phoenix.findbugs.jaxb.SourceLine;
import org.jcoderz.phoenix.report.jaxb.Item;
import org.jcoderz.phoenix.report.jaxb.ObjectFactory;
/**
*
* @author Michael Griffel
*/
public final class FindBugsReportReader
extends AbstractReportReader
{
/** JAXB context path. */
public static final String FINDBUGS_JAXB_CONTEXT_PATH
= "org.jcoderz.phoenix.findbugs.jaxb";
private static final String CLASSNAME = FindBugsReportReader.class.getName();
private static final Logger logger = Logger.getLogger(CLASSNAME);
private BugCollection mReportDocument;
FindBugsReportReader ()
throws JAXBException
{
super(FINDBUGS_JAXB_CONTEXT_PATH);
}
/** {@inheritDoc} */
public void parse (File f)
throws JAXBException
{
try
{
mReportDocument = (BugCollection) getUnmarshaller().unmarshal(
new JCoverageInputStream(new FileInputStream(f)));
}
catch (IOException e)
{
throw new JAXBException("Cannot read JCoverage report", e);
}
}
/** {@inheritDoc} */
public Map<ResourceInfo, List<Item>> getItems ()
throws JAXBException
{
final Map<ResourceInfo, List<Item>> itemMap = new HashMap<ResourceInfo, List<Item>>();
final List<BugInstance> bugInstances = mReportDocument.getBugInstance();
logger.fine("Found #" + bugInstances.size() + " FindBugs bug instances!");
final List<String> sourceDirs
= mReportDocument.getProject().getSrcDir();
logger.finer("Using source dir '" + sourceDirs + "'");
for (BugInstance bugInstance : bugInstances)
{
- final List<Object> list = bugInstance.getClazzOrFieldOrMethod();
+ final List list = bugInstance.getClazzOrFieldOrMethod();
final Item item = new ObjectFactory().createItem();
final List<String> objectMessageList = new ArrayList<String>();
item.setMessage(bugInstance.getLongMessage());
boolean topLevelSourceLineRead = false;
for (Object element : list)
{
objectMessageList.add(toString(element));
if (element instanceof Class)
{
if (item.isSetOrigin())
{
continue;
}
final Class c = (Class) element;
final String clazz = c.getClassname();
logger.finer("Processing class '" + clazz + "'");
final String javaFile = convertToRelativeJavaFile(clazz);
final ResourceInfo info = findResourceInfo(sourceDirs, javaFile);
if (info != null)
{
List<Item> itemList = itemMap.get(info);
if (itemList == null)
{
itemList = new ArrayList<Item>();
itemMap.put(info, itemList);
}
item.setOrigin(Origin.FINDBUGS);
item.setSeverity(bugInstance.getPriority());
item.setFindingType(bugInstance.getType());
itemList.add(item);
logger.finest("Adding findings for resource " + javaFile);
}
else
{
logger.finer("Ignoring findings for resource " + javaFile);
}
}
else if (element instanceof SourceLine)
{
// Can be more specific info so allow override
// if given data is not concrete.
// There are finders like IL_INFINITE_LOOP which
// report additional SourceLine items that point to
// informative other lines rather than the buginstance.
// Til we know how to get the correct line we should leave it
// like that. (see also http://tinyurl.com/ycol9h ff.)
if (topLevelSourceLineRead
&& item.isSetLine() && item.getLine() > 0)
{
continue;
}
logger.finer("Adding source line information to item "
+ item.getFindingType());
final SourceLine sourceLine = (SourceLine) element;
if (sourceLine.isSetStart())
{
item.setLine(sourceLine.getStart());
topLevelSourceLineRead = true;
if (sourceLine.isSetEnd())
{
item.setEndLine(sourceLine.getEnd());
}
}
}
else if (element instanceof Method)
{
if (item.isSetLine())
{
continue;
}
if (((Method) element).isSetSourceLine())
{
logger.finer("Adding source line information for method"
+ " to item " + item.getFindingType());
final SourceLine sourceLine
= ((Method) element).getSourceLine();
if (sourceLine.isSetStart())
{
item.setLine(sourceLine.getStart());
if (sourceLine.isSetEnd())
{
item.setEndLine(sourceLine.getEnd());
}
}
}
}
}
}
return itemMap;
}
private ResourceInfo findResourceInfo (List<String> sourceDirs, String javaFile)
{
ResourceInfo info = null;
for (String dir : sourceDirs) {
final String srcDir = dir + File.separator;
final String key = normalizeFileName(srcDir + javaFile);
logger.finest("Looking for file: " + key);
info = ResourceInfo.lookup(key);
if (info != null)
{
break;
}
}
return info;
}
private String toString (Object element)
{
final String ret;
if (element instanceof Class)
{
final Class c = (Class) element;
ret = c.getClassname();
}
else if (element instanceof Method)
{
final Method m = (Method) element;
ret = m.getName() + m.getSignature();
}
else if (element instanceof Field)
{
final Field f = (Field) element;
ret = f.getName();
}
else if (element instanceof SourceLine)
{
final SourceLine sl = (SourceLine) element;
ret = sl.getStart() + "-" + sl.getEnd();
}
else if (element instanceof Int)
{
final Int i = (Int) element;
ret = String.valueOf(i.getValue());
}
else
{
ret = String.valueOf(element);
}
return ret;
}
private String convertToRelativeJavaFile (String clzznm)
{
String clazzname = clzznm;
if (clazzname.indexOf('$') != -1) // inner clazz
{
clazzname = clazzname.substring(0, clazzname.indexOf('$'));
}
return clazzname.replace('.', File.separatorChar) + ".java";
}
}
| true | true | public Map<ResourceInfo, List<Item>> getItems ()
throws JAXBException
{
final Map<ResourceInfo, List<Item>> itemMap = new HashMap<ResourceInfo, List<Item>>();
final List<BugInstance> bugInstances = mReportDocument.getBugInstance();
logger.fine("Found #" + bugInstances.size() + " FindBugs bug instances!");
final List<String> sourceDirs
= mReportDocument.getProject().getSrcDir();
logger.finer("Using source dir '" + sourceDirs + "'");
for (BugInstance bugInstance : bugInstances)
{
final List<Object> list = bugInstance.getClazzOrFieldOrMethod();
final Item item = new ObjectFactory().createItem();
final List<String> objectMessageList = new ArrayList<String>();
item.setMessage(bugInstance.getLongMessage());
boolean topLevelSourceLineRead = false;
for (Object element : list)
{
objectMessageList.add(toString(element));
if (element instanceof Class)
{
if (item.isSetOrigin())
{
continue;
}
final Class c = (Class) element;
final String clazz = c.getClassname();
logger.finer("Processing class '" + clazz + "'");
final String javaFile = convertToRelativeJavaFile(clazz);
final ResourceInfo info = findResourceInfo(sourceDirs, javaFile);
if (info != null)
{
List<Item> itemList = itemMap.get(info);
if (itemList == null)
{
itemList = new ArrayList<Item>();
itemMap.put(info, itemList);
}
item.setOrigin(Origin.FINDBUGS);
item.setSeverity(bugInstance.getPriority());
item.setFindingType(bugInstance.getType());
itemList.add(item);
logger.finest("Adding findings for resource " + javaFile);
}
else
{
logger.finer("Ignoring findings for resource " + javaFile);
}
}
else if (element instanceof SourceLine)
{
// Can be more specific info so allow override
// if given data is not concrete.
// There are finders like IL_INFINITE_LOOP which
// report additional SourceLine items that point to
// informative other lines rather than the buginstance.
// Til we know how to get the correct line we should leave it
// like that. (see also http://tinyurl.com/ycol9h ff.)
if (topLevelSourceLineRead
&& item.isSetLine() && item.getLine() > 0)
{
continue;
}
logger.finer("Adding source line information to item "
+ item.getFindingType());
final SourceLine sourceLine = (SourceLine) element;
if (sourceLine.isSetStart())
{
item.setLine(sourceLine.getStart());
topLevelSourceLineRead = true;
if (sourceLine.isSetEnd())
{
item.setEndLine(sourceLine.getEnd());
}
}
}
else if (element instanceof Method)
{
if (item.isSetLine())
{
continue;
}
if (((Method) element).isSetSourceLine())
{
logger.finer("Adding source line information for method"
+ " to item " + item.getFindingType());
final SourceLine sourceLine
= ((Method) element).getSourceLine();
if (sourceLine.isSetStart())
{
item.setLine(sourceLine.getStart());
if (sourceLine.isSetEnd())
{
item.setEndLine(sourceLine.getEnd());
}
}
}
}
}
}
return itemMap;
}
| public Map<ResourceInfo, List<Item>> getItems ()
throws JAXBException
{
final Map<ResourceInfo, List<Item>> itemMap = new HashMap<ResourceInfo, List<Item>>();
final List<BugInstance> bugInstances = mReportDocument.getBugInstance();
logger.fine("Found #" + bugInstances.size() + " FindBugs bug instances!");
final List<String> sourceDirs
= mReportDocument.getProject().getSrcDir();
logger.finer("Using source dir '" + sourceDirs + "'");
for (BugInstance bugInstance : bugInstances)
{
final List list = bugInstance.getClazzOrFieldOrMethod();
final Item item = new ObjectFactory().createItem();
final List<String> objectMessageList = new ArrayList<String>();
item.setMessage(bugInstance.getLongMessage());
boolean topLevelSourceLineRead = false;
for (Object element : list)
{
objectMessageList.add(toString(element));
if (element instanceof Class)
{
if (item.isSetOrigin())
{
continue;
}
final Class c = (Class) element;
final String clazz = c.getClassname();
logger.finer("Processing class '" + clazz + "'");
final String javaFile = convertToRelativeJavaFile(clazz);
final ResourceInfo info = findResourceInfo(sourceDirs, javaFile);
if (info != null)
{
List<Item> itemList = itemMap.get(info);
if (itemList == null)
{
itemList = new ArrayList<Item>();
itemMap.put(info, itemList);
}
item.setOrigin(Origin.FINDBUGS);
item.setSeverity(bugInstance.getPriority());
item.setFindingType(bugInstance.getType());
itemList.add(item);
logger.finest("Adding findings for resource " + javaFile);
}
else
{
logger.finer("Ignoring findings for resource " + javaFile);
}
}
else if (element instanceof SourceLine)
{
// Can be more specific info so allow override
// if given data is not concrete.
// There are finders like IL_INFINITE_LOOP which
// report additional SourceLine items that point to
// informative other lines rather than the buginstance.
// Til we know how to get the correct line we should leave it
// like that. (see also http://tinyurl.com/ycol9h ff.)
if (topLevelSourceLineRead
&& item.isSetLine() && item.getLine() > 0)
{
continue;
}
logger.finer("Adding source line information to item "
+ item.getFindingType());
final SourceLine sourceLine = (SourceLine) element;
if (sourceLine.isSetStart())
{
item.setLine(sourceLine.getStart());
topLevelSourceLineRead = true;
if (sourceLine.isSetEnd())
{
item.setEndLine(sourceLine.getEnd());
}
}
}
else if (element instanceof Method)
{
if (item.isSetLine())
{
continue;
}
if (((Method) element).isSetSourceLine())
{
logger.finer("Adding source line information for method"
+ " to item " + item.getFindingType());
final SourceLine sourceLine
= ((Method) element).getSourceLine();
if (sourceLine.isSetStart())
{
item.setLine(sourceLine.getStart());
if (sourceLine.isSetEnd())
{
item.setEndLine(sourceLine.getEnd());
}
}
}
}
}
}
return itemMap;
}
|
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java
index 7f1bcaea..04bc5ade 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java
@@ -1,284 +1,284 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.impl;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.wst.common.componentcore.internal.ComponentResource;
import org.eclipse.wst.common.componentcore.internal.ComponentcorePackage;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent;
import org.eclipse.wst.common.componentcore.internal.util.IPathProvider;
/**
* <p>
* The following class is experimental until fully documented.
* </p>
*/
public class ResourceTreeNode {
public static final int CREATE_NONE = 0x0;
/**
* Type constant (bit mask value 1) which identifies creating child nodes.
*
*/
public static final int CREATE_TREENODE_IFNEC = 0x1;
/**
* Type constant (bit mask value 2) which identifies always creating a virtual resource.
*
*/
public static final int CREATE_RESOURCE_ALWAYS = 0x2;
private final Set moduleResources = Collections.synchronizedSet(new HashSet());
private final Map children = Collections.synchronizedMap(new HashMap());
private final Map transientChildResources = Collections.synchronizedMap(new HashMap());
private static final ComponentResource[] NO_MODULE_RESOURCES = new ComponentResource[]{};
private IPathProvider pathProvider;
// private ResourceTreeNode parent;
private String pathSegment;
public ResourceTreeNode(String aPathSegment, ResourceTreeNode parent, IPathProvider aPathProvider) {
pathSegment = aPathSegment;
pathProvider = aPathProvider;
}
public ResourceTreeNode addChild(ResourceTreeNode aChild) {
children.put(aChild.getPathSegment(), aChild);
return aChild;
}
public ResourceTreeNode addChild(ComponentResource aModuleResource) {
ResourceTreeNode newChild = findChild(getPathProvider().getPath(aModuleResource), CREATE_TREENODE_IFNEC);
if(newChild != null) {
newChild.addModuleResource(aModuleResource);
return newChild;
}
return null;
}
public ResourceTreeNode removeChild(ResourceTreeNode aChild) {
return (ResourceTreeNode) children.remove(aChild.getPathSegment());
}
public ResourceTreeNode removeChild(ComponentResource aModuleResource) {
ResourceTreeNode containingChild = findChild(getPathProvider().getPath(aModuleResource), CREATE_NONE);
if(containingChild != null) {
containingChild.removeResource(aModuleResource);
if(containingChild.hasModuleResources())
return containingChild;
return removeChild(containingChild);
}
return null;
}
public ResourceTreeNode removeChild(IPath targetPath, ComponentResource aModuleResource) {
ResourceTreeNode containingChild = findChild(targetPath, CREATE_NONE);
if(containingChild != null) {
containingChild.removeResource(aModuleResource);
if(containingChild.hasModuleResources())
return containingChild;
return removeChild(containingChild);
}
return null;
}
public void removeResource(ComponentResource aResource) {
moduleResources.remove(aResource);
}
public ResourceTreeNode findChild(IPath aPath) {
return findChild(aPath, CREATE_TREENODE_IFNEC);
}
public ResourceTreeNode findChild(IPath aPath, int creationFlags) {
if(aPath == null)
return null;
ResourceTreeNode child = this;
if (aPath.segmentCount() > 0) {
child = findChild(aPath.segment(0), creationFlags);
if (child == null)
return null;
if (aPath.segmentCount() == 1)
return child;
child = child.findChild(aPath.removeFirstSegments(1), creationFlags);
}
return child;
}
public ResourceTreeNode findChild(String aPathSegment) {
if (aPathSegment == null || aPathSegment.length() == 0)
return this;
return findChild(aPathSegment, CREATE_NONE);
}
public ResourceTreeNode findChild(String aPathSegment, int creationFlags) {
boolean toCreateChildIfNecessary = (creationFlags & CREATE_TREENODE_IFNEC) == CREATE_TREENODE_IFNEC;
ResourceTreeNode childNode = (ResourceTreeNode) children.get(aPathSegment);
if (childNode == null && toCreateChildIfNecessary)
childNode = addChild(aPathSegment);
return childNode;
}
public ComponentResource[] findModuleResources(IPath aPath, int creationFlags) {
Set foundModuleResources = findModuleResourcesSet(aPath, aPath, creationFlags);
if (foundModuleResources.size() == 0)
return NO_MODULE_RESOURCES;
return (ComponentResource[]) foundModuleResources.toArray(new ComponentResource[foundModuleResources.size()]);
}
public boolean exists(IPath aPath, int creationFlags) {
Set foundModuleResources = findModuleResourcesSet(aPath, aPath, creationFlags);
if (foundModuleResources.size() == 0) {
if (true) {
ResourceTreeNode child = findChild(aPath.segment(0), creationFlags);
if (child != null)
return true;
}
return false;
}
return true;
}
public boolean hasModuleResources() {
return moduleResources.size() > 0;
}
public ComponentResource[] getModuleResources() {
return (ComponentResource[]) moduleResources.toArray(new ComponentResource[moduleResources.size()]);
}
private Set findModuleResourcesSet(IPath aFullPath, IPath aPath, int creationFlags) {
if (aPath.segmentCount() == 0) {
Set resources = aggregateResources(new HashSet());
return resources;
}
ResourceTreeNode child = findChild(aPath.segment(0), creationFlags);
if (child == null)
return findMatchingVirtualPathsSet(aFullPath, aPath, creationFlags);
Set foundResources = new HashSet();
foundResources.addAll(child.findModuleResourcesSet(aFullPath, aPath.removeFirstSegments(1), creationFlags));
foundResources.addAll(findMatchingVirtualPathsSet(aFullPath, aPath, creationFlags));
return foundResources;
}
private Set findMatchingVirtualPathsSet(IPath aFullPath, IPath aPath, int creationFlags) {
boolean toCreateResourceAlways = (creationFlags & CREATE_RESOURCE_ALWAYS) == CREATE_RESOURCE_ALWAYS;
if (hasModuleResources()) {
ComponentResource moduleResource = null;
IResource eclipseResource = null;
IContainer eclipseContainer = null;
Set resultSet = new HashSet();
for (Iterator resourceIter = moduleResources.iterator(); resourceIter.hasNext();) {
moduleResource = (ComponentResource) resourceIter.next();
if(moduleResource.getRuntimePath() != null && moduleResource.eResource() != null) {
eclipseResource = StructureEdit.getEclipseResource(moduleResource);
if (eclipseResource != null && (eclipseResource.getType() == IResource.FOLDER || eclipseResource.getType() == IResource.PROJECT)) {
eclipseContainer = (IContainer) eclipseResource;
IPath runtimeURI = moduleResource.getRuntimePath().append(aPath);
IPath srcPath = eclipseContainer.getProjectRelativePath().append(aPath);
// check for existing subpath in tree
ComponentResource newResource = findExistingComponentResource(moduleResource.getComponent(), runtimeURI, srcPath);
// add new resource if null
if(newResource == null) {
// flesh out the tree
IResource eclipseRes = eclipseContainer.findMember(aPath);
if ((toCreateResourceAlways) || (eclipseRes != null)) {
- newResource = (ComponentResource)transientChildResources.get(aPath);
+ newResource = (ComponentResource)transientChildResources.get(srcPath);
if (newResource == null) {
newResource = ComponentcorePackage.eINSTANCE.getComponentcoreFactory().createComponentResource();
// Not setting the parent on this transient child resource
// newResource.setComponent(moduleResource.getComponent());
newResource.setRuntimePath(runtimeURI);
newResource.setSourcePath(srcPath);
if (eclipseRes != null)
newResource.setOwningProject(eclipseRes.getProject());
- transientChildResources.put(aPath,newResource);
+ transientChildResources.put(srcPath,newResource);
}
resultSet.add(newResource);
}
}
}
}
}
return resultSet.size() > 0 ? resultSet : Collections.EMPTY_SET;
}
return Collections.EMPTY_SET;
}
private ComponentResource findExistingComponentResource(WorkbenchComponent component, IPath runtimeURI, IPath srcPath) {
List resources = component.getResources();
for (Iterator iter = resources.iterator(); iter.hasNext();) {
ComponentResource element = (ComponentResource) iter.next();
if(runtimeURI.equals(element.getRuntimePath()) && srcPath.equals(element.getSourcePath()))
return element;
}
return null;
}
private Set aggregateResources(Set anAggregationSet) {
if (hasModuleResources())
anAggregationSet.addAll(moduleResources);
ResourceTreeNode childNode = null;
for (Iterator childrenIterator = children.values().iterator(); childrenIterator.hasNext();) {
childNode = (ResourceTreeNode) childrenIterator.next();
childNode.aggregateResources(anAggregationSet);
}
return anAggregationSet;
}
public int childrenCount() {
return children.size();
}
public String getPathSegment() {
return pathSegment;
}
protected ResourceTreeNode addChild(String aPathSegment) {
ResourceTreeNode newChild = null;
if ((newChild = (ResourceTreeNode) children.get(aPathSegment)) == null) {
newChild = new ResourceTreeNode(aPathSegment, this, pathProvider);
children.put(newChild.getPathSegment(), newChild);
}
return newChild;
}
protected ResourceTreeNode removeChild(String aPathSegment) {
return (ResourceTreeNode) children.remove(aPathSegment);
}
/* package */void addModuleResource(ComponentResource aModuleResource) {
moduleResources.add(aModuleResource);
}
/* package */IPathProvider getPathProvider() {
return pathProvider;
}
}
| false | true | private Set findMatchingVirtualPathsSet(IPath aFullPath, IPath aPath, int creationFlags) {
boolean toCreateResourceAlways = (creationFlags & CREATE_RESOURCE_ALWAYS) == CREATE_RESOURCE_ALWAYS;
if (hasModuleResources()) {
ComponentResource moduleResource = null;
IResource eclipseResource = null;
IContainer eclipseContainer = null;
Set resultSet = new HashSet();
for (Iterator resourceIter = moduleResources.iterator(); resourceIter.hasNext();) {
moduleResource = (ComponentResource) resourceIter.next();
if(moduleResource.getRuntimePath() != null && moduleResource.eResource() != null) {
eclipseResource = StructureEdit.getEclipseResource(moduleResource);
if (eclipseResource != null && (eclipseResource.getType() == IResource.FOLDER || eclipseResource.getType() == IResource.PROJECT)) {
eclipseContainer = (IContainer) eclipseResource;
IPath runtimeURI = moduleResource.getRuntimePath().append(aPath);
IPath srcPath = eclipseContainer.getProjectRelativePath().append(aPath);
// check for existing subpath in tree
ComponentResource newResource = findExistingComponentResource(moduleResource.getComponent(), runtimeURI, srcPath);
// add new resource if null
if(newResource == null) {
// flesh out the tree
IResource eclipseRes = eclipseContainer.findMember(aPath);
if ((toCreateResourceAlways) || (eclipseRes != null)) {
newResource = (ComponentResource)transientChildResources.get(aPath);
if (newResource == null) {
newResource = ComponentcorePackage.eINSTANCE.getComponentcoreFactory().createComponentResource();
// Not setting the parent on this transient child resource
// newResource.setComponent(moduleResource.getComponent());
newResource.setRuntimePath(runtimeURI);
newResource.setSourcePath(srcPath);
if (eclipseRes != null)
newResource.setOwningProject(eclipseRes.getProject());
transientChildResources.put(aPath,newResource);
}
resultSet.add(newResource);
}
}
}
}
}
return resultSet.size() > 0 ? resultSet : Collections.EMPTY_SET;
}
return Collections.EMPTY_SET;
}
| private Set findMatchingVirtualPathsSet(IPath aFullPath, IPath aPath, int creationFlags) {
boolean toCreateResourceAlways = (creationFlags & CREATE_RESOURCE_ALWAYS) == CREATE_RESOURCE_ALWAYS;
if (hasModuleResources()) {
ComponentResource moduleResource = null;
IResource eclipseResource = null;
IContainer eclipseContainer = null;
Set resultSet = new HashSet();
for (Iterator resourceIter = moduleResources.iterator(); resourceIter.hasNext();) {
moduleResource = (ComponentResource) resourceIter.next();
if(moduleResource.getRuntimePath() != null && moduleResource.eResource() != null) {
eclipseResource = StructureEdit.getEclipseResource(moduleResource);
if (eclipseResource != null && (eclipseResource.getType() == IResource.FOLDER || eclipseResource.getType() == IResource.PROJECT)) {
eclipseContainer = (IContainer) eclipseResource;
IPath runtimeURI = moduleResource.getRuntimePath().append(aPath);
IPath srcPath = eclipseContainer.getProjectRelativePath().append(aPath);
// check for existing subpath in tree
ComponentResource newResource = findExistingComponentResource(moduleResource.getComponent(), runtimeURI, srcPath);
// add new resource if null
if(newResource == null) {
// flesh out the tree
IResource eclipseRes = eclipseContainer.findMember(aPath);
if ((toCreateResourceAlways) || (eclipseRes != null)) {
newResource = (ComponentResource)transientChildResources.get(srcPath);
if (newResource == null) {
newResource = ComponentcorePackage.eINSTANCE.getComponentcoreFactory().createComponentResource();
// Not setting the parent on this transient child resource
// newResource.setComponent(moduleResource.getComponent());
newResource.setRuntimePath(runtimeURI);
newResource.setSourcePath(srcPath);
if (eclipseRes != null)
newResource.setOwningProject(eclipseRes.getProject());
transientChildResources.put(srcPath,newResource);
}
resultSet.add(newResource);
}
}
}
}
}
return resultSet.size() > 0 ? resultSet : Collections.EMPTY_SET;
}
return Collections.EMPTY_SET;
}
|
diff --git a/beansbinding/src/javax/beans/binding/BeanProperty.java b/beansbinding/src/javax/beans/binding/BeanProperty.java
index 5ebc8ac..4980d3e 100644
--- a/beansbinding/src/javax/beans/binding/BeanProperty.java
+++ b/beansbinding/src/javax/beans/binding/BeanProperty.java
@@ -1,686 +1,686 @@
/*
* Copyright (C) 2006-2007 Sun Microsystems, Inc. All rights reserved. Use is
* subject to license terms.
*/
package javax.beans.binding;
import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.ConcurrentModificationException;
import com.sun.java.util.ObservableMap;
import com.sun.java.util.ObservableMapListener;
/**
* @author Shannon Hickey
*/
public final class BeanProperty implements Property<Object, Object> {
private final PropertyPath path;
private Object source;
private Object[] cache;
private Object cachedValue;
private PropertyChangeSupport support;
private boolean isListening = false;
private ChangeHandler changeHandler;
private boolean ignoreChange;
private static final Object UNREADABLE = new Object();
/**
* @throws IllegalArgumentException for empty or {@code null} path.
*/
public BeanProperty(String path) {
this(path, null);
}
/**
* @throws IllegalArgumentException for empty or {@code null} path.
*/
public BeanProperty(String path, Object source) {
this.path = PropertyPath.createPropertyPath(path);
this.source = source;
}
public void setSource(Object source) {
this.source = source;
if (isListening) {
cachedValueChanged(0);
}
};
public Object getSource() {
return source;
}
private Object getLastSource() {
if (source == null) {
System.err.println("LOG: source is null");
return null;
}
Object src = source;
for (int i = 0; i < path.length() - 1; i++) {
src = getProperty(src, path.get(i));
if (src == null) {
System.err.println("LOG: missing source");
return null;
}
if (src == UNREADABLE) {
System.err.println("LOG: missing read method in chain");
return null;
}
}
return src;
}
public Class<?> getValueType() {
int pathLength = path.length();
if (isListening) {
validateCache(-1);
return getType(cache[pathLength - 1], path.getLast());
}
Object src = getLastSource();
if (src == null) {
throw new IllegalStateException("Unreadable and unwritable");
}
src = getType(src, path.getLast());
if (src == null) {
System.err.println("LOG: missing read or write method");
throw new IllegalStateException("Unreadable and unwritable");
}
return (Class<?>)src;
}
public Object getValue() {
int pathLength = path.length();
if (isListening) {
validateCache(-1);
return cachedValue;
}
Object src = getLastSource();
if (src == null) {
throw new IllegalStateException("Unreadable");
}
src = getProperty(src, path.getLast());
if (src == UNREADABLE) {
System.err.println("LOG: missing read method");
throw new IllegalStateException("Unreadable");
}
return src;
}
public void setValue(Object value) {
int pathLength = path.length();
if (isListening) {
validateCache(-1);
setProperty(cache[pathLength - 1], path.getLast(), value);
updateCachedValue();
} else {
if (source == null) {
System.err.println("LOG: source is null");
throw new IllegalStateException("Unwritable");
}
Object src = getLastSource();
if (src == null) {
throw new IllegalStateException("Unwritable");
}
setProperty(src, path.getLast(), value);
}
}
public boolean isReadable() {
if (isListening) {
}
Object src = getLastSource();
if (src == null) {
return false;
}
PropertyDescriptor pd = getPropertyDescriptor(src, path.getLast());
if (pd == null || pd.getReadMethod() == null) {
System.err.println("LOG: missing read method");
return false;
}
return true;
}
public boolean isWriteable() {
if (isListening) {
}
Object src = getLastSource();
if (src == null) {
return false;
}
PropertyDescriptor pd = getPropertyDescriptor(src, path.getLast());
if (pd == null || pd.getWriteMethod() == null) {
System.err.println("LOG: missing write method");
return false;
}
return true;
}
private void maybeStartListening() {
if (!isListening && getPropertyChangeListeners().length != 0) {
startListening();
}
}
private void startListening() {
isListening = true;
if (cache == null) {
cache = new Object[path.length()];
}
cache[0] = UNREADABLE;
updateListeners(0);
cachedValue = getProperty(cache[path.length() - 1], path.getLast());
}
private void maybeStopListening() {
if (isListening && getPropertyChangeListeners().length == 0) {
stopListening();
}
}
private void stopListening() {
isListening = false;
if (changeHandler != null) {
for (int i = 0; i < path.length(); i++) {
unregisterListener(cache[i], path.get(i));
cache[i] = null;
}
}
cachedValue = null;
changeHandler = null;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
if (support == null) {
support = new PropertyChangeSupport(this);
}
support.addPropertyChangeListener(listener);
maybeStartListening();
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
if (support == null) {
support = new PropertyChangeSupport(this);
}
support.addPropertyChangeListener(propertyName, listener);
maybeStartListening();
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
if (support == null) {
return;
}
support.removePropertyChangeListener(listener);
maybeStopListening();
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
if (support == null) {
return;
}
support.removePropertyChangeListener(propertyName, listener);
maybeStopListening();
}
public PropertyChangeListener[] getPropertyChangeListeners() {
if (support == null) {
return new PropertyChangeListener[0];
}
return support.getPropertyChangeListeners();
}
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
if (support == null) {
return new PropertyChangeListener[0];
}
return support.getPropertyChangeListeners(propertyName);
}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (support == null || support.getPropertyChangeListeners().length == 0) {
return;
}
if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
return;
}
support.firePropertyChange(propertyName, oldValue, newValue);
}
public String toString() {
String className = (source == null ? "" : source.getClass().getName());
return className + path;
}
/**
* @throws PropertyResolverException
*/
private PropertyDescriptor getPropertyDescriptor(Object object, String string) {
BeanInfo info;
try {
info = Introspector.getBeanInfo(object.getClass(), Introspector.IGNORE_ALL_BEANINFO);
} catch (IntrospectionException ie) {
throw new PropertyResolverException("Exception accessing " + object.getClass().getName() + "." + string,
source, path.toString(), ie);
}
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (!(pd instanceof IndexedPropertyDescriptor) && pd.getName().equals(string)) {
return pd;
}
}
return null;
}
/**
* @throws PropertyResolverException
*/
private Object getProperty(Object object, String string) {
if (object == null || object == UNREADABLE) {
return null;
}
if (object instanceof Map) {
return ((Map)object).get(string);
}
PropertyDescriptor pd = getPropertyDescriptor(object, string);
Method readMethod = null;
if (pd == null || (readMethod = pd.getReadMethod()) == null) {
return UNREADABLE;
}
Exception reason = null;
try {
return readMethod.invoke(object);
} catch (IllegalArgumentException ex) {
reason = ex;
} catch (IllegalAccessException ex) {
reason = ex;
} catch (InvocationTargetException ex) {
reason = ex;
}
throw new PropertyResolverException("Exception reading " + object.getClass().getName() + "." + string,
source, path.toString(), reason);
}
private static String capitalize(String name) {
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
/**
* @throws PropertyResolverException
*/
private Class<?> getType(Object object, String string) {
assert object != null;
if (object instanceof Map) {
return Object.class;
}
PropertyDescriptor pd = getPropertyDescriptor(object, string);
if (pd == null) {
return null;
}
return pd.getPropertyType();
}
/**
* @throws PropertyResolverException
* @throws IllegalStateException
*/
private void setProperty(Object object, String propertyName, Object value) {
assert object != null;
try {
ignoreChange = true;
if (object instanceof Map) {
((Map)object).put(propertyName, value);
return;
}
PropertyDescriptor pd = getPropertyDescriptor(object, propertyName);
Method writeMethod = null;
if (pd == null || (writeMethod = pd.getWriteMethod()) == null) {
System.err.println("missing write method");
throw new IllegalStateException("Unwritable");
}
Exception reason;
try {
writeMethod.invoke(object, value);
return;
} catch (IllegalArgumentException ex) {
reason = ex;
} catch (InvocationTargetException ex) {
reason = ex;
} catch (IllegalAccessException ex) {
reason = ex;
}
throw new PropertyResolverException("Exception writing " + object.getClass().getName() + "." + propertyName,
source, path.toString(), reason);
} finally {
ignoreChange = false;
}
}
private void updateListeners(int index) {
boolean loggedYet = false;
if (index == 0) {
if (cache[0] != source) {
unregisterListener(cache[0], path.get(0));
cache[0] = source;
if (source == null) {
loggedYet = true;
System.err.println("LOG: source is null");
} else {
registerListener(source, path.get(0));
}
}
index++;
}
for (int i = index; i < path.length(); i++) {
Object old = cache[i];
- Object sourceValue = getProperty(cache[index - 1], path.get(index - 1));
+ Object sourceValue = getProperty(cache[i - 1], path.get(i - 1));
if (sourceValue != old) {
unregisterListener(old, path.get(i));
cache[i] = sourceValue;
if (sourceValue == null) {
if (!loggedYet) {
loggedYet = true;
System.err.println("LOG: missing source");
}
} else if (sourceValue == UNREADABLE) {
if (!loggedYet) {
loggedYet = true;
System.err.println("LOG: missing read method");
}
} else {
registerListener(sourceValue, path.get(i));
}
}
}
}
private void registerListener(Object source, String property) {
System.out.println("Added listener for " + gs(source) + "." + property);
if (source != null && source != UNREADABLE) {
if (source instanceof ObservableMap) {
((ObservableMap)source).addObservableMapListener(
getChangeHandler());
} else {
addPropertyChangeListener(source, property);
}
}
}
private static String gs(Object source) {
if (source == null) {
return "null";
} else if (source == UNREADABLE) {
return "UNREADABLE";
} else {
return source.getClass().getName();
}
}
/**
* @throws PropertyResolverException
*/
private void unregisterListener(Object source, String property) {
System.out.println("Removed listener for " + gs(source) + "." + property);
if (changeHandler != null && source != null && source != UNREADABLE) {
// PENDING: optimize this and cache
if (source instanceof ObservableMap) {
((ObservableMap)source).removeObservableMapListener(
getChangeHandler());
} else {
removePropertyChangeListener(source, property);
}
}
}
/**
* @throws PropertyResolverException
*/
private void addPropertyChangeListener(Object source, String property) {
// PENDING: optimize this and cache
Exception reason = null;
try {
Method addPCL = source.getClass().getMethod(
"addPropertyChangeListener",
String.class, PropertyChangeListener.class);
addPCL.invoke(source, property, getChangeHandler());
} catch (SecurityException ex) {
reason = ex;
} catch (IllegalArgumentException ex) {
reason = ex;
} catch (InvocationTargetException ex) {
reason = ex;
} catch (IllegalAccessException ex) {
reason = ex;
} catch (NoSuchMethodException ex) {
// No addPCL(String,PCL), look for addPCL(PCL)
try {
Method addPCL = source.getClass().getMethod(
"addPropertyChangeListener",
PropertyChangeListener.class);
addPCL.invoke(source, getChangeHandler());
} catch (SecurityException ex2) {
reason = ex2;
} catch (IllegalArgumentException ex2) {
reason = ex2;
} catch (InvocationTargetException ex2) {
reason = ex2;
} catch (IllegalAccessException ex2) {
reason = ex2;
} catch (NoSuchMethodException ex2) {
// No addPCL(String,PCL), or addPCL(PCL), should log.
}
}
if (reason != null) {
throw new PropertyResolverException(
"Unable to register propertyChangeListener " + property + " " + source,
source, path.toString(), reason);
}
}
/**
* @throws PropertyResolverException
*/
private void removePropertyChangeListener(Object source, String property) {
Exception reason = null;
try {
Method removePCL = source.getClass().getMethod(
"removePropertyChangeListener",
String.class, PropertyChangeListener.class);
removePCL.invoke(source, property, changeHandler);
} catch (SecurityException ex) {
reason = ex;
} catch (IllegalArgumentException ex) {
reason = ex;
} catch (InvocationTargetException ex) {
reason = ex;
} catch (IllegalAccessException ex) {
reason = ex;
} catch (NoSuchMethodException ex) {
// No removePCL(String,PCL), try removePCL(PCL)
try {
Method removePCL = source.getClass().getMethod(
"removePropertyChangeListener",
PropertyChangeListener.class);
removePCL.invoke(source, changeHandler);
} catch (SecurityException ex2) {
reason = ex2;
} catch (IllegalArgumentException ex2) {
reason = ex2;
} catch (InvocationTargetException ex2) {
reason = ex2;
} catch (IllegalAccessException ex2) {
reason = ex2;
} catch (NoSuchMethodException ex2) {
}
}
if (reason != null) {
throw new PropertyResolverException(
"Unable to remove propertyChangeListener " + property + " " + source,
source, path.toString(), reason);
}
}
private int getSourceIndex(Object source) {
for (int i = 0; i < cache.length; i++) {
if (cache[i] == source) {
return i;
}
}
return -1;
}
private void validateCache(int ignore) {
for (int i = 0; i < path.length() - 1; i++) {
if (i == ignore - 1) {
continue;
}
Object source = cache[i];
if (source == null) {
return;
}
Object next = getProperty(source, path.get(i));
if (next != cache[i + 1]) {
throw new ConcurrentModificationException();
}
}
if (path.length() != ignore) {
Object next = getProperty(cache[path.length() - 1], path.getLast());
if (cachedValue != next) {
throw new ConcurrentModificationException();
}
}
}
private void updateCachedValue() {
Object oldValue = cachedValue;
cachedValue = getProperty(cache[path.length() - 1], path.getLast());
firePropertyChange("value", oldValue, cachedValue);
}
private void cachedValueChanged(int index) {
validateCache(index);
int pathLength = path.length();
updateListeners(index);
updateCachedValue();
}
private void mapValueChanged(ObservableMap map, Object key) {
if (!ignoreChange) {
int index = getSourceIndex(map);
if (index != -1) {
if (key.equals(path.get(index))) {
cachedValueChanged(index + 1);
}
} else {
throw new AssertionError();
}
}
}
private ChangeHandler getChangeHandler() {
if (changeHandler== null) {
changeHandler = new ChangeHandler();
}
return changeHandler;
}
private final class ChangeHandler implements PropertyChangeListener,
ObservableMapListener {
public void propertyChange(PropertyChangeEvent e) {
if (!ignoreChange) {
Object source = e.getSource();
int index = getSourceIndex(e.getSource());
if (index != -1) {
String propertyName = e.getPropertyName();
if (propertyName == null ||
path.get(index).equals(propertyName)) {
Object newValue = e.getNewValue();
cachedValueChanged(index + 1);
}
} else {
throw new AssertionError();
}
}
}
public void mapKeyValueChanged(ObservableMap map, Object key, Object lastValue) {
mapValueChanged(map, key);
}
public void mapKeyAdded(ObservableMap map, Object key) {
mapValueChanged(map, key);
}
public void mapKeyRemoved(ObservableMap map, Object key, Object value) {
mapValueChanged(map, key);
}
}
}
| true | true | private void updateListeners(int index) {
boolean loggedYet = false;
if (index == 0) {
if (cache[0] != source) {
unregisterListener(cache[0], path.get(0));
cache[0] = source;
if (source == null) {
loggedYet = true;
System.err.println("LOG: source is null");
} else {
registerListener(source, path.get(0));
}
}
index++;
}
for (int i = index; i < path.length(); i++) {
Object old = cache[i];
Object sourceValue = getProperty(cache[index - 1], path.get(index - 1));
if (sourceValue != old) {
unregisterListener(old, path.get(i));
cache[i] = sourceValue;
if (sourceValue == null) {
if (!loggedYet) {
loggedYet = true;
System.err.println("LOG: missing source");
}
} else if (sourceValue == UNREADABLE) {
if (!loggedYet) {
loggedYet = true;
System.err.println("LOG: missing read method");
}
} else {
registerListener(sourceValue, path.get(i));
}
}
}
}
| private void updateListeners(int index) {
boolean loggedYet = false;
if (index == 0) {
if (cache[0] != source) {
unregisterListener(cache[0], path.get(0));
cache[0] = source;
if (source == null) {
loggedYet = true;
System.err.println("LOG: source is null");
} else {
registerListener(source, path.get(0));
}
}
index++;
}
for (int i = index; i < path.length(); i++) {
Object old = cache[i];
Object sourceValue = getProperty(cache[i - 1], path.get(i - 1));
if (sourceValue != old) {
unregisterListener(old, path.get(i));
cache[i] = sourceValue;
if (sourceValue == null) {
if (!loggedYet) {
loggedYet = true;
System.err.println("LOG: missing source");
}
} else if (sourceValue == UNREADABLE) {
if (!loggedYet) {
loggedYet = true;
System.err.println("LOG: missing read method");
}
} else {
registerListener(sourceValue, path.get(i));
}
}
}
}
|
diff --git a/src/org/matheusdev/ror/RuinsOfRevenge.java b/src/org/matheusdev/ror/RuinsOfRevenge.java
index 4ae9255..7203a36 100644
--- a/src/org/matheusdev/ror/RuinsOfRevenge.java
+++ b/src/org/matheusdev/ror/RuinsOfRevenge.java
@@ -1,177 +1,178 @@
/*
* Copyright (c) 2013 matheusdev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.matheusdev.ror;
import java.io.IOException;
import java.util.Stack;
import org.matheusdev.ror.screens.AbstractScreen;
import org.matheusdev.ror.screens.ScreenMenu;
import org.matheusdev.util.Config;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.bitfire.utils.ShaderLoader;
/**
* @author matheusdev
*
*/
public class RuinsOfRevenge extends Game implements InputProcessor {
public static void main(String[] args) {
new LwjglApplication(
new RuinsOfRevenge(),
"matheusdev: Ruins Of Revenge",
Config.get().resolutionX,
Config.get().resolutionY,
true);
}
private ResourceLoader res;
private Stack<AbstractScreen> screens;
private Stack<AbstractScreen> drawStack;
private final Color darkenColor = new Color(1f, 1f, 1f, 0.6f);
@Override
public void create() {
ShaderLoader.BasePath = "data/shaders/";
screens = new Stack<>();
drawStack = new Stack<>();
try {
res = new ResourceLoader(Gdx.files.internal("data/sprites/resources.xml"));
} catch (IOException e) {
e.printStackTrace();
}
pushScreen(new ScreenMenu(res, this));
Gdx.graphics.setVSync(true);
Gdx.input.setInputProcessor(this);
}
@Override
public void render() {
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 0f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
prepareDrawStack();
updateDrawStack(Gdx.graphics.getDeltaTime());
}
private void prepareDrawStack() {
for (int i = screens.size()-1; i >= 0; i--) {
AbstractScreen screen = screens.get(i);
drawStack.push(screen);
if (!screen.isParentVisible()) {
break;
}
}
}
private void updateDrawStack(float delta) {
while (drawStack.size() > 1) {
AbstractScreen screen = drawStack.pop();
Stage stage = screen.getStage();
// if it's the last element (topmost screen)
stage.getSpriteBatch().setColor(Color.WHITE);
screen.update(delta);
}
AbstractScreen topScreen = drawStack.pop();
Stage stage = topScreen.getStage();
stage.getSpriteBatch().enableBlending();
stage.getSpriteBatch().setColor(darkenColor);
stage.getSpriteBatch().begin();
stage.getSpriteBatch().draw(res.getRegion("white"), 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stage.getSpriteBatch().end();
+ stage.getSpriteBatch().setColor(Color.WHITE);
topScreen.update(delta);
}
@Override
public void resize(int width, int height) {
Gdx.gl.glViewport(0, 0, width, height);
for (AbstractScreen screen : screens) {
screen.resize(width, height);
}
Config.get().setRes(width, height);
}
@Override
public void dispose() {
res.dispose();
}
public AbstractScreen popScreen() {
AbstractScreen popped = screens.pop();
return popped;
}
public void pushScreen(AbstractScreen screen) {
screens.add(screen);
}
@Override
public boolean keyDown(int keycode) {
return screens.peek().keyDown(keycode);
}
@Override
public boolean keyUp(int keycode) {
return screens.peek().keyUp(keycode);
}
@Override
public boolean keyTyped(char character) {
return screens.peek().keyTyped(character);
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return screens.peek().touchDown(screenX, screenY, pointer, button);
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return screens.peek().touchUp(screenX, screenY, pointer, button);
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return screens.peek().touchDragged(screenX, screenY, pointer);
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return screens.peek().mouseMoved(screenX, screenY);
}
@Override
public boolean scrolled(int amount) {
return screens.peek().scrolled(amount);
}
}
| true | true | private void updateDrawStack(float delta) {
while (drawStack.size() > 1) {
AbstractScreen screen = drawStack.pop();
Stage stage = screen.getStage();
// if it's the last element (topmost screen)
stage.getSpriteBatch().setColor(Color.WHITE);
screen.update(delta);
}
AbstractScreen topScreen = drawStack.pop();
Stage stage = topScreen.getStage();
stage.getSpriteBatch().enableBlending();
stage.getSpriteBatch().setColor(darkenColor);
stage.getSpriteBatch().begin();
stage.getSpriteBatch().draw(res.getRegion("white"), 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stage.getSpriteBatch().end();
topScreen.update(delta);
}
| private void updateDrawStack(float delta) {
while (drawStack.size() > 1) {
AbstractScreen screen = drawStack.pop();
Stage stage = screen.getStage();
// if it's the last element (topmost screen)
stage.getSpriteBatch().setColor(Color.WHITE);
screen.update(delta);
}
AbstractScreen topScreen = drawStack.pop();
Stage stage = topScreen.getStage();
stage.getSpriteBatch().enableBlending();
stage.getSpriteBatch().setColor(darkenColor);
stage.getSpriteBatch().begin();
stage.getSpriteBatch().draw(res.getRegion("white"), 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stage.getSpriteBatch().end();
stage.getSpriteBatch().setColor(Color.WHITE);
topScreen.update(delta);
}
|
diff --git a/MutualFund/src/controller/EmployeeTransitionDayAction.java b/MutualFund/src/controller/EmployeeTransitionDayAction.java
index 9510a2e..6cb2922 100644
--- a/MutualFund/src/controller/EmployeeTransitionDayAction.java
+++ b/MutualFund/src/controller/EmployeeTransitionDayAction.java
@@ -1,336 +1,336 @@
/**
* @author Team Snipers (Team 1)
* Jan 26, 2013
*/
package controller;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import databean.CustomerBean;
import databean.FundGeneralInfoBean;
import databean.FundPriceHistoryBean;
import databean.PendingTransactionBean;
import databean.PositionBean;
import databean.TransactionBean;
import formbean.TransitionDayForm;
import model.CustomerDAO;
import model.FundPriceHistoryDAO;
import model.Model;
import model.MyDAOException;
import model.PositionDAO;
import model.TransactionDAO;
public class EmployeeTransitionDayAction extends Action {
private CustomerDAO customerDAO;
private FundPriceHistoryDAO fundPriceHistoryDAO;
private PositionDAO positionDAO;
private TransactionDAO transactionDAO;
public EmployeeTransitionDayAction(Model model) {
customerDAO = model.getCustomerDAO();
fundPriceHistoryDAO = model.getFundPriceHistoryDAO();
positionDAO = model.getPositionDAO();
transactionDAO = model.getTransactionDAO();
}
public String getName() { return "employee-transitionday.do"; }
public String perform(HttpServletRequest request) {
List<String> errors = new ArrayList<String>();
request.setAttribute("errors",errors);
try {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
// Get last dates of transaction and fund price history. Set later one as last trading date.
Date lastDateTransaction = transactionDAO.getLastTradingDateOfALLTransactions();
Date lastDateFund = fundPriceHistoryDAO.getLastTradingDateOfALLFunds();
Date lastDate;
if (lastDateTransaction == null) {
lastDate = lastDateFund;
} else if (lastDateFund == null) {
lastDate = lastDateTransaction;
} else {
lastDate = lastDateTransaction.after(lastDateFund) ? lastDateTransaction : lastDateFund;
}
if (lastDate == null) {
request.setAttribute("lastDate", "No last trading day");
} else {
request.setAttribute("lastDate", df.format(lastDate));
}
// Set default date as tomorrow if last date exists. Otherwise, set today as default day.
Date defaultDate = lastDate != null ? getTomorrow(lastDate) : new Date();
request.setAttribute("defaultDate", df.format(defaultDate));
//get full fund list, allows customer to choose
FundGeneralInfoBean[] fundGeneralList = fundPriceHistoryDAO.getAllFundsGeneralInfo();
request.setAttribute("fundGeneralList", fundGeneralList);
int len = fundGeneralList == null ? 0: fundGeneralList.length;
request.setAttribute("fundListLength", len);
TransitionDayForm form = new TransitionDayForm(request);
request.setAttribute("form",form);
// If no params were passed, return with no errors so that the form will be
// presented (we assume for the first time).
if (!form.isPresent()) {
return "employee-transitionday.jsp";
}
// Remain prices entered before
String[] formPrice = form.getClosingPrice();
if (formPrice != null) {
for (int i = 0; i < len; i++) {
fundGeneralList[i].setSpecifiedPrice(formPrice[i]);
}
}
// Any validation errors?
errors.addAll(form.getValidationErrors());
if (errors.size() != 0) {
return "employee-transitionday.jsp";
}
// Get specified date
Date specifiedDate = form.getSpecifiedDate();
- if (specifiedDate != null && !specifiedDate.after(lastDate)) {
+ if (lastDate != null && !specifiedDate.after(lastDate)) {
errors.add("Can only choose the date after last trading date.");
return "employee-transitionday.jsp";
}
// Check whether fund list is empty, if not, update prices.
if (!form.isFundListEmpty()) {
// Get fund ids and closing prices from fund list grid.
int[] fundIds = form.getFundIdsAsInteger();
double[] closingPrices = form.getClosingPricesAsDouble();
// Insert new prices into price history table
for (int i = 0; i < len; i++) {
FundPriceHistoryBean bean = new FundPriceHistoryBean();
bean.setFund_id(fundIds[i]);
bean.setPrice(closingPrices[i]);
bean.setPrice_date(specifiedDate);
fundPriceHistoryDAO.create(bean);
}
}
// Process all pending transactions
int success = 0;
int rejected = 0;
PendingTransactionBean bean = getPendingTransactionAllInfo();
while (bean != null) {
boolean flag = false;
switch (bean.getTransactionType()) {
case 1:
flag = buyFund(bean, specifiedDate);
break;
case 2:
flag = sellFund(bean, specifiedDate);
break;
case 3:
flag = requestCheck(bean, specifiedDate);
break;
case 4:
flag = depositCheck(bean, specifiedDate);
break;
}
if (flag) {
success++;
} else {
rejected++;
}
bean = getPendingTransactionAllInfo();
}
// Display message
request.setAttribute("message", "Transition Day finished successfully. " + success + " are processed, " + rejected + " are rejected.");
return "employee-confirmation.jsp";
} catch (MyDAOException e) {
errors.add(e.getMessage());
return "employee-transitionday.jsp";
}
}
private PendingTransactionBean getPendingTransactionAllInfo() throws MyDAOException {
PendingTransactionBean bean = transactionDAO.readFirstPendingTransaction();
if (bean == null) return null;
FundPriceHistoryBean historyBean = fundPriceHistoryDAO.getLastTrading(bean.getFundId());
if (historyBean != null) {
bean.setPrice(historyBean.getPrice());
bean.setExecuteDate(historyBean.getPrice_date());
}
bean.setOwnedShares(positionDAO.getSinglePosition(bean.getCustomerId(), bean.getFundId()));
bean.setCash(customerDAO.read(bean.getCustomerId()).getCash());
return bean;
}
public boolean buyFund(PendingTransactionBean bean, Date date) throws MyDAOException {
if (bean.getAmount() > bean.getCash()) {
transactionDAO.rejectTransaction(date, bean.getTransactionId());
return false;
}
// Do calculation
double boughtShares = divide(bean.getAmount(), bean.getPrice(), 3);
double totalShares = add(boughtShares, bean.getOwnedShares());
double cost = multiply(boughtShares, bean.getPrice());
double remainingCash = subtract(bean.getCash(), cost);
// Update position table
PositionBean positionBean = new PositionBean();
positionBean.setCustomerId(bean.getCustomerId());
positionBean.setFundId(bean.getFundId());
positionBean.setShares(totalShares);
if (positionDAO.read(bean.getCustomerId(), bean.getFundId()) != null) {
positionDAO.update(positionBean);
} else {
positionDAO.create(positionBean);
}
// Update customer table
CustomerBean customerBean = new CustomerBean();
customerBean.setCustomerId(bean.getCustomerId());
customerBean.setCash(remainingCash);
customerDAO.updateCash(customerBean);
// Update transaction table
TransactionBean transactionBean = new TransactionBean();
transactionBean.setTransactionId(bean.getTransactionId());
transactionBean.setExecuteDate(date);
transactionBean.setShares(boughtShares);
transactionBean.setSharePrice(bean.getPrice());
transactionBean.setAmount(cost);
transactionDAO.processFundTransaction(transactionBean);
return true;
}
public boolean sellFund(PendingTransactionBean bean, Date date) throws MyDAOException {
if (bean.getToSellShares() > bean.getOwnedShares()) {
transactionDAO.rejectTransaction(date, bean.getTransactionId());
return false;
}
// Do calculation
double remainingShares = subtract(bean.getOwnedShares(), bean.getToSellShares());
double revenue = multiply(bean.getToSellShares(), bean.getPrice());
double totalCash = add(bean.getCash(), revenue);
// Update position table
PositionBean positionBean = new PositionBean();
positionBean.setCustomerId(bean.getCustomerId());
positionBean.setFundId(bean.getFundId());
positionBean.setShares(remainingShares);
positionDAO.update(positionBean);
// Update customer table
CustomerBean customerBean = new CustomerBean();
customerBean.setCustomerId(bean.getCustomerId());
customerBean.setCash(totalCash);
customerDAO.updateCash(customerBean);
// Update transaction table
TransactionBean transactionBean = new TransactionBean();
transactionBean.setTransactionId(bean.getTransactionId());
transactionBean.setExecuteDate(date);
transactionBean.setShares(bean.getToSellShares());
transactionBean.setSharePrice(bean.getPrice());
transactionBean.setAmount(revenue);
transactionDAO.processFundTransaction(transactionBean);
return true;
}
public boolean requestCheck(PendingTransactionBean bean, Date date) throws MyDAOException {
if (bean.getAmount() > bean.getCash()) {
transactionDAO.rejectTransaction(date, bean.getTransactionId());
return false;
}
// Do calculation
double remainingCash = subtract(bean.getCash(), bean.getAmount());
// Update customer table
CustomerBean customerBean = new CustomerBean();
customerBean.setCustomerId(bean.getCustomerId());
customerBean.setCash(remainingCash);
customerDAO.updateCash(customerBean);
// Update transaction table
TransactionBean transactionBean = new TransactionBean();
transactionBean.setTransactionId(bean.getTransactionId());
transactionBean.setExecuteDate(date);
transactionBean.setAmount(bean.getAmount());
transactionDAO.processCheckTransaction(transactionBean);
return true;
}
public boolean depositCheck(PendingTransactionBean bean, Date date) throws MyDAOException {
// Do calculation
double totalCash = add(bean.getCash(), bean.getAmount());
// Update customer table
CustomerBean customerBean = new CustomerBean();
customerBean.setCustomerId(bean.getCustomerId());
customerBean.setCash(totalCash);
customerDAO.updateCash(customerBean);
// Update transaction table
TransactionBean transactionBean = new TransactionBean();
transactionBean.setTransactionId(bean.getTransactionId());
transactionBean.setExecuteDate(date);
transactionBean.setAmount(bean.getAmount());
transactionDAO.processCheckTransaction(transactionBean);
return true;
}
public double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
public double subtract(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
public double multiply(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
public double divide(double v1, double v2, int scale) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public Date getTomorrow(Date today) {
if (today == null) return new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(today);
cal.add(Calendar.DAY_OF_YEAR, 1);
return cal.getTime();
}
}
| true | true | public String perform(HttpServletRequest request) {
List<String> errors = new ArrayList<String>();
request.setAttribute("errors",errors);
try {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
// Get last dates of transaction and fund price history. Set later one as last trading date.
Date lastDateTransaction = transactionDAO.getLastTradingDateOfALLTransactions();
Date lastDateFund = fundPriceHistoryDAO.getLastTradingDateOfALLFunds();
Date lastDate;
if (lastDateTransaction == null) {
lastDate = lastDateFund;
} else if (lastDateFund == null) {
lastDate = lastDateTransaction;
} else {
lastDate = lastDateTransaction.after(lastDateFund) ? lastDateTransaction : lastDateFund;
}
if (lastDate == null) {
request.setAttribute("lastDate", "No last trading day");
} else {
request.setAttribute("lastDate", df.format(lastDate));
}
// Set default date as tomorrow if last date exists. Otherwise, set today as default day.
Date defaultDate = lastDate != null ? getTomorrow(lastDate) : new Date();
request.setAttribute("defaultDate", df.format(defaultDate));
//get full fund list, allows customer to choose
FundGeneralInfoBean[] fundGeneralList = fundPriceHistoryDAO.getAllFundsGeneralInfo();
request.setAttribute("fundGeneralList", fundGeneralList);
int len = fundGeneralList == null ? 0: fundGeneralList.length;
request.setAttribute("fundListLength", len);
TransitionDayForm form = new TransitionDayForm(request);
request.setAttribute("form",form);
// If no params were passed, return with no errors so that the form will be
// presented (we assume for the first time).
if (!form.isPresent()) {
return "employee-transitionday.jsp";
}
// Remain prices entered before
String[] formPrice = form.getClosingPrice();
if (formPrice != null) {
for (int i = 0; i < len; i++) {
fundGeneralList[i].setSpecifiedPrice(formPrice[i]);
}
}
// Any validation errors?
errors.addAll(form.getValidationErrors());
if (errors.size() != 0) {
return "employee-transitionday.jsp";
}
// Get specified date
Date specifiedDate = form.getSpecifiedDate();
if (specifiedDate != null && !specifiedDate.after(lastDate)) {
errors.add("Can only choose the date after last trading date.");
return "employee-transitionday.jsp";
}
// Check whether fund list is empty, if not, update prices.
if (!form.isFundListEmpty()) {
// Get fund ids and closing prices from fund list grid.
int[] fundIds = form.getFundIdsAsInteger();
double[] closingPrices = form.getClosingPricesAsDouble();
// Insert new prices into price history table
for (int i = 0; i < len; i++) {
FundPriceHistoryBean bean = new FundPriceHistoryBean();
bean.setFund_id(fundIds[i]);
bean.setPrice(closingPrices[i]);
bean.setPrice_date(specifiedDate);
fundPriceHistoryDAO.create(bean);
}
}
// Process all pending transactions
int success = 0;
int rejected = 0;
PendingTransactionBean bean = getPendingTransactionAllInfo();
while (bean != null) {
boolean flag = false;
switch (bean.getTransactionType()) {
case 1:
flag = buyFund(bean, specifiedDate);
break;
case 2:
flag = sellFund(bean, specifiedDate);
break;
case 3:
flag = requestCheck(bean, specifiedDate);
break;
case 4:
flag = depositCheck(bean, specifiedDate);
break;
}
if (flag) {
success++;
} else {
rejected++;
}
bean = getPendingTransactionAllInfo();
}
// Display message
request.setAttribute("message", "Transition Day finished successfully. " + success + " are processed, " + rejected + " are rejected.");
return "employee-confirmation.jsp";
} catch (MyDAOException e) {
errors.add(e.getMessage());
return "employee-transitionday.jsp";
}
}
| public String perform(HttpServletRequest request) {
List<String> errors = new ArrayList<String>();
request.setAttribute("errors",errors);
try {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
// Get last dates of transaction and fund price history. Set later one as last trading date.
Date lastDateTransaction = transactionDAO.getLastTradingDateOfALLTransactions();
Date lastDateFund = fundPriceHistoryDAO.getLastTradingDateOfALLFunds();
Date lastDate;
if (lastDateTransaction == null) {
lastDate = lastDateFund;
} else if (lastDateFund == null) {
lastDate = lastDateTransaction;
} else {
lastDate = lastDateTransaction.after(lastDateFund) ? lastDateTransaction : lastDateFund;
}
if (lastDate == null) {
request.setAttribute("lastDate", "No last trading day");
} else {
request.setAttribute("lastDate", df.format(lastDate));
}
// Set default date as tomorrow if last date exists. Otherwise, set today as default day.
Date defaultDate = lastDate != null ? getTomorrow(lastDate) : new Date();
request.setAttribute("defaultDate", df.format(defaultDate));
//get full fund list, allows customer to choose
FundGeneralInfoBean[] fundGeneralList = fundPriceHistoryDAO.getAllFundsGeneralInfo();
request.setAttribute("fundGeneralList", fundGeneralList);
int len = fundGeneralList == null ? 0: fundGeneralList.length;
request.setAttribute("fundListLength", len);
TransitionDayForm form = new TransitionDayForm(request);
request.setAttribute("form",form);
// If no params were passed, return with no errors so that the form will be
// presented (we assume for the first time).
if (!form.isPresent()) {
return "employee-transitionday.jsp";
}
// Remain prices entered before
String[] formPrice = form.getClosingPrice();
if (formPrice != null) {
for (int i = 0; i < len; i++) {
fundGeneralList[i].setSpecifiedPrice(formPrice[i]);
}
}
// Any validation errors?
errors.addAll(form.getValidationErrors());
if (errors.size() != 0) {
return "employee-transitionday.jsp";
}
// Get specified date
Date specifiedDate = form.getSpecifiedDate();
if (lastDate != null && !specifiedDate.after(lastDate)) {
errors.add("Can only choose the date after last trading date.");
return "employee-transitionday.jsp";
}
// Check whether fund list is empty, if not, update prices.
if (!form.isFundListEmpty()) {
// Get fund ids and closing prices from fund list grid.
int[] fundIds = form.getFundIdsAsInteger();
double[] closingPrices = form.getClosingPricesAsDouble();
// Insert new prices into price history table
for (int i = 0; i < len; i++) {
FundPriceHistoryBean bean = new FundPriceHistoryBean();
bean.setFund_id(fundIds[i]);
bean.setPrice(closingPrices[i]);
bean.setPrice_date(specifiedDate);
fundPriceHistoryDAO.create(bean);
}
}
// Process all pending transactions
int success = 0;
int rejected = 0;
PendingTransactionBean bean = getPendingTransactionAllInfo();
while (bean != null) {
boolean flag = false;
switch (bean.getTransactionType()) {
case 1:
flag = buyFund(bean, specifiedDate);
break;
case 2:
flag = sellFund(bean, specifiedDate);
break;
case 3:
flag = requestCheck(bean, specifiedDate);
break;
case 4:
flag = depositCheck(bean, specifiedDate);
break;
}
if (flag) {
success++;
} else {
rejected++;
}
bean = getPendingTransactionAllInfo();
}
// Display message
request.setAttribute("message", "Transition Day finished successfully. " + success + " are processed, " + rejected + " are rejected.");
return "employee-confirmation.jsp";
} catch (MyDAOException e) {
errors.add(e.getMessage());
return "employee-transitionday.jsp";
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java
index b3f208c00..552a2f2d3 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java
@@ -1,281 +1,281 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.equinox.p2.tests.full;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.p2.director.app.LatestIUVersionCollector;
import org.eclipse.equinox.internal.provisional.frameworkadmin.*;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.director.IDirector;
import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest;
import org.eclipse.equinox.internal.provisional.p2.engine.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.query.Collector;
import org.eclipse.equinox.p2.tests.AbstractProvisioningTest;
import org.eclipse.equinox.p2.tests.TestActivator;
import org.eclipse.osgi.service.environment.EnvironmentInfo;
import org.osgi.framework.*;
import org.osgi.util.tracker.ServiceTracker;
public class End2EndTest extends AbstractProvisioningTest {
private IMetadataRepositoryManager metadataRepoManager;
private IArtifactRepositoryManager artifactRepoManager;
private IDirector director;
private ServiceTracker fwAdminTracker;
protected void setUp() throws Exception {
ServiceReference sr = TestActivator.context.getServiceReference(IDirector.class.getName());
if (sr == null)
throw new RuntimeException("Director service not available");
director = createDirector();
// planner = createPlanner();
ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName());
metadataRepoManager = (IMetadataRepositoryManager) TestActivator.context.getService(sr2);
if (metadataRepoManager == null)
throw new RuntimeException("Metadata repository manager could not be loaded");
ServiceReference sr3 = TestActivator.context.getServiceReference(IArtifactRepositoryManager.class.getName());
artifactRepoManager = (IArtifactRepositoryManager) TestActivator.context.getService(sr3);
if (artifactRepoManager == null)
throw new RuntimeException("Artifact repo manager could not be loaded");
}
protected IProfile createProfile(String profileId, String installFolder) {
ServiceReference profileRegSr = TestActivator.context.getServiceReference(IProfileRegistry.class.getName());
IProfileRegistry profileRegistry = (IProfileRegistry) TestActivator.context.getService(profileRegSr);
if (profileRegistry == null) {
throw new RuntimeException("Profile registry service not available");
}
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, installFolder);
EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(TestActivator.getContext(), EnvironmentInfo.class.getName());
if (info != null)
properties.put(IProfile.PROP_ENVIRONMENTS, "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch());
properties.put("org.eclipse.update.install.features", "true");
properties.put(IProfile.PROP_CACHE, installFolder);
return createProfile(profileId, null, properties);
}
public void testInstallSDK() {
- //disabled due to failures on test machines. See bug
+ //disabled due to failures on test machines. See bug 252129
if (true)
return;
File installFolder = TestActivator.getContext().getDataFile(End2EndTest.class.getName());
IProfile profile2 = createProfile("End2EndProfile", installFolder.getAbsolutePath());
//Add repository of the release
try {
URI location = new URI("http://download.eclipse.org/eclipse/updates/3.4");
metadataRepoManager.addRepository(location);
metadataRepoManager.setEnabled(location, true);
metadataRepoManager.loadRepository(location, new NullProgressMonitor());
artifactRepoManager.addRepository(location);
artifactRepoManager.setEnabled(location, true);
} catch (ProvisionException e) {
fail("Exception loading the repository.", e);
} catch (URISyntaxException e) {
fail("Invalid repository location", e);
}
installPlatform(profile2, installFolder);
installPlatformSource(profile2, installFolder);
attemptToUninstallPlatform(profile2, installFolder);
rollbackPlatformSource(profile2, installFolder);
uninstallPlatform(profile2, installFolder);
}
private void attemptToUninstallPlatform(IProfile profile2, File installFolder) {
// TODO Auto-generated method stub
}
private void uninstallPlatform(IProfile profile2, File installFolder) {
// TODO Auto-generated method stub
}
private void rollbackPlatformSource(IProfile profile2, File installFolder) {
IMetadataRepository rollbackRepo = null;
try {
rollbackRepo = metadataRepoManager.loadRepository(director.getRollbackRepositoryLocation(), new NullProgressMonitor());
} catch (ProvisionException e) {
fail("Can't find rollback repository");
}
Collector collector = rollbackRepo.query(new InstallableUnitQuery(profile2.getProfileId()), new LatestIUVersionCollector(), new NullProgressMonitor());
assertEquals(1, collector.size());
IStatus s = director.revert((IInstallableUnit) collector.iterator().next(), profile2, new ProvisioningContext(), new NullProgressMonitor());
assertTrue(s.isOK());
validateInstallContentFor34(installFolder);
assertFalse(new File(installFolder, "configuration/org.eclipse.equinox.source/source.info").exists());
}
private void installPlatformSource(IProfile profile2, File installFolder) {
final String id = "org.eclipse.platform.source.feature.group";
final Version version = new Version("3.4.1.r341_v20080731-9I96EiDElYevwz-p1bP5z-NlAaP7vtX6Utotqsu");
IInstallableUnit toInstall = getIU(id, version);
if (toInstall == null)
assertNotNull(toInstall);
ProfileChangeRequest request = new ProfileChangeRequest(profile2);
request.addInstallableUnits(new IInstallableUnit[] {toInstall});
IStatus s = director.provision(request, null, new NullProgressMonitor());
if (!s.isOK())
fail("Installation of the " + id + " " + version + " failed.");
assertProfileContainsAll("Platform source feature", profile2, new IInstallableUnit[] {toInstall});
assertTrue(new File(installFolder, "configuration/org.eclipse.equinox.source").exists());
}
private void installPlatform(IProfile profile2, File installFolder) {
final String id = "org.eclipse.platform.ide";
final Version version = new Version("3.4.0.M20080911-1700");
//First we install the platform
ProfileChangeRequest request = new ProfileChangeRequest(profile2);
IInstallableUnit platformIU = getIU(id, version);
if (platformIU == null)
assertNotNull(platformIU);
request.addInstallableUnits(new IInstallableUnit[] {platformIU});
IStatus s = director.provision(request, null, new NullProgressMonitor());
if (!s.isOK()) {
LogHelper.log(s);
fail("Installation of the " + id + " " + version + " failed. " + s.toString());
}
assertProfileContainsAll("Platform 3.4 profile", profile2, new IInstallableUnit[] {platformIU});
validateInstallContentFor34(installFolder);
assertFalse(new File(installFolder, "configuration/org.eclipse.equinox.source").exists());
}
public IInstallableUnit getIU(String id, Version v) {
Iterator it = metadataRepoManager.query(new InstallableUnitQuery(id, v), new Collector(), null).iterator();
if (it.hasNext())
return (IInstallableUnit) it.next();
return null;
}
private void validateInstallContentFor34(File installFolder) {
FrameworkAdmin fwkAdmin = getEquinoxFrameworkAdmin();
Manipulator manipulator = fwkAdmin.getManipulator();
LauncherData launcherData = manipulator.getLauncherData();
launcherData.setFwConfigLocation(new File(installFolder, "configuration"));
launcherData.setLauncher(new File(installFolder, getLauncherName("eclipse", Platform.getOS())));
try {
manipulator.load();
} catch (IllegalStateException e) {
fail("Error loading the configuration", e);
} catch (FrameworkAdminRuntimeException e) {
fail("Error loading the configuration", e);
} catch (IOException e) {
fail("Error loading the configuration", e);
}
assertContains("Can't find VM arg", manipulator.getLauncherData().getJvmArgs(), "-Xms40m");
assertContains("Can't find VM arg", manipulator.getLauncherData().getJvmArgs(), "-Xmx256m");
String[] programArgs = manipulator.getLauncherData().getProgramArgs();
assertContains("Can't find program arg", programArgs, "-startup");
assertContains("Can't find program arg", programArgs, "-showsplash");
assertContains("Can't find program arg", programArgs, "org.eclipse.platform");
assertTrue(manipulator.getConfigData().getBundles().length > 50);
assertTrue(new File(installFolder, "plugins").exists());
assertTrue(new File(installFolder, "features").exists());
}
private void assertContains(String message, String[] source, String searched) {
for (int i = 0; i < source.length; i++) {
if (source[i].equals(searched))
return;
}
fail(message + " " + searched);
}
private FrameworkAdmin getEquinoxFrameworkAdmin() {
final String FILTER_OBJECTCLASS = "(" + Constants.OBJECTCLASS + "=" + FrameworkAdmin.class.getName() + ")";
final String filterFwName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_FW_NAME + "=Equinox)";
final String filterLauncherName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_NAME + "=Eclipse.exe)";
final String filterFwAdmin = "(&" + FILTER_OBJECTCLASS + filterFwName + filterLauncherName + ")";
String FWK_ADMIN_EQ = "org.eclipse.equinox.frameworkadmin.equinox";
Bundle b = Platform.getBundle(FWK_ADMIN_EQ);
if (b == null)
fail("Bundle: " + FWK_ADMIN_EQ + " is required for this test");
try {
b.start();
} catch (BundleException e) {
fail("Can't start framework admin");
}
if (fwAdminTracker == null) {
Filter filter;
try {
filter = TestActivator.getContext().createFilter(filterFwAdmin);
fwAdminTracker = new ServiceTracker(TestActivator.getContext(), filter, null);
fwAdminTracker.open();
} catch (InvalidSyntaxException e) {
// never happens
e.printStackTrace();
}
}
return (FrameworkAdmin) fwAdminTracker.getService();
}
private static String getLauncherName(String name, String os) {
if (os == null) {
EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(TestActivator.getContext(), EnvironmentInfo.class.getName());
if (info != null)
os = info.getOS();
}
if (os.equals(org.eclipse.osgi.service.environment.Constants.OS_WIN32)) {
IPath path = new Path(name);
if ("exe".equals(path.getFileExtension())) //$NON-NLS-1$
return name;
return name + ".exe"; //$NON-NLS-1$
}
if (os.equals(org.eclipse.osgi.service.environment.Constants.OS_MACOSX)) {
IPath path = new Path(name);
if ("app".equals(path.getFileExtension())) //$NON-NLS-1$
return name;
StringBuffer buffer = new StringBuffer();
buffer.append(name.substring(0, 1).toUpperCase());
buffer.append(name.substring(1));
buffer.append(".app/Contents/MacOS/"); //$NON-NLS-1$
buffer.append(name.toLowerCase());
return buffer.toString();
}
return name;
}
}
| true | true | public void testInstallSDK() {
//disabled due to failures on test machines. See bug
if (true)
return;
File installFolder = TestActivator.getContext().getDataFile(End2EndTest.class.getName());
IProfile profile2 = createProfile("End2EndProfile", installFolder.getAbsolutePath());
//Add repository of the release
try {
URI location = new URI("http://download.eclipse.org/eclipse/updates/3.4");
metadataRepoManager.addRepository(location);
metadataRepoManager.setEnabled(location, true);
metadataRepoManager.loadRepository(location, new NullProgressMonitor());
artifactRepoManager.addRepository(location);
artifactRepoManager.setEnabled(location, true);
} catch (ProvisionException e) {
fail("Exception loading the repository.", e);
} catch (URISyntaxException e) {
fail("Invalid repository location", e);
}
installPlatform(profile2, installFolder);
installPlatformSource(profile2, installFolder);
attemptToUninstallPlatform(profile2, installFolder);
rollbackPlatformSource(profile2, installFolder);
uninstallPlatform(profile2, installFolder);
}
| public void testInstallSDK() {
//disabled due to failures on test machines. See bug 252129
if (true)
return;
File installFolder = TestActivator.getContext().getDataFile(End2EndTest.class.getName());
IProfile profile2 = createProfile("End2EndProfile", installFolder.getAbsolutePath());
//Add repository of the release
try {
URI location = new URI("http://download.eclipse.org/eclipse/updates/3.4");
metadataRepoManager.addRepository(location);
metadataRepoManager.setEnabled(location, true);
metadataRepoManager.loadRepository(location, new NullProgressMonitor());
artifactRepoManager.addRepository(location);
artifactRepoManager.setEnabled(location, true);
} catch (ProvisionException e) {
fail("Exception loading the repository.", e);
} catch (URISyntaxException e) {
fail("Invalid repository location", e);
}
installPlatform(profile2, installFolder);
installPlatformSource(profile2, installFolder);
attemptToUninstallPlatform(profile2, installFolder);
rollbackPlatformSource(profile2, installFolder);
uninstallPlatform(profile2, installFolder);
}
|
diff --git a/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java b/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java
index a18e3dc2..3bd62067 100644
--- a/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java
+++ b/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java
@@ -1,365 +1,371 @@
/*
* Copyright (c) 2013. ToppleTheNun
*
* 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.conventnunnery.plugins.mythicdrops.managers;
import com.conventnunnery.plugins.mythicdrops.MythicDrops;
import com.conventnunnery.plugins.mythicdrops.objects.CustomItem;
import com.conventnunnery.plugins.mythicdrops.objects.MythicEnchantment;
import com.conventnunnery.plugins.mythicdrops.objects.SocketGem;
import com.conventnunnery.plugins.mythicdrops.objects.SocketItem;
import com.conventnunnery.plugins.mythicdrops.objects.Tier;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentWrapper;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* A class that handles all of the plugin's drop creation.
*/
public class DropManager {
private final MythicDrops plugin;
private List<CustomItem> customItems;
/**
* Instantiates a new Drop API.
*
* @param plugin the plugin
*/
public DropManager(MythicDrops plugin) {
this.plugin = plugin;
customItems = new ArrayList<CustomItem>();
}
/**
* Construct a random ItemStack.
*
* @param reason the reason
* @return random ItemStack
*/
public ItemStack constructItemStack(GenerationReason reason) {
switch (reason) {
case MOB_SPAWN:
if (getPlugin().getPluginSettings().isAllowCustomToSpawn() &&
getPlugin().getPluginSettings().isOnlyCustomItems() ||
getPlugin().getRandom().nextDouble() <=
getPlugin().getPluginSettings().getPercentageCustomDrop() &&
!customItems.isEmpty()) {
return randomCustomItemWithChance().toItemStack();
}
if (getPlugin().getPluginSettings().isSocketGemsEnabled()
&& getPlugin().getRandom().nextDouble() < getPlugin()
.getPluginSettings().getSocketGemsChance()) {
MaterialData materialData = getPlugin().getSocketGemManager().getRandomSocketGemMaterial();
SocketGem socketGem = getPlugin().getSocketGemManager().getRandomSocketGemWithChance();
if (materialData != null && socketGem != null)
return new SocketItem(materialData, socketGem);
}
return constructItemStack(getPlugin().getTierManager().randomTierWithChance(), reason);
case COMMAND:
return constructItemStack(getPlugin().getTierManager()
.randomTierWithChance(), reason);
case EXTERNAL:
return constructItemStack(getPlugin().getTierManager()
.randomTierWithChance(), reason);
default:
return constructItemStack(getPlugin().getTierManager()
.randomTierWithChance(), reason);
}
}
/**
* Construct an ItemStack based on a Tier.
*
* @param tier Tier to base the ItemStack on
* @param reason reason to generate the ItemStack
* @return constructed ItemStack
*/
public ItemStack constructItemStack(Tier tier, GenerationReason reason) {
ItemStack itemstack = null;
MaterialData matData = null;
int attempts = 0;
if (tier == null) {
return null;
}
while (matData == null && attempts < 10) {
matData = getPlugin().getItemManager().getMatDataFromTier(tier);
attempts++;
}
if (matData == null || matData.getItemTypeId() == 0
|| matData.getItemType() == Material.AIR)
return itemstack;
itemstack = matData.toItemStack(1);
if (itemstack == null) {
return itemstack;
}
if (reason != null && reason != GenerationReason.COMMAND) {
double min = Math.min(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double max = Math.max(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double minDuraPercent = itemstack.getType().getMaxDurability() -
Math.max(min, max) *
itemstack.getType().getMaxDurability();
double maxDuraPercent =
itemstack.getType().getMaxDurability() -
Math.min(min, max) *
itemstack.getType().getMaxDurability();
int minDura =
(int) minDuraPercent;
int maxDura = (int) maxDuraPercent;
short dura = (short) (getPlugin().getRandom()
.nextInt(
Math.abs(Math.max(minDura, maxDura) - Math.min(minDura, maxDura)) + 1) +
Math.min(minDura, maxDura));
itemstack.setDurability(dura);
}
for (MythicEnchantment me : tier.getBaseEnchantments()) {
+ if (me.getEnchantment() == null){
+ continue;
+ }
if (tier.isSafeBaseEnchantments() && me.getEnchantment().canEnchantItem(itemstack)) {
itemstack.addEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel())));
} else if (!tier.isSafeBaseEnchantments()) {
itemstack.addUnsafeEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1)));
}
}
if (tier.getMaximumBonusEnchantments() > 0) {
int randEnchs = getPlugin().getRandom().nextInt(
Math.abs(tier.getMaximumBonusEnchantments() - tier.getMinimumBonusEnchantments() + 1)) +
tier.getMinimumBonusEnchantments();
for (int i = 0; i < randEnchs; i++) {
Set<MythicEnchantment> allowEnchs = tier.getBonusEnchantments();
List<Enchantment> stackEnchs = getEnchantStack(itemstack);
List<MythicEnchantment> actual = new ArrayList<MythicEnchantment>();
for (MythicEnchantment te : allowEnchs) {
+ if (te.getEnchantment() == null) {
+ continue;
+ }
if (stackEnchs.contains(te.getEnchantment())) {
actual.add(te);
}
}
if (actual.size() > 0) {
MythicEnchantment ench = actual.get(getPlugin().getRandom()
.nextInt(actual.size()));
int lev =
getPlugin().getRandom()
.nextInt(Math.abs(ench.getMaximumLevel() - ench.getMinimumLevel()) + 1) +
ench.getMinimumLevel();
if (getPlugin().getPluginSettings().isSafeEnchantsOnly()) {
if (!getPlugin().getPluginSettings().isAllowEnchantsPastNormalLevel()) {
itemstack.addEnchantment(
ench.getEnchantment(),
getAcceptableEnchantmentLevel(ench.getEnchantment(),
lev <= 0 ? 1 : Math.abs(lev)));
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
}
}
}
if (matData.getItemType() == null) {
return itemstack;
}
ItemMeta im;
if (itemstack.hasItemMeta())
im = itemstack.getItemMeta();
else
im = Bukkit.getItemFactory().getItemMeta(matData.getItemType());
im.setDisplayName(getPlugin().getNameManager().randomFormattedName(
itemstack, tier));
List<String> toolTips = getPlugin().getPluginSettings()
.getAdvancedToolTipFormat();
List<String> tt = new ArrayList<String>();
for (String s : toolTips) {
tt.add(ChatColor.translateAlternateColorCodes(
'&',
s.replace("%itemtype%",
getPlugin().getNameManager().getItemTypeName(matData))
.replace("%tiername%",
tier.getDisplayColor() + tier.getDisplayName())
.replace(
"%basematerial%",
getPlugin().getNameManager()
.getMinecraftMaterialName(
itemstack.getType()))
.replace(
"%mythicmaterial%",
getPlugin().getNameManager()
.getMythicMaterialName(
itemstack.getData())).replace("%enchantment%",
tier.getDisplayColor() + getPlugin().getNameManager().getEnchantmentTypeName(itemstack) +
tier.getIdentificationColor())));
}
if (getPlugin().getPluginSettings().isSockettedItemsEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getSpawnWithSocketChance()) {
int amtTT = 0;
for (int i = 0;
i < getPlugin().getRandom()
.nextInt(Math.abs(tier.getMaximumSockets() - tier.getMinimumSockets()) + 1) +
tier.getMinimumSockets(); i++) {
tt.add(ChatColor.GOLD + "(Socket)");
amtTT++;
}
if (amtTT > 0) {
tt.add(ChatColor.GRAY + "Find a " + ChatColor.GOLD + "Socket Gem" + ChatColor.GRAY + " to fill a " +
ChatColor.GOLD + "(Socket)");
}
}
if (getPlugin().getPluginSettings().isRandomLoreEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getRandomLoreChance() &&
!getPlugin().getNameManager().getBasicLore().isEmpty()) {
tt.addAll(getPlugin().getNameManager().randomLore());
}
im.setLore(tt);
if (im instanceof Repairable) {
Repairable r = (Repairable) im;
r.setRepairCost(1000);
itemstack.setItemMeta((ItemMeta) r);
} else {
itemstack.setItemMeta(im);
}
return itemstack;
}
/**
* Gets acceptable Enchantment level.
*
* @param ench the Enchantment
* @param level the level
* @return the acceptable Enchantment level
*/
public int getAcceptableEnchantmentLevel(Enchantment ench, int level) {
EnchantmentWrapper ew = new EnchantmentWrapper(ench.getId());
int i = level;
if (i > ew.getMaxLevel()) {
i = ew.getMaxLevel();
} else if (i < ew.getStartLevel()) {
i = ew.getStartLevel();
}
return i;
}
/**
* Gets custom items.
*
* @return the custom items
*/
public List<CustomItem> getCustomItems() {
return customItems;
}
/**
* Gets a list of Enchantments that can go on an ItemStack.
*
* @param ci ItemStack to check
* @return list of possible Enchantments
*/
public List<Enchantment> getEnchantStack(final ItemStack ci) {
List<Enchantment> set = new ArrayList<Enchantment>();
if (ci == null) {
return set;
}
boolean bln = getPlugin().getPluginSettings().isSafeEnchantsOnly();
for (Enchantment e : Enchantment.values()) {
if (bln) {
if (e.canEnchantItem(ci)) {
set.add(e);
}
} else {
set.add(e);
}
}
return set;
}
/**
* Gets plugin.
*
* @return the plugin
*/
public MythicDrops getPlugin() {
return plugin;
}
public void debugCustomItems() {
List<String> customItemNames = new ArrayList<String>();
for (CustomItem ci : customItems) {
customItemNames.add(ci.getName());
}
getPlugin().getDebug().debug(
"Loaded custom items: "
+ customItemNames.toString().replace("[", "")
.replace("]", ""));
}
/**
* Random custom item.
*
* @return the custom item
*/
@SuppressWarnings("unused")
public CustomItem randomCustomItem() {
return customItems.get(getPlugin().getRandom().nextInt(customItems.size()));
}
public CustomItem getCustomItemByName(String name) {
for (CustomItem i : customItems) {
if (name.equalsIgnoreCase(i.getName())) {
return i;
}
}
return null;
}
/**
* Random custom item with chance.
*
* @return the custom item
*/
public CustomItem randomCustomItemWithChance() {
CustomItem ci = null;
if (customItems == null || customItems.isEmpty())
return ci;
while (ci == null) {
for (CustomItem c : customItems) {
double d = plugin.getRandom().nextDouble();
if (d <= c.getChance()) {
ci = c;
break;
}
}
}
return ci;
}
/**
* Enum of GenerationReasons.
*/
public enum GenerationReason {
/**
* Use when spawning a mob
*/MOB_SPAWN, /**
* Use for commands
*/COMMAND, /**
* Use for anything else
*/EXTERNAL
}
}
| false | true | public ItemStack constructItemStack(Tier tier, GenerationReason reason) {
ItemStack itemstack = null;
MaterialData matData = null;
int attempts = 0;
if (tier == null) {
return null;
}
while (matData == null && attempts < 10) {
matData = getPlugin().getItemManager().getMatDataFromTier(tier);
attempts++;
}
if (matData == null || matData.getItemTypeId() == 0
|| matData.getItemType() == Material.AIR)
return itemstack;
itemstack = matData.toItemStack(1);
if (itemstack == null) {
return itemstack;
}
if (reason != null && reason != GenerationReason.COMMAND) {
double min = Math.min(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double max = Math.max(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double minDuraPercent = itemstack.getType().getMaxDurability() -
Math.max(min, max) *
itemstack.getType().getMaxDurability();
double maxDuraPercent =
itemstack.getType().getMaxDurability() -
Math.min(min, max) *
itemstack.getType().getMaxDurability();
int minDura =
(int) minDuraPercent;
int maxDura = (int) maxDuraPercent;
short dura = (short) (getPlugin().getRandom()
.nextInt(
Math.abs(Math.max(minDura, maxDura) - Math.min(minDura, maxDura)) + 1) +
Math.min(minDura, maxDura));
itemstack.setDurability(dura);
}
for (MythicEnchantment me : tier.getBaseEnchantments()) {
if (tier.isSafeBaseEnchantments() && me.getEnchantment().canEnchantItem(itemstack)) {
itemstack.addEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel())));
} else if (!tier.isSafeBaseEnchantments()) {
itemstack.addUnsafeEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1)));
}
}
if (tier.getMaximumBonusEnchantments() > 0) {
int randEnchs = getPlugin().getRandom().nextInt(
Math.abs(tier.getMaximumBonusEnchantments() - tier.getMinimumBonusEnchantments() + 1)) +
tier.getMinimumBonusEnchantments();
for (int i = 0; i < randEnchs; i++) {
Set<MythicEnchantment> allowEnchs = tier.getBonusEnchantments();
List<Enchantment> stackEnchs = getEnchantStack(itemstack);
List<MythicEnchantment> actual = new ArrayList<MythicEnchantment>();
for (MythicEnchantment te : allowEnchs) {
if (stackEnchs.contains(te.getEnchantment())) {
actual.add(te);
}
}
if (actual.size() > 0) {
MythicEnchantment ench = actual.get(getPlugin().getRandom()
.nextInt(actual.size()));
int lev =
getPlugin().getRandom()
.nextInt(Math.abs(ench.getMaximumLevel() - ench.getMinimumLevel()) + 1) +
ench.getMinimumLevel();
if (getPlugin().getPluginSettings().isSafeEnchantsOnly()) {
if (!getPlugin().getPluginSettings().isAllowEnchantsPastNormalLevel()) {
itemstack.addEnchantment(
ench.getEnchantment(),
getAcceptableEnchantmentLevel(ench.getEnchantment(),
lev <= 0 ? 1 : Math.abs(lev)));
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
}
}
}
if (matData.getItemType() == null) {
return itemstack;
}
ItemMeta im;
if (itemstack.hasItemMeta())
im = itemstack.getItemMeta();
else
im = Bukkit.getItemFactory().getItemMeta(matData.getItemType());
im.setDisplayName(getPlugin().getNameManager().randomFormattedName(
itemstack, tier));
List<String> toolTips = getPlugin().getPluginSettings()
.getAdvancedToolTipFormat();
List<String> tt = new ArrayList<String>();
for (String s : toolTips) {
tt.add(ChatColor.translateAlternateColorCodes(
'&',
s.replace("%itemtype%",
getPlugin().getNameManager().getItemTypeName(matData))
.replace("%tiername%",
tier.getDisplayColor() + tier.getDisplayName())
.replace(
"%basematerial%",
getPlugin().getNameManager()
.getMinecraftMaterialName(
itemstack.getType()))
.replace(
"%mythicmaterial%",
getPlugin().getNameManager()
.getMythicMaterialName(
itemstack.getData())).replace("%enchantment%",
tier.getDisplayColor() + getPlugin().getNameManager().getEnchantmentTypeName(itemstack) +
tier.getIdentificationColor())));
}
if (getPlugin().getPluginSettings().isSockettedItemsEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getSpawnWithSocketChance()) {
int amtTT = 0;
for (int i = 0;
i < getPlugin().getRandom()
.nextInt(Math.abs(tier.getMaximumSockets() - tier.getMinimumSockets()) + 1) +
tier.getMinimumSockets(); i++) {
tt.add(ChatColor.GOLD + "(Socket)");
amtTT++;
}
if (amtTT > 0) {
tt.add(ChatColor.GRAY + "Find a " + ChatColor.GOLD + "Socket Gem" + ChatColor.GRAY + " to fill a " +
ChatColor.GOLD + "(Socket)");
}
}
if (getPlugin().getPluginSettings().isRandomLoreEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getRandomLoreChance() &&
!getPlugin().getNameManager().getBasicLore().isEmpty()) {
tt.addAll(getPlugin().getNameManager().randomLore());
}
im.setLore(tt);
if (im instanceof Repairable) {
Repairable r = (Repairable) im;
r.setRepairCost(1000);
itemstack.setItemMeta((ItemMeta) r);
} else {
itemstack.setItemMeta(im);
}
return itemstack;
}
| public ItemStack constructItemStack(Tier tier, GenerationReason reason) {
ItemStack itemstack = null;
MaterialData matData = null;
int attempts = 0;
if (tier == null) {
return null;
}
while (matData == null && attempts < 10) {
matData = getPlugin().getItemManager().getMatDataFromTier(tier);
attempts++;
}
if (matData == null || matData.getItemTypeId() == 0
|| matData.getItemType() == Material.AIR)
return itemstack;
itemstack = matData.toItemStack(1);
if (itemstack == null) {
return itemstack;
}
if (reason != null && reason != GenerationReason.COMMAND) {
double min = Math.min(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double max = Math.max(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double minDuraPercent = itemstack.getType().getMaxDurability() -
Math.max(min, max) *
itemstack.getType().getMaxDurability();
double maxDuraPercent =
itemstack.getType().getMaxDurability() -
Math.min(min, max) *
itemstack.getType().getMaxDurability();
int minDura =
(int) minDuraPercent;
int maxDura = (int) maxDuraPercent;
short dura = (short) (getPlugin().getRandom()
.nextInt(
Math.abs(Math.max(minDura, maxDura) - Math.min(minDura, maxDura)) + 1) +
Math.min(minDura, maxDura));
itemstack.setDurability(dura);
}
for (MythicEnchantment me : tier.getBaseEnchantments()) {
if (me.getEnchantment() == null){
continue;
}
if (tier.isSafeBaseEnchantments() && me.getEnchantment().canEnchantItem(itemstack)) {
itemstack.addEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel())));
} else if (!tier.isSafeBaseEnchantments()) {
itemstack.addUnsafeEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1)));
}
}
if (tier.getMaximumBonusEnchantments() > 0) {
int randEnchs = getPlugin().getRandom().nextInt(
Math.abs(tier.getMaximumBonusEnchantments() - tier.getMinimumBonusEnchantments() + 1)) +
tier.getMinimumBonusEnchantments();
for (int i = 0; i < randEnchs; i++) {
Set<MythicEnchantment> allowEnchs = tier.getBonusEnchantments();
List<Enchantment> stackEnchs = getEnchantStack(itemstack);
List<MythicEnchantment> actual = new ArrayList<MythicEnchantment>();
for (MythicEnchantment te : allowEnchs) {
if (te.getEnchantment() == null) {
continue;
}
if (stackEnchs.contains(te.getEnchantment())) {
actual.add(te);
}
}
if (actual.size() > 0) {
MythicEnchantment ench = actual.get(getPlugin().getRandom()
.nextInt(actual.size()));
int lev =
getPlugin().getRandom()
.nextInt(Math.abs(ench.getMaximumLevel() - ench.getMinimumLevel()) + 1) +
ench.getMinimumLevel();
if (getPlugin().getPluginSettings().isSafeEnchantsOnly()) {
if (!getPlugin().getPluginSettings().isAllowEnchantsPastNormalLevel()) {
itemstack.addEnchantment(
ench.getEnchantment(),
getAcceptableEnchantmentLevel(ench.getEnchantment(),
lev <= 0 ? 1 : Math.abs(lev)));
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
}
}
}
if (matData.getItemType() == null) {
return itemstack;
}
ItemMeta im;
if (itemstack.hasItemMeta())
im = itemstack.getItemMeta();
else
im = Bukkit.getItemFactory().getItemMeta(matData.getItemType());
im.setDisplayName(getPlugin().getNameManager().randomFormattedName(
itemstack, tier));
List<String> toolTips = getPlugin().getPluginSettings()
.getAdvancedToolTipFormat();
List<String> tt = new ArrayList<String>();
for (String s : toolTips) {
tt.add(ChatColor.translateAlternateColorCodes(
'&',
s.replace("%itemtype%",
getPlugin().getNameManager().getItemTypeName(matData))
.replace("%tiername%",
tier.getDisplayColor() + tier.getDisplayName())
.replace(
"%basematerial%",
getPlugin().getNameManager()
.getMinecraftMaterialName(
itemstack.getType()))
.replace(
"%mythicmaterial%",
getPlugin().getNameManager()
.getMythicMaterialName(
itemstack.getData())).replace("%enchantment%",
tier.getDisplayColor() + getPlugin().getNameManager().getEnchantmentTypeName(itemstack) +
tier.getIdentificationColor())));
}
if (getPlugin().getPluginSettings().isSockettedItemsEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getSpawnWithSocketChance()) {
int amtTT = 0;
for (int i = 0;
i < getPlugin().getRandom()
.nextInt(Math.abs(tier.getMaximumSockets() - tier.getMinimumSockets()) + 1) +
tier.getMinimumSockets(); i++) {
tt.add(ChatColor.GOLD + "(Socket)");
amtTT++;
}
if (amtTT > 0) {
tt.add(ChatColor.GRAY + "Find a " + ChatColor.GOLD + "Socket Gem" + ChatColor.GRAY + " to fill a " +
ChatColor.GOLD + "(Socket)");
}
}
if (getPlugin().getPluginSettings().isRandomLoreEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getRandomLoreChance() &&
!getPlugin().getNameManager().getBasicLore().isEmpty()) {
tt.addAll(getPlugin().getNameManager().randomLore());
}
im.setLore(tt);
if (im instanceof Repairable) {
Repairable r = (Repairable) im;
r.setRepairCost(1000);
itemstack.setItemMeta((ItemMeta) r);
} else {
itemstack.setItemMeta(im);
}
return itemstack;
}
|
diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java
index e087f976f..f4f6944c1 100644
--- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java
+++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java
@@ -1,1633 +1,1633 @@
package org.apache.maven.plugin;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.ArtifactFilterManager;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.metadata.ResolutionGroup;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.MultipleArtifactsNotFoundException;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.RuntimeInformation;
import org.apache.maven.lifecycle.statemgmt.StateManagementUtils;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.monitor.event.EventDispatcher;
import org.apache.maven.monitor.event.MavenEvents;
import org.apache.maven.monitor.logging.DefaultLog;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.Parameter;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.version.PluginVersionManager;
import org.apache.maven.plugin.version.PluginVersionNotFoundException;
import org.apache.maven.plugin.version.PluginVersionResolutionException;
import org.apache.maven.project.DuplicateArtifactAttachmentException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.artifact.InvalidDependencyVersionException;
import org.apache.maven.project.artifact.MavenMetadataSource;
import org.apache.maven.project.path.PathTranslator;
import org.apache.maven.realm.MavenRealmManager;
import org.apache.maven.realm.RealmManagementException;
import org.apache.maven.reporting.MavenReport;
import org.codehaus.plexus.MutablePlexusContainer;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import org.codehaus.plexus.component.configurator.ComponentConfigurator;
import org.codehaus.plexus.component.configurator.ConfigurationListener;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.component.repository.exception.ComponentRepositoryException;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.configuration.PlexusConfigurationException;
import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DefaultPluginManager
extends AbstractLogEnabled
implements PluginManager, Contextualizable
{
private static final List RESERVED_GROUP_IDS;
static
{
List rgids = new ArrayList();
rgids.add( StateManagementUtils.GROUP_ID );
RESERVED_GROUP_IDS = rgids;
}
protected MutablePlexusContainer container;
protected PluginDescriptorBuilder pluginDescriptorBuilder;
protected ArtifactFilterManager coreArtifactFilterManager;
private Log mojoLogger;
// component requirements
protected PathTranslator pathTranslator;
protected MavenPluginCollector pluginCollector;
protected PluginVersionManager pluginVersionManager;
protected ArtifactFactory artifactFactory;
protected ArtifactResolver artifactResolver;
protected ArtifactMetadataSource artifactMetadataSource;
protected RuntimeInformation runtimeInformation;
protected MavenProjectBuilder mavenProjectBuilder;
protected PluginMappingManager pluginMappingManager;
private PluginManagerSupport pluginManagerSupport;
// END component requirements
public DefaultPluginManager()
{
pluginDescriptorBuilder = new PluginDescriptorBuilder();
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public Plugin getPluginDefinitionForPrefix( String prefix,
MavenSession session,
MavenProject project )
{
// TODO: since this is only used in the lifecycle executor, maybe it should be moved there? There is no other
// use for the mapping manager in here
return pluginMappingManager.getByPrefix( prefix, session.getSettings().getPluginGroups(),
project.getRemoteArtifactRepositories(),
session.getLocalRepository() );
}
public PluginDescriptor verifyPlugin( Plugin plugin,
MavenProject project,
MavenSession session )
throws ArtifactResolutionException, PluginVersionResolutionException,
ArtifactNotFoundException, InvalidPluginException,
PluginManagerException, PluginNotFoundException, PluginVersionNotFoundException
{
String pluginVersion = plugin.getVersion();
// TODO: this should be possibly outside
// All version-resolution logic has been moved to DefaultPluginVersionManager.
getLogger().debug( "Resolving plugin: " + plugin.getKey() + " with version: " + pluginVersion );
if ( ( pluginVersion == null ) || Artifact.LATEST_VERSION.equals( pluginVersion ) || Artifact.RELEASE_VERSION.equals( pluginVersion ) )
{
getLogger().debug( "Resolving version for plugin: " + plugin.getKey() );
pluginVersion = pluginVersionManager.resolvePluginVersion( plugin.getGroupId(),
plugin.getArtifactId(),
project, session );
plugin.setVersion( pluginVersion );
getLogger().debug( "Resolved to version: " + pluginVersion );
}
return verifyVersionedPlugin( plugin, project, session );
}
private PluginDescriptor verifyVersionedPlugin( Plugin plugin,
MavenProject project,
MavenSession session )
throws PluginVersionResolutionException, ArtifactNotFoundException,
ArtifactResolutionException, InvalidPluginException,
PluginManagerException, PluginNotFoundException
{
getLogger().debug( "In verifyVersionedPlugin for: " + plugin.getKey() );
ArtifactRepository localRepository = session.getLocalRepository();
// TODO: this might result in an artifact "RELEASE" being resolved continuously
// FIXME: need to find out how a plugin gets marked as 'installed'
// and no ChildContainer exists. The check for that below fixes
// the 'Can't find plexus container for plugin: xxx' error.
try
{
// if the groupId is internal, don't try to resolve it...
if ( !RESERVED_GROUP_IDS.contains( plugin.getGroupId() ) )
{
Artifact pluginArtifact = pluginManagerSupport.resolvePluginArtifact( plugin, project, session );
addPlugin( plugin, pluginArtifact, project, session );
}
else
{
getLogger().debug(
"Skipping resolution for Maven built-in plugin: "
+ plugin.getKey() );
}
project.addPlugin( plugin );
}
catch ( ArtifactNotFoundException e )
{
String groupId = plugin.getGroupId();
String artifactId = plugin.getArtifactId();
String version = plugin.getVersion();
if ( ( groupId == null ) || ( artifactId == null ) || ( version == null ) )
{
throw new PluginNotFoundException( plugin, e );
}
else if ( groupId.equals( e.getGroupId() ) && artifactId.equals( e.getArtifactId() )
&& version.equals( e.getVersion() ) && "maven-plugin".equals( e.getType() ) )
{
throw new PluginNotFoundException( plugin, e );
}
else
{
throw e;
}
}
PluginDescriptor pluginDescriptor = pluginCollector.getPluginDescriptor( plugin );
setDescriptorClassAndArtifactInfo( pluginDescriptor, project, session, new ArrayList() );
return pluginDescriptor;
}
protected void addPlugin( Plugin plugin,
Artifact pluginArtifact,
MavenProject project,
MavenSession session )
throws ArtifactNotFoundException, ArtifactResolutionException, PluginManagerException,
InvalidPluginException
{
// ----------------------------------------------------------------------------
// Get the dependencies for the Plugin
// ----------------------------------------------------------------------------
// the only Plugin instance which will have dependencies is the one specified in the project.
// We need to look for a Plugin instance there, in case the instance we're using didn't come from
// the project.
Plugin projectPlugin = project.getPlugin( plugin.getKey() );
if ( projectPlugin == null )
{
projectPlugin = plugin;
}
else if ( projectPlugin.getVersion() == null )
{
projectPlugin.setVersion( plugin.getVersion() );
}
Set artifacts = getPluginArtifacts( pluginArtifact, projectPlugin, project,
session.getLocalRepository() );
getLogger().debug( "Got plugin artifacts:\n\n" + artifacts );
MavenRealmManager realmManager = session.getRealmManager();
ClassRealm pluginRealm = realmManager.getPluginRealm( projectPlugin );
if ( pluginRealm == null )
{
try
{
pluginRealm = realmManager.createPluginRealm( projectPlugin,
pluginArtifact,
artifacts,
coreArtifactFilterManager.getArtifactFilter() );
getLogger().debug( "Created realm: " + pluginRealm + " for plugin: " + projectPlugin.getKey() );
}
catch ( RealmManagementException e )
{
throw new PluginContainerException( plugin,
"Failed to create realm for plugin '"
+ projectPlugin, e );
}
try
{
getLogger().debug( "Discovering components in realm: " + pluginRealm );
container.discoverComponents( pluginRealm, false );
}
catch ( PlexusConfigurationException e )
{
throw new PluginContainerException( plugin, pluginRealm, "Error scanning plugin realm for components.", e );
}
catch ( ComponentRepositoryException e )
{
throw new PluginContainerException( plugin, pluginRealm, "Error scanning plugin realm for components.", e );
}
// ----------------------------------------------------------------------------
// The PluginCollector will now know about the plugin we are trying to load
// ----------------------------------------------------------------------------
getLogger().debug(
"Checking for plugin descriptor for: " + projectPlugin.getKey()
+ " with version: " + projectPlugin.getVersion() + " in collector: " + pluginCollector );
PluginDescriptor pluginDescriptor = pluginCollector.getPluginDescriptor( projectPlugin );
if ( pluginDescriptor == null )
{
if ( ( pluginRealm != null ) && getLogger().isDebugEnabled() )
{
getLogger().debug( "Plugin Realm: " );
pluginRealm.display();
}
getLogger().debug( "Removing invalid plugin realm." );
realmManager.disposePluginRealm( projectPlugin );
throw new PluginManagerException( projectPlugin, "The PluginDescriptor for the plugin "
+ projectPlugin.getKey() + " was not found. Should have been in realm: " + pluginRealm, project );
}
pluginDescriptor.setPluginArtifact( pluginArtifact );
getLogger().debug( "Realm for plugin: " + plugin.getKey() + ":\n" + pluginRealm );
}
else
{
List managedPluginArtifacts = realmManager.getPluginArtifacts( projectPlugin );
if ( ( managedPluginArtifacts == null ) || ( managedPluginArtifacts.isEmpty() && !artifacts.isEmpty() ) )
{
realmManager.setPluginArtifacts( projectPlugin, artifacts );
}
}
}
private Set getPluginArtifacts( Artifact pluginArtifact,
Plugin plugin,
MavenProject project,
ArtifactRepository localRepository )
throws InvalidPluginException, ArtifactNotFoundException, ArtifactResolutionException
{
Set projectPluginDependencies;
try
{
projectPluginDependencies = MavenMetadataSource.createArtifacts(
artifactFactory,
plugin.getDependencies(),
null,
coreArtifactFilterManager.getCoreArtifactFilter(),
project );
}
catch ( InvalidDependencyVersionException e )
{
throw new InvalidPluginException( "Plugin '" + plugin + "' is invalid: "
+ e.getMessage(), e );
}
ResolutionGroup resolutionGroup;
try
{
resolutionGroup = artifactMetadataSource.retrieve(
pluginArtifact,
localRepository,
project.getRemoteArtifactRepositories() );
}
catch ( ArtifactMetadataRetrievalException e )
{
throw new ArtifactResolutionException(
"Unable to download metadata from repository for plugin '"
+ pluginArtifact.getId() + "': "
+ e.getMessage(),
pluginArtifact, e );
}
/* get plugin managed versions */
Map pluginManagedDependencies = new HashMap();
try
{
MavenProject pluginProject =
mavenProjectBuilder.buildFromRepository( pluginArtifact, project.getRemoteArtifactRepositories(),
localRepository );
if ( pluginProject != null )
{
pluginManagedDependencies = pluginProject.getManagedVersionMap();
}
}
catch ( ProjectBuildingException e )
{
// this can't happen, it would have blowed up at artifactMetadataSource.retrieve()
}
// checkPlexusUtils( resolutionGroup, artifactFactory );
Set dependencies = new LinkedHashSet();
// resolve the plugin dependencies specified in <plugin><dependencies> first:
dependencies.addAll( projectPluginDependencies );
// followed by the plugin's default artifact set
dependencies.addAll( resolutionGroup.getArtifacts() );
LinkedHashSet repositories = new LinkedHashSet();
repositories.addAll( resolutionGroup.getResolutionRepositories() );
repositories.addAll( project.getRemoteArtifactRepositories() );
ArtifactFilter filter = new ScopeArtifactFilter( Artifact.SCOPE_RUNTIME );
ArtifactResolutionResult result = artifactResolver.resolveTransitively(
dependencies,
pluginArtifact,
pluginManagedDependencies,
localRepository,
repositories.isEmpty()
? Collections.EMPTY_LIST
: new ArrayList(
repositories ),
artifactMetadataSource,
filter );
Set resolved = new HashSet( result.getArtifacts() );
for ( Iterator it = resolved.iterator(); it.hasNext(); )
{
Artifact artifact = (Artifact) it.next();
if ( !artifact.equals( pluginArtifact ) )
{
artifact = project.replaceWithActiveArtifact( artifact );
}
}
getLogger().debug(
"Using the following artifacts for classpath of: "
+ pluginArtifact.getId() + ":\n\n"
+ resolved.toString().replace( ',', '\n' ) );
return resolved;
}
// ----------------------------------------------------------------------
// Mojo execution
// ----------------------------------------------------------------------
public void executeMojo( MavenProject project,
MojoExecution mojoExecution,
MavenSession session )
throws ArtifactResolutionException, MojoFailureException,
ArtifactNotFoundException, InvalidDependencyVersionException, PluginManagerException,
PluginConfigurationException
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
// NOTE: I'm putting these checks in here, since this is the central point of access for
// anything that wants to execute a mojo.
if ( mojoDescriptor.isProjectRequired() && !session.isUsingPOMsFromFilesystem() )
{
throw new PluginExecutionException( mojoExecution, project,
"Cannot execute mojo: "
+ mojoDescriptor.getGoal()
+ ". It requires a project with an existing pom.xml, but the build is not using one." );
}
if ( mojoDescriptor.isOnlineRequired() && session.getSettings().isOffline() )
{
// TODO: Should we error out, or simply warn and skip??
throw new PluginExecutionException( mojoExecution, project,
"Mojo: "
+ mojoDescriptor.getGoal()
+ " requires online mode for execution. Maven is currently offline." );
}
if ( mojoDescriptor.getDeprecated() != null )
{
getLogger().warn( "Mojo: " + mojoDescriptor.getGoal() + " is deprecated.\n" + mojoDescriptor.getDeprecated() );
}
if ( mojoDescriptor.isDependencyResolutionRequired() != null )
{
Collection projects;
if ( mojoDescriptor.isAggregator() )
{
projects = session.getSortedProjects();
}
else
{
projects = Collections.singleton( project );
}
for ( Iterator i = projects.iterator(); i.hasNext(); )
{
MavenProject p = (MavenProject) i.next();
resolveTransitiveDependencies( session,
artifactResolver,
mojoDescriptor.isDependencyResolutionRequired(),
artifactFactory,
p,
mojoDescriptor.isAggregator() );
}
downloadDependencies( project, session, artifactResolver );
}
String goalName = mojoDescriptor.getFullGoalName();
Mojo mojo = null;
PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();
Xpp3Dom dom = mojoExecution.getConfiguration();
if ( dom != null )
{
// make a defensive copy, to keep things from getting polluted.
dom = new Xpp3Dom( dom );
}
// Event monitoring.
String event = MavenEvents.MOJO_EXECUTION;
EventDispatcher dispatcher = session.getEventDispatcher();
String goalExecId = goalName;
if ( mojoExecution.getExecutionId() != null )
{
goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}";
}
// by this time, the pluginDescriptor has had the correct realm setup from getConfiguredMojo(..)
ClassRealm pluginRealm = null;
ClassRealm oldLookupRealm = container.getLookupRealm();
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
List realmActions = new ArrayList();
try
{
mojo = getConfiguredMojo( session, dom, project, false, mojoExecution, realmActions );
dispatcher.dispatchStart( event, goalExecId );
pluginRealm = pluginDescriptor.getClassRealm();
getLogger().debug( "Setting context classloader for plugin to: " + pluginRealm.getId() + " (instance is: " + pluginRealm + ")" );
Thread.currentThread().setContextClassLoader( pluginRealm );
// NOTE: DuplicateArtifactAttachmentException is currently unchecked, so be careful removing this try/catch!
// This is necessary to avoid creating compatibility problems for existing plugins that use
// MavenProjectHelper.attachArtifact(..).
try
{
mojo.execute();
}
catch( DuplicateArtifactAttachmentException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw new PluginExecutionException( mojoExecution, project, e );
}
// NEW: If the mojo that just executed is a report, store it in the LifecycleExecutionContext
// for reference by future mojos.
if ( mojo instanceof MavenReport )
{
session.addReport( mojoDescriptor, (MavenReport) mojo );
}
dispatcher.dispatchEnd( event, goalExecId );
}
catch ( MojoExecutionException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw new PluginExecutionException( mojoExecution, project, e );
}
catch ( MojoFailureException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw e;
}
catch ( LinkageError e )
{
if ( getLogger().isFatalErrorEnabled() )
{
getLogger().fatalError(
- mojo.getClass().getName() + "#execute() caused a linkage error ("
+ mojoDescriptor.getImplementation() + "#execute() caused a linkage error ("
+ e.getClass().getName() + ") and may be out-of-date. Check the realms:" );
StringBuffer sb = new StringBuffer();
sb.append( "Plugin realm = " + pluginRealm.getId() ).append( '\n' );
for ( int i = 0; i < pluginRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + pluginRealm.getURLs()[i] );
if ( i != ( pluginRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
ClassRealm containerRealm = container.getContainerRealm();
sb = new StringBuffer();
sb.append( "Container realm = " + containerRealm.getId() ).append( '\n' );
for ( int i = 0; i < containerRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + containerRealm.getURLs()[i] );
if ( i != ( containerRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
}
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw e;
}
finally
{
if ( mojo != null )
{
try
{
container.release( mojo );
}
catch ( ComponentLifecycleException e )
{
getLogger().debug( "Error releasing mojo for: " + goalExecId, e );
}
}
pluginDescriptor.setClassRealm( null );
pluginDescriptor.setArtifacts( null );
for ( Iterator it = realmActions.iterator(); it.hasNext(); )
{
PluginRealmAction action = (PluginRealmAction) it.next();
action.undo();
}
if ( oldLookupRealm != null )
{
container.setLookupRealm( oldLookupRealm );
}
Thread.currentThread().setContextClassLoader( oldClassLoader );
}
}
private Plugin createDummyPlugin( PluginDescriptor pluginDescriptor )
{
Plugin plugin = new Plugin();
plugin.setGroupId( pluginDescriptor.getGroupId() );
plugin.setArtifactId( pluginDescriptor.getArtifactId() );
plugin.setVersion( pluginDescriptor.getVersion() );
return plugin;
}
public MavenReport getReport( MavenProject project,
MojoExecution mojoExecution,
MavenSession session )
throws ArtifactNotFoundException, PluginConfigurationException, PluginManagerException,
ArtifactResolutionException
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
PluginDescriptor descriptor = mojoDescriptor.getPluginDescriptor();
Xpp3Dom dom = project.getReportConfiguration( descriptor.getGroupId(),
descriptor.getArtifactId(),
mojoExecution.getExecutionId() );
if ( mojoExecution.getConfiguration() != null )
{
dom = Xpp3Dom.mergeXpp3Dom( dom, mojoExecution.getConfiguration() );
}
return (MavenReport) getConfiguredMojo( session, dom, project, true, mojoExecution, new ArrayList() );
}
public PluginDescriptor verifyReportPlugin( ReportPlugin reportPlugin,
MavenProject project,
MavenSession session )
throws PluginVersionResolutionException, ArtifactResolutionException,
ArtifactNotFoundException, InvalidPluginException,
PluginManagerException, PluginNotFoundException, PluginVersionNotFoundException
{
String version = reportPlugin.getVersion();
if ( version == null )
{
version = pluginVersionManager.resolveReportPluginVersion(
reportPlugin.getGroupId(),
reportPlugin.getArtifactId(),
project, session );
reportPlugin.setVersion( version );
}
Plugin forLookup = new Plugin();
forLookup.setGroupId( reportPlugin.getGroupId() );
forLookup.setArtifactId( reportPlugin.getArtifactId() );
forLookup.setVersion( version );
return verifyVersionedPlugin( forLookup, project, session );
}
private Mojo getConfiguredMojo( MavenSession session,
Xpp3Dom dom,
MavenProject project,
boolean report,
MojoExecution mojoExecution,
List realmActions )
throws PluginConfigurationException, PluginManagerException
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();
setDescriptorClassAndArtifactInfo( pluginDescriptor, project, session, realmActions );
ClassRealm pluginRealm = pluginDescriptor.getClassRealm();
if ( mojoDescriptor.isRequiresReports() )
{
Set reportDescriptors = session.getReportMojoDescriptors();
if ( ( reportDescriptors != null ) && !reportDescriptors.isEmpty() )
{
for ( Iterator it = reportDescriptors.iterator(); it.hasNext(); )
{
MojoDescriptor reportDescriptor = (MojoDescriptor) it.next();
setDescriptorClassAndArtifactInfo( reportDescriptor.getPluginDescriptor(), project, session, realmActions );
}
}
}
// We are forcing the use of the plugin realm for all lookups that might occur during
// the lifecycle that is part of the lookup. Here we are specifically trying to keep
// lookups that occur in contextualize calls in line with the right realm.
container.setLookupRealm( pluginRealm );
getLogger().debug(
"Looking up mojo " + mojoDescriptor.getRoleHint() + " in realm "
+ pluginRealm.getId() + " - descRealmId="
+ mojoDescriptor.getRealmId() );
Mojo mojo;
try
{
mojo = (Mojo) container.lookup( Mojo.ROLE, mojoDescriptor.getRoleHint(), pluginRealm );
}
catch ( ComponentLookupException e )
{
throw new PluginContainerException( mojoDescriptor, pluginRealm, "Unable to find the mojo '"
+ mojoDescriptor.getRoleHint() + "' in the plugin '"
+ pluginDescriptor.getPluginLookupKey() + "'", e );
}
if ( mojo != null )
{
getLogger().debug(
"Looked up - " + mojo + " - "
+ mojo.getClass().getClassLoader() );
}
else
{
getLogger().warn( "No luck." );
}
if ( report && !( mojo instanceof MavenReport ) )
{
// TODO: the mojoDescriptor should actually capture this information so we don't get this far
return null;
}
if ( mojo instanceof ContextEnabled )
{
Map pluginContext = session.getPluginContext( pluginDescriptor, project );
pluginContext.put( "project", project );
pluginContext.put( "pluginDescriptor", pluginDescriptor );
( (ContextEnabled) mojo ).setPluginContext( pluginContext );
}
mojo.setLog( mojoLogger );
XmlPlexusConfiguration pomConfiguration;
if ( dom == null )
{
pomConfiguration = new XmlPlexusConfiguration( "configuration" );
}
else
{
pomConfiguration = new XmlPlexusConfiguration( dom );
}
// Validate against non-editable (@readonly) parameters, to make sure users aren't trying to
// override in the POM.
validatePomConfiguration( mojoDescriptor, pomConfiguration );
PlexusConfiguration mergedConfiguration = mergeMojoConfiguration( pomConfiguration,
mojoDescriptor );
// TODO: plexus changes to make this more like the component descriptor so this can be used instead
// PlexusConfiguration mergedConfiguration = mergeConfiguration( pomConfiguration,
// mojoDescriptor.getConfiguration() );
ExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator(
session,
mojoExecution,
pathTranslator,
getLogger(),
session.getExecutionProperties() );
PlexusConfiguration extractedMojoConfiguration = extractMojoConfiguration(
mergedConfiguration,
mojoDescriptor );
checkDeprecatedParameters( mojoDescriptor, pomConfiguration );
checkRequiredParameters( mojoDescriptor, extractedMojoConfiguration, expressionEvaluator );
populatePluginFields( mojo, mojoDescriptor, extractedMojoConfiguration, expressionEvaluator );
return mojo;
}
private void checkDeprecatedParameters( MojoDescriptor mojoDescriptor,
PlexusConfiguration extractedMojoConfiguration )
{
if ( ( extractedMojoConfiguration == null ) || ( extractedMojoConfiguration.getChildCount() < 1 ) )
{
return;
}
List parameters = mojoDescriptor.getParameters();
if ( ( parameters != null ) && !parameters.isEmpty() )
{
for ( Iterator it = parameters.iterator(); it.hasNext(); )
{
Parameter param = (Parameter) it.next();
if ( param.getDeprecated() != null )
{
boolean warnOfDeprecation = false;
PlexusConfiguration child = extractedMojoConfiguration.getChild( param.getName() );
try
{
if ( ( child != null ) && ( child.getValue() != null ) )
{
warnOfDeprecation = true;
}
else if ( param.getAlias() != null)
{
child = extractedMojoConfiguration.getChild( param.getAlias() );
if ( ( child != null ) && ( child.getValue() != null ) )
{
warnOfDeprecation = true;
}
}
}
catch ( PlexusConfigurationException e )
{
// forget it, this is just for deprecation checking, after all...
}
if ( warnOfDeprecation )
{
StringBuffer buffer = new StringBuffer();
buffer.append( "In mojo: " ).append( mojoDescriptor.getGoal() ).append( ", parameter: " ).append( param.getName() );
if ( param.getAlias() != null )
{
buffer.append( " (alias: " ).append( param.getAlias() ).append( ")" );
}
buffer.append( " is deprecated:" ).append( "\n\n" ).append( param.getDeprecated() ).append( "\n" );
getLogger().warn( buffer.toString() );
}
}
}
}
}
private void setDescriptorClassAndArtifactInfo( PluginDescriptor pluginDescriptor,
MavenProject project,
MavenSession session,
List realmActions )
{
MavenRealmManager realmManager = session.getRealmManager();
ClassRealm projectRealm = realmManager.getProjectRealm( project.getGroupId(), project.getArtifactId(), project.getVersion() );
if ( projectRealm == null )
{
getLogger().debug( "Realm for project: " + project.getId() + " not found. Using container realm instead." );
projectRealm = container.getContainerRealm();
}
Plugin plugin = project.getPlugin( pluginDescriptor.getPluginLookupKey() );
if ( plugin == null )
{
plugin = createDummyPlugin( pluginDescriptor );
}
ClassRealm pluginRealm = realmManager.getPluginRealm( plugin );
if ( pluginRealm == null )
{
getLogger().debug( "Realm for plugin: " + pluginDescriptor.getId() + " not found. Using project realm instead." );
pluginRealm = projectRealm;
realmActions.add( new PluginRealmAction( pluginDescriptor ) );
}
else
{
pluginRealm.setParentRealm( projectRealm );
realmActions.add( new PluginRealmAction( pluginDescriptor, pluginRealm ) );
}
getLogger().debug( "Setting realm for plugin descriptor: " + pluginDescriptor.getId() + " to: " + pluginRealm );
pluginDescriptor.setClassRealm( pluginRealm );
pluginDescriptor.setArtifacts( realmManager.getPluginArtifacts( plugin ) );
}
private PlexusConfiguration extractMojoConfiguration( PlexusConfiguration mergedConfiguration,
MojoDescriptor mojoDescriptor )
{
Map parameterMap = mojoDescriptor.getParameterMap();
PlexusConfiguration[] mergedChildren = mergedConfiguration.getChildren();
XmlPlexusConfiguration extractedConfiguration = new XmlPlexusConfiguration( "configuration" );
for ( int i = 0; i < mergedChildren.length; i++ )
{
PlexusConfiguration child = mergedChildren[i];
if ( parameterMap.containsKey( child.getName() ) )
{
extractedConfiguration.addChild( copyConfiguration( child ) );
}
else
{
// TODO: I defy anyone to find these messages in the '-X' output! Do we need a new log level?
// ideally, this would be elevated above the true debug output, but below the default INFO level...
// [BP] (2004-07-18): need to understand the context more but would prefer this could be either WARN or
// removed - shouldn't need DEBUG to diagnose a problem most of the time.
getLogger().debug(
"*** WARNING: Configuration \'" + child.getName()
+ "\' is not used in goal \'"
+ mojoDescriptor.getFullGoalName()
+ "; this may indicate a typo... ***" );
}
}
return extractedConfiguration;
}
private void checkRequiredParameters( MojoDescriptor goal,
PlexusConfiguration configuration,
ExpressionEvaluator expressionEvaluator )
throws PluginConfigurationException
{
// TODO: this should be built in to the configurator, as we presently double process the expressions
List parameters = goal.getParameters();
if ( parameters == null )
{
return;
}
List invalidParameters = new ArrayList();
for ( int i = 0; i < parameters.size(); i++ )
{
Parameter parameter = (Parameter) parameters.get( i );
if ( parameter.isRequired() )
{
// the key for the configuration map we're building.
String key = parameter.getName();
Object fieldValue = null;
String expression = null;
PlexusConfiguration value = configuration.getChild( key, false );
try
{
if ( value != null )
{
expression = value.getValue( null );
fieldValue = expressionEvaluator.evaluate( expression );
if ( fieldValue == null )
{
fieldValue = value.getAttribute( "default-value", null );
}
}
if ( ( fieldValue == null ) && StringUtils.isNotEmpty( parameter.getAlias() ) )
{
value = configuration.getChild( parameter.getAlias(), false );
if ( value != null )
{
expression = value.getValue( null );
fieldValue = expressionEvaluator.evaluate( expression );
if ( fieldValue == null )
{
fieldValue = value.getAttribute( "default-value", null );
}
}
}
}
catch ( ExpressionEvaluationException e )
{
throw new PluginConfigurationException( goal.getPluginDescriptor(),
e.getMessage(), e );
}
// only mark as invalid if there are no child nodes
if ( ( fieldValue == null )
&& ( ( value == null ) || ( value.getChildCount() == 0 ) ) )
{
parameter.setExpression( expression );
invalidParameters.add( parameter );
}
}
}
if ( !invalidParameters.isEmpty() )
{
throw new PluginParameterException( goal, invalidParameters );
}
}
private void validatePomConfiguration( MojoDescriptor goal,
PlexusConfiguration pomConfiguration )
throws PluginConfigurationException
{
List parameters = goal.getParameters();
if ( parameters == null )
{
return;
}
for ( int i = 0; i < parameters.size(); i++ )
{
Parameter parameter = (Parameter) parameters.get( i );
// the key for the configuration map we're building.
String key = parameter.getName();
PlexusConfiguration value = pomConfiguration.getChild( key, false );
if ( ( value == null ) && StringUtils.isNotEmpty( parameter.getAlias() ) )
{
key = parameter.getAlias();
value = pomConfiguration.getChild( key, false );
}
if ( value != null )
{
// Make sure the parameter is either editable/configurable, or else is NOT specified in the POM
if ( !parameter.isEditable() )
{
StringBuffer errorMessage = new StringBuffer().append( "ERROR: Cannot override read-only parameter: " );
errorMessage.append( key );
errorMessage.append( " in goal: " ).append( goal.getFullGoalName() );
throw new PluginConfigurationException( goal.getPluginDescriptor(),
errorMessage.toString() );
}
String deprecated = parameter.getDeprecated();
if ( StringUtils.isNotEmpty( deprecated ) )
{
getLogger().warn( "DEPRECATED [" + parameter.getName() + "]: " + deprecated );
}
}
}
}
private PlexusConfiguration mergeMojoConfiguration( XmlPlexusConfiguration fromPom,
MojoDescriptor mojoDescriptor )
{
XmlPlexusConfiguration result = new XmlPlexusConfiguration( fromPom.getName() );
result.setValue( fromPom.getValue( null ) );
if ( mojoDescriptor.getParameters() != null )
{
PlexusConfiguration fromMojo = mojoDescriptor.getMojoConfiguration();
for ( Iterator it = mojoDescriptor.getParameters().iterator(); it.hasNext(); )
{
Parameter parameter = (Parameter) it.next();
String paramName = parameter.getName();
String alias = parameter.getAlias();
String implementation = parameter.getImplementation();
PlexusConfiguration pomConfig = fromPom.getChild( paramName );
PlexusConfiguration aliased = null;
if ( alias != null )
{
aliased = fromPom.getChild( alias );
}
PlexusConfiguration mojoConfig = fromMojo.getChild( paramName, false );
// first we'll merge configurations from the aliased and real params.
// TODO: Is this the right thing to do?
if ( aliased != null )
{
if ( pomConfig == null )
{
pomConfig = new XmlPlexusConfiguration( paramName );
}
pomConfig = buildTopDownMergedConfiguration( pomConfig, aliased );
}
PlexusConfiguration toAdd = null;
if ( pomConfig != null )
{
pomConfig = buildTopDownMergedConfiguration( pomConfig, mojoConfig );
if ( StringUtils.isNotEmpty( pomConfig.getValue( null ) )
|| ( pomConfig.getChildCount() > 0 ) )
{
toAdd = pomConfig;
}
}
if ( ( toAdd == null ) && ( mojoConfig != null ) )
{
toAdd = copyConfiguration( mojoConfig );
}
if ( toAdd != null )
{
if ( ( implementation != null )
&& ( toAdd.getAttribute( "implementation", null ) == null ) )
{
XmlPlexusConfiguration implementationConf = new XmlPlexusConfiguration(
paramName );
implementationConf.setAttribute( "implementation",
parameter.getImplementation() );
toAdd = buildTopDownMergedConfiguration( toAdd, implementationConf );
}
result.addChild( toAdd );
}
}
}
return result;
}
private XmlPlexusConfiguration buildTopDownMergedConfiguration( PlexusConfiguration dominant,
PlexusConfiguration recessive )
{
XmlPlexusConfiguration result = new XmlPlexusConfiguration( dominant.getName() );
String value = dominant.getValue( null );
if ( StringUtils.isEmpty( value ) && ( recessive != null ) )
{
value = recessive.getValue( null );
}
if ( StringUtils.isNotEmpty( value ) )
{
result.setValue( value );
}
String[] attributeNames = dominant.getAttributeNames();
for ( int i = 0; i < attributeNames.length; i++ )
{
String attributeValue = dominant.getAttribute( attributeNames[i], null );
result.setAttribute( attributeNames[i], attributeValue );
}
if ( recessive != null )
{
attributeNames = recessive.getAttributeNames();
for ( int i = 0; i < attributeNames.length; i++ )
{
String attributeValue = recessive.getAttribute( attributeNames[i], null );
// TODO: recessive seems to be dominant here?
result.setAttribute( attributeNames[i], attributeValue );
}
}
PlexusConfiguration[] children = dominant.getChildren();
for ( int i = 0; i < children.length; i++ )
{
PlexusConfiguration childDom = children[i];
PlexusConfiguration childRec = recessive == null ? null
: recessive.getChild( childDom.getName(), false );
if ( childRec != null )
{
result.addChild( buildTopDownMergedConfiguration( childDom, childRec ) );
}
else
{ // FIXME: copy, or use reference?
result.addChild( copyConfiguration( childDom ) );
}
}
return result;
}
public static PlexusConfiguration copyConfiguration( PlexusConfiguration src )
{
// TODO: shouldn't be necessary
XmlPlexusConfiguration dom = new XmlPlexusConfiguration( src.getName() );
dom.setValue( src.getValue( null ) );
String[] attributeNames = src.getAttributeNames();
for ( int i = 0; i < attributeNames.length; i++ )
{
String attributeName = attributeNames[i];
dom.setAttribute( attributeName, src.getAttribute( attributeName, null ) );
}
PlexusConfiguration[] children = src.getChildren();
for ( int i = 0; i < children.length; i++ )
{
dom.addChild( copyConfiguration( children[i] ) );
}
return dom;
}
// ----------------------------------------------------------------------
// Mojo Parameter Handling
// ----------------------------------------------------------------------
private void populatePluginFields( Mojo plugin,
MojoDescriptor mojoDescriptor,
PlexusConfiguration configuration,
ExpressionEvaluator expressionEvaluator )
throws PluginConfigurationException
{
ComponentConfigurator configurator = null;
// TODO: What is the point in using the plugin realm here instead of the core realm?
ClassRealm realm = mojoDescriptor.getPluginDescriptor().getClassRealm();
try
{
String configuratorId = mojoDescriptor.getComponentConfigurator();
// TODO: could the configuration be passed to lookup and the configurator known to plexus via the descriptor
// so that this meethod could entirely be handled by a plexus lookup?
if ( StringUtils.isNotEmpty( configuratorId ) )
{
configurator = (ComponentConfigurator) container.lookup( ComponentConfigurator.ROLE, configuratorId, realm );
}
else
{
configurator = (ComponentConfigurator) container.lookup( ComponentConfigurator.ROLE, "basic", realm );
}
ConfigurationListener listener = new DebugConfigurationListener( getLogger() );
getLogger().debug( "Configuring mojo '" + mojoDescriptor.getId() + "' with "
+ ( configuratorId == null ? "basic" : configuratorId )
+ " configurator -->" );
// This needs to be able to use methods
configurator.configureComponent( plugin, configuration, expressionEvaluator, realm, listener );
getLogger().debug( "-- end configuration --" );
}
catch ( ComponentConfigurationException e )
{
throw new PluginConfigurationException(
mojoDescriptor.getPluginDescriptor(),
"Unable to parse the created DOM for plugin configuration",
e );
}
catch ( ComponentLookupException e )
{
throw new PluginConfigurationException(
mojoDescriptor.getPluginDescriptor(),
"Unable to retrieve component configurator for plugin configuration",
e );
}
catch ( LinkageError e )
{
if ( getLogger().isFatalErrorEnabled() )
{
getLogger().fatalError(
configurator.getClass().getName() + "#configureComponent(...) caused a linkage error ("
+ e.getClass().getName() + ") and may be out-of-date. Check the realms:" );
ClassRealm pluginRealm = mojoDescriptor.getPluginDescriptor().getClassRealm();
StringBuffer sb = new StringBuffer();
sb.append( "Plugin realm = " + pluginRealm.getId() ).append( '\n' );
for ( int i = 0; i < pluginRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + pluginRealm.getURLs()[i] );
if ( i != ( pluginRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
ClassRealm containerRealm = container.getContainerRealm();
sb = new StringBuffer();
sb.append( "Container realm = " + containerRealm.getId() ).append( '\n' );
for ( int i = 0; i < containerRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + containerRealm.getURLs()[i] );
if ( i != ( containerRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
}
throw new PluginConfigurationException(
mojoDescriptor.getPluginDescriptor(),
e.getClass().getName() + ": " + e.getMessage(),
new ComponentConfigurationException( e ) );
}
finally
{
if ( configurator != null )
{
try
{
container.release( configurator );
}
catch ( ComponentLifecycleException e )
{
getLogger().debug( "Failed to release plugin container - ignoring." );
}
}
}
}
public static String createPluginParameterRequiredMessage( MojoDescriptor mojo,
Parameter parameter,
String expression )
{
StringBuffer message = new StringBuffer();
message.append( "The '" );
message.append( parameter.getName() );
message.append( "' parameter is required for the execution of the " );
message.append( mojo.getFullGoalName() );
message.append( " mojo and cannot be null." );
if ( expression != null )
{
message.append( " The retrieval expression was: " ).append( expression );
}
return message.toString();
}
// ----------------------------------------------------------------------
// Lifecycle
// ----------------------------------------------------------------------
public void contextualize( Context context )
throws ContextException
{
container = (MutablePlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
mojoLogger = new DefaultLog( container.getLoggerManager().getLoggerForComponent( Mojo.ROLE ) );
}
// ----------------------------------------------------------------------
// Artifact resolution
// ----------------------------------------------------------------------
private void resolveTransitiveDependencies( MavenSession context,
ArtifactResolver artifactResolver,
String scope,
ArtifactFactory artifactFactory,
MavenProject project,
boolean isAggregator )
throws ArtifactResolutionException, ArtifactNotFoundException,
InvalidDependencyVersionException
{
ArtifactFilter filter = new ScopeArtifactFilter( scope );
// TODO: such a call in MavenMetadataSource too - packaging not really the intention of type
Artifact artifact = artifactFactory.createBuildArtifact( project.getGroupId(),
project.getArtifactId(),
project.getVersion(),
project.getPackaging() );
// TODO: we don't need to resolve over and over again, as long as we are sure that the parameters are the same
// check this with yourkit as a hot spot.
// Don't recreate if already created - for effeciency, and because clover plugin adds to it
if ( project.getDependencyArtifacts() == null )
{
// NOTE: Don't worry about covering this case with the error-reporter bindings...it's already handled by the project error reporter.
project.setDependencyArtifacts( project.createArtifacts( artifactFactory, null, null ) );
}
Set resolvedArtifacts;
try
{
ArtifactResolutionResult result = artifactResolver.resolveTransitively(
project.getDependencyArtifacts(),
artifact,
project.getManagedVersionMap(),
context.getLocalRepository(),
project.getRemoteArtifactRepositories(),
artifactMetadataSource,
filter );
resolvedArtifacts = result.getArtifacts();
}
catch( MultipleArtifactsNotFoundException e )
{
/*only do this if we are an aggregating plugin: MNG-2277
if the dependency doesn't yet exist but is in the reactor, then
all we can do is warn and skip it. A better fix can be inserted into 2.1*/
if ( isAggregator
&& checkMissingArtifactsInReactor( context.getSortedProjects(),
e.getMissingArtifacts() ) )
{
resolvedArtifacts = new HashSet( e.getResolvedArtifacts() );
}
else
{
//we can't find all the artifacts in the reactor so bubble the exception up.
throw e;
}
}
project.setArtifacts( resolvedArtifacts );
}
/**
* This method is checking to see if the artifacts that can't be resolved are all
* part of this reactor. This is done to prevent a chicken or egg scenario with
* fresh projects that have a plugin that is an aggregator and requires dependencies. See
* MNG-2277 for more info.
*
* NOTE: If this happens, it most likely means the project-artifact for an
* interproject dependency doesn't have a file yet (it hasn't been built yet).
*
* @param projects the sibling projects in the reactor
* @param missing the artifacts that can't be found
* @return true if ALL missing artifacts are found in the reactor.
*/
private boolean checkMissingArtifactsInReactor( Collection projects,
Collection missing )
{
Collection foundInReactor = new HashSet();
Iterator iter = missing.iterator();
while ( iter.hasNext() )
{
Artifact mArtifact = (Artifact) iter.next();
Iterator pIter = projects.iterator();
while ( pIter.hasNext() )
{
MavenProject p = (MavenProject) pIter.next();
if ( p.getArtifactId().equals( mArtifact.getArtifactId() )
&& p.getGroupId().equals( mArtifact.getGroupId() )
&& p.getVersion().equals( mArtifact.getVersion() ) )
{
//TODO: the packaging could be different, but the exception doesn't contain that info
//most likely it would be produced by the project we just found in the reactor since all
//the other info matches. Assume it's ok.
getLogger().warn( "The dependency: "
+ p.getId()
+ " can't be resolved but has been found in the reactor.\nThis dependency has been excluded from the plugin execution. You should rerun this mojo after executing mvn install.\n" );
//found it, move on.
foundInReactor.add( p );
break;
}
}
}
//if all of them have been found, we can continue.
return foundInReactor.size() == missing.size();
}
// ----------------------------------------------------------------------
// Artifact downloading
// ----------------------------------------------------------------------
private void downloadDependencies( MavenProject project,
MavenSession context,
ArtifactResolver artifactResolver )
throws ArtifactResolutionException, ArtifactNotFoundException
{
ArtifactRepository localRepository = context.getLocalRepository();
List remoteArtifactRepositories = project.getRemoteArtifactRepositories();
for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); )
{
Artifact artifact = (Artifact) it.next();
artifactResolver.resolve( artifact, remoteArtifactRepositories, localRepository );
}
}
public static void checkPlexusUtils( ResolutionGroup resolutionGroup,
ArtifactFactory artifactFactory )
{
// ----------------------------------------------------------------------------
// If the plugin already declares a dependency on plexus-utils then we're all
// set as the plugin author is aware of its use. If we don't have a dependency
// on plexus-utils then we must protect users from stupid plugin authors who
// did not declare a direct dependency on plexus-utils because the version
// Maven uses is hidden from downstream use. We will also bump up any
// anything below 1.1 to 1.1 as this mimics the behaviour in 2.0.5 where
// plexus-utils 1.1 was being forced into use.
// ----------------------------------------------------------------------------
VersionRange vr = null;
try
{
vr = VersionRange.createFromVersionSpec( "[1.1,)" );
}
catch ( InvalidVersionSpecificationException e )
{
// Won't happen
}
boolean plexusUtilsPresent = false;
for ( Iterator i = resolutionGroup.getArtifacts().iterator(); i.hasNext(); )
{
Artifact a = (Artifact) i.next();
if ( a.getArtifactId().equals( "plexus-utils" )
&& vr.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) )
{
plexusUtilsPresent = true;
break;
}
}
if ( !plexusUtilsPresent )
{
// We will add plexus-utils as every plugin was getting this anyway from Maven itself. We will set the
// version to the latest version we know that works as of the 2.0.6 release. We set the scope to runtime
// as this is what's implicitly happening in 2.0.6.
resolutionGroup.getArtifacts()
.add(
artifactFactory.createArtifact( "org.codehaus.plexus",
"plexus-utils", "1.1",
Artifact.SCOPE_RUNTIME, "jar" ) );
}
}
private static final class PluginRealmAction
{
private final PluginDescriptor pluginDescriptor;
private final ClassRealm realmWithTransientParent;
PluginRealmAction( PluginDescriptor pluginDescriptor )
{
this.pluginDescriptor = pluginDescriptor;
realmWithTransientParent = null;
}
PluginRealmAction( PluginDescriptor pluginDescriptor, ClassRealm realmWithTransientParent )
{
this.pluginDescriptor = pluginDescriptor;
this.realmWithTransientParent = realmWithTransientParent;
}
void undo()
{
pluginDescriptor.setArtifacts( null );
pluginDescriptor.setClassRealm( null );
if ( realmWithTransientParent != null )
{
realmWithTransientParent.setParentRealm( null );
}
}
}
}
| true | true | public void executeMojo( MavenProject project,
MojoExecution mojoExecution,
MavenSession session )
throws ArtifactResolutionException, MojoFailureException,
ArtifactNotFoundException, InvalidDependencyVersionException, PluginManagerException,
PluginConfigurationException
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
// NOTE: I'm putting these checks in here, since this is the central point of access for
// anything that wants to execute a mojo.
if ( mojoDescriptor.isProjectRequired() && !session.isUsingPOMsFromFilesystem() )
{
throw new PluginExecutionException( mojoExecution, project,
"Cannot execute mojo: "
+ mojoDescriptor.getGoal()
+ ". It requires a project with an existing pom.xml, but the build is not using one." );
}
if ( mojoDescriptor.isOnlineRequired() && session.getSettings().isOffline() )
{
// TODO: Should we error out, or simply warn and skip??
throw new PluginExecutionException( mojoExecution, project,
"Mojo: "
+ mojoDescriptor.getGoal()
+ " requires online mode for execution. Maven is currently offline." );
}
if ( mojoDescriptor.getDeprecated() != null )
{
getLogger().warn( "Mojo: " + mojoDescriptor.getGoal() + " is deprecated.\n" + mojoDescriptor.getDeprecated() );
}
if ( mojoDescriptor.isDependencyResolutionRequired() != null )
{
Collection projects;
if ( mojoDescriptor.isAggregator() )
{
projects = session.getSortedProjects();
}
else
{
projects = Collections.singleton( project );
}
for ( Iterator i = projects.iterator(); i.hasNext(); )
{
MavenProject p = (MavenProject) i.next();
resolveTransitiveDependencies( session,
artifactResolver,
mojoDescriptor.isDependencyResolutionRequired(),
artifactFactory,
p,
mojoDescriptor.isAggregator() );
}
downloadDependencies( project, session, artifactResolver );
}
String goalName = mojoDescriptor.getFullGoalName();
Mojo mojo = null;
PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();
Xpp3Dom dom = mojoExecution.getConfiguration();
if ( dom != null )
{
// make a defensive copy, to keep things from getting polluted.
dom = new Xpp3Dom( dom );
}
// Event monitoring.
String event = MavenEvents.MOJO_EXECUTION;
EventDispatcher dispatcher = session.getEventDispatcher();
String goalExecId = goalName;
if ( mojoExecution.getExecutionId() != null )
{
goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}";
}
// by this time, the pluginDescriptor has had the correct realm setup from getConfiguredMojo(..)
ClassRealm pluginRealm = null;
ClassRealm oldLookupRealm = container.getLookupRealm();
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
List realmActions = new ArrayList();
try
{
mojo = getConfiguredMojo( session, dom, project, false, mojoExecution, realmActions );
dispatcher.dispatchStart( event, goalExecId );
pluginRealm = pluginDescriptor.getClassRealm();
getLogger().debug( "Setting context classloader for plugin to: " + pluginRealm.getId() + " (instance is: " + pluginRealm + ")" );
Thread.currentThread().setContextClassLoader( pluginRealm );
// NOTE: DuplicateArtifactAttachmentException is currently unchecked, so be careful removing this try/catch!
// This is necessary to avoid creating compatibility problems for existing plugins that use
// MavenProjectHelper.attachArtifact(..).
try
{
mojo.execute();
}
catch( DuplicateArtifactAttachmentException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw new PluginExecutionException( mojoExecution, project, e );
}
// NEW: If the mojo that just executed is a report, store it in the LifecycleExecutionContext
// for reference by future mojos.
if ( mojo instanceof MavenReport )
{
session.addReport( mojoDescriptor, (MavenReport) mojo );
}
dispatcher.dispatchEnd( event, goalExecId );
}
catch ( MojoExecutionException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw new PluginExecutionException( mojoExecution, project, e );
}
catch ( MojoFailureException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw e;
}
catch ( LinkageError e )
{
if ( getLogger().isFatalErrorEnabled() )
{
getLogger().fatalError(
mojo.getClass().getName() + "#execute() caused a linkage error ("
+ e.getClass().getName() + ") and may be out-of-date. Check the realms:" );
StringBuffer sb = new StringBuffer();
sb.append( "Plugin realm = " + pluginRealm.getId() ).append( '\n' );
for ( int i = 0; i < pluginRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + pluginRealm.getURLs()[i] );
if ( i != ( pluginRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
ClassRealm containerRealm = container.getContainerRealm();
sb = new StringBuffer();
sb.append( "Container realm = " + containerRealm.getId() ).append( '\n' );
for ( int i = 0; i < containerRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + containerRealm.getURLs()[i] );
if ( i != ( containerRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
}
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw e;
}
finally
{
if ( mojo != null )
{
try
{
container.release( mojo );
}
catch ( ComponentLifecycleException e )
{
getLogger().debug( "Error releasing mojo for: " + goalExecId, e );
}
}
pluginDescriptor.setClassRealm( null );
pluginDescriptor.setArtifacts( null );
for ( Iterator it = realmActions.iterator(); it.hasNext(); )
{
PluginRealmAction action = (PluginRealmAction) it.next();
action.undo();
}
if ( oldLookupRealm != null )
{
container.setLookupRealm( oldLookupRealm );
}
Thread.currentThread().setContextClassLoader( oldClassLoader );
}
}
| public void executeMojo( MavenProject project,
MojoExecution mojoExecution,
MavenSession session )
throws ArtifactResolutionException, MojoFailureException,
ArtifactNotFoundException, InvalidDependencyVersionException, PluginManagerException,
PluginConfigurationException
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
// NOTE: I'm putting these checks in here, since this is the central point of access for
// anything that wants to execute a mojo.
if ( mojoDescriptor.isProjectRequired() && !session.isUsingPOMsFromFilesystem() )
{
throw new PluginExecutionException( mojoExecution, project,
"Cannot execute mojo: "
+ mojoDescriptor.getGoal()
+ ". It requires a project with an existing pom.xml, but the build is not using one." );
}
if ( mojoDescriptor.isOnlineRequired() && session.getSettings().isOffline() )
{
// TODO: Should we error out, or simply warn and skip??
throw new PluginExecutionException( mojoExecution, project,
"Mojo: "
+ mojoDescriptor.getGoal()
+ " requires online mode for execution. Maven is currently offline." );
}
if ( mojoDescriptor.getDeprecated() != null )
{
getLogger().warn( "Mojo: " + mojoDescriptor.getGoal() + " is deprecated.\n" + mojoDescriptor.getDeprecated() );
}
if ( mojoDescriptor.isDependencyResolutionRequired() != null )
{
Collection projects;
if ( mojoDescriptor.isAggregator() )
{
projects = session.getSortedProjects();
}
else
{
projects = Collections.singleton( project );
}
for ( Iterator i = projects.iterator(); i.hasNext(); )
{
MavenProject p = (MavenProject) i.next();
resolveTransitiveDependencies( session,
artifactResolver,
mojoDescriptor.isDependencyResolutionRequired(),
artifactFactory,
p,
mojoDescriptor.isAggregator() );
}
downloadDependencies( project, session, artifactResolver );
}
String goalName = mojoDescriptor.getFullGoalName();
Mojo mojo = null;
PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();
Xpp3Dom dom = mojoExecution.getConfiguration();
if ( dom != null )
{
// make a defensive copy, to keep things from getting polluted.
dom = new Xpp3Dom( dom );
}
// Event monitoring.
String event = MavenEvents.MOJO_EXECUTION;
EventDispatcher dispatcher = session.getEventDispatcher();
String goalExecId = goalName;
if ( mojoExecution.getExecutionId() != null )
{
goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}";
}
// by this time, the pluginDescriptor has had the correct realm setup from getConfiguredMojo(..)
ClassRealm pluginRealm = null;
ClassRealm oldLookupRealm = container.getLookupRealm();
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
List realmActions = new ArrayList();
try
{
mojo = getConfiguredMojo( session, dom, project, false, mojoExecution, realmActions );
dispatcher.dispatchStart( event, goalExecId );
pluginRealm = pluginDescriptor.getClassRealm();
getLogger().debug( "Setting context classloader for plugin to: " + pluginRealm.getId() + " (instance is: " + pluginRealm + ")" );
Thread.currentThread().setContextClassLoader( pluginRealm );
// NOTE: DuplicateArtifactAttachmentException is currently unchecked, so be careful removing this try/catch!
// This is necessary to avoid creating compatibility problems for existing plugins that use
// MavenProjectHelper.attachArtifact(..).
try
{
mojo.execute();
}
catch( DuplicateArtifactAttachmentException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw new PluginExecutionException( mojoExecution, project, e );
}
// NEW: If the mojo that just executed is a report, store it in the LifecycleExecutionContext
// for reference by future mojos.
if ( mojo instanceof MavenReport )
{
session.addReport( mojoDescriptor, (MavenReport) mojo );
}
dispatcher.dispatchEnd( event, goalExecId );
}
catch ( MojoExecutionException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw new PluginExecutionException( mojoExecution, project, e );
}
catch ( MojoFailureException e )
{
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw e;
}
catch ( LinkageError e )
{
if ( getLogger().isFatalErrorEnabled() )
{
getLogger().fatalError(
mojoDescriptor.getImplementation() + "#execute() caused a linkage error ("
+ e.getClass().getName() + ") and may be out-of-date. Check the realms:" );
StringBuffer sb = new StringBuffer();
sb.append( "Plugin realm = " + pluginRealm.getId() ).append( '\n' );
for ( int i = 0; i < pluginRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + pluginRealm.getURLs()[i] );
if ( i != ( pluginRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
ClassRealm containerRealm = container.getContainerRealm();
sb = new StringBuffer();
sb.append( "Container realm = " + containerRealm.getId() ).append( '\n' );
for ( int i = 0; i < containerRealm.getURLs().length; i++ )
{
sb.append( "urls[" + i + "] = " + containerRealm.getURLs()[i] );
if ( i != ( containerRealm.getURLs().length - 1 ) )
{
sb.append( '\n' );
}
}
getLogger().fatalError( sb.toString() );
}
session.getEventDispatcher().dispatchError( event, goalExecId, e );
throw e;
}
finally
{
if ( mojo != null )
{
try
{
container.release( mojo );
}
catch ( ComponentLifecycleException e )
{
getLogger().debug( "Error releasing mojo for: " + goalExecId, e );
}
}
pluginDescriptor.setClassRealm( null );
pluginDescriptor.setArtifacts( null );
for ( Iterator it = realmActions.iterator(); it.hasNext(); )
{
PluginRealmAction action = (PluginRealmAction) it.next();
action.undo();
}
if ( oldLookupRealm != null )
{
container.setLookupRealm( oldLookupRealm );
}
Thread.currentThread().setContextClassLoader( oldClassLoader );
}
}
|
diff --git a/splat/src/main/uk/ac/starlink/splat/data/SpecData.java b/splat/src/main/uk/ac/starlink/splat/data/SpecData.java
index ae32951bc..c027f2bc6 100644
--- a/splat/src/main/uk/ac/starlink/splat/data/SpecData.java
+++ b/splat/src/main/uk/ac/starlink/splat/data/SpecData.java
@@ -1,3022 +1,3023 @@
/*
* Copyright (C) 2002-2004 Central Laboratory of the Research Councils
* Copyright (C) 2007 Particle Physics and Astronomy Research Council
* Copyright (C) 2007-2009 Science and Technology Facilities Council
*
* History:
* 01-SEP-2002 (Peter W. Draper):
* Original version.
* 26-FEB-2004 (Peter W. Draper):
* Added column name methods.
*/
package uk.ac.starlink.splat.data;
import java.awt.Color;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Logger;
import nom.tam.fits.Header;
import uk.ac.starlink.ast.AstException;
import uk.ac.starlink.ast.Frame;
import uk.ac.starlink.ast.FrameSet;
import uk.ac.starlink.ast.Grf;
import uk.ac.starlink.ast.Mapping;
import uk.ac.starlink.ast.Plot;
import uk.ac.starlink.ast.grf.DefaultGrf;
import uk.ac.starlink.ast.grf.DefaultGrfMarker;
import uk.ac.starlink.ast.grf.DefaultGrfState;
import uk.ac.starlink.diva.interp.LinearInterp;
import uk.ac.starlink.splat.ast.ASTChannel;
import uk.ac.starlink.splat.ast.ASTJ;
import uk.ac.starlink.splat.util.Sort;
import uk.ac.starlink.splat.util.SplatException;
// IMPORT NOTE: modifying the member variables could change the
// serialization signature of this class. If really need to then
// think about providing a backwards compatibility mechanism with
// the Serializable API (this should be possible since all
// serializable classes have a serialVersionUID).
/**
* SpecData defines an interface for general access to spectral datasets of
* differing fundamental data types and represents the main data model used
* in SPLAT.
* <p>
*
* It uses a derived class of SpecDataImpl to a supported data format (i.e.
* FITS, NDF and text files etc.) to give generalised access to:
* <ul>
* <li> the spectrum data
* <li> the associated data errors
* <li> the coordinate of any data point
* <li> the spectrum properties (i.e. related values)
* </ul>
* <p>
*
* It should always be used when dealing with spectral data to avoid any
* specialised knowledge of the data format. <p>
*
* Missing data, or gaps in the spectrum, are indicated using the special
* value SpecData.BAD. Generally useful code should always test for this in
* the data values (otherwise you'll see numeric problems as BAD is the lowest
* possible double value). <p>
*
* Matching of data values between this spectrum and anothers coordinates can
* currently be done using the evalYData and evalYDataArray method of the
* AnalyticSpectrum interface (but note that at present this uses a simple
* interpolation scheme, so shouldn't be used for analysis, except when the
* interpolated spectrum is an analytic one, such as a polynomial). <p>
*
* Each object records a series of properties that define how the spectrum
* should be rendered (i.e. line colour, thickness, style, plotting style, or
* marker type and size, plus whether to show any errors as bars etc.). These
* are stored in any serialized versions of this class. Rendering using the
* Grf object primitives is performed by this class for spectra and error
* bars. <p>
*
* General utilities for converting coordinates and looking up values are
* provided, as are methods for specialised functions like formatting and
* unformatting values. This allows you to avoid understanding what is
* returned as a value from a user interaction as formatting and unformatting
* match the units of the spectral axes (which can therefore be in esoteric
* units, like RA or Dec).
*
* @author Peter W. Draper
* @version $Id$
* @see SpecDataImpl
* @see SpecDataFactory
* @see AnalyticSpectrum
* @see "The Bridge Design Pattern"
*/
public class SpecData
implements AnalyticSpectrum, Serializable
{
// Logger.
private static Logger logger =
Logger.getLogger( "uk.ac.starlink.splat.data.SpecData" );
// =============
// Constructors.
// =============
/**
* Create an instance using the data in a given SpecDataImpl object.
*
* @param impl a concrete implementation of a SpecDataImpl class that is
* accessing spectral data in of some format.
* @exception SplatException thrown if there are problems obtaining
* spectrum.
*/
public SpecData( SpecDataImpl impl )
throws SplatException
{
this( impl, false );
}
/**
* Create an instance using the data in a given SpecDataImpl
* object. Do not attempt to read the data if suggested. This variant is
* provided for sub-classes that will deal with the data at some later
* time.
*
* @param impl a concrete implementation of a SpecDataImpl class that
* will be used for spectral data in of some format.
* @param check if true then a check for the presence of data will be
* made, before attempting a read. Otherwise no check will be
* made and problems will be indicated by throwing an error
* at a later time.
* @exception SplatException thrown if there are problems obtaining
* spectrum information.
*/
protected SpecData( SpecDataImpl impl, boolean check )
throws SplatException
{
setSpecDataImpl( impl, check );
}
/**
* Set the {@link SpecDataImpl} instance.
*
* @param impl a concrete implementation of a SpecDataImpl class that
* will be used for spectral data in of some format.
* @exception SplatException thrown if there are problems obtaining
* spectrum information.
*/
public void setSpecDataImpl( SpecDataImpl impl )
throws SplatException
{
setSpecDataImpl( impl, false );
}
/**
* Set the {@link SpecDataImpl} instance. This is the constructor.
*
* @param impl a concrete implementation of a SpecDataImpl class that
* will be used for spectral data in of some format.
* @param check if true then a check for the presence of data will be
* made, before attempting a read. Otherwise no check will be
* made and problems will be indicated by throwing an error
* at a later time.
* @exception SplatException thrown if there are problems obtaining
* spectrum information.
*/
protected void setSpecDataImpl( SpecDataImpl impl, boolean check )
throws SplatException
{
this.impl = impl;
fullName = impl.getFullName();
setShortName( impl.getShortName() );
if ( ! check || ( check && impl.getData() != null ) ) {
readDataPrivate();
}
}
/**
* Return the SpecDataImpl object so that it can expose very data specific
* methods (if needed, you really shouldn't use this).
*
* @return SpecDataImpl object defining the data access used by this
* instance.
*/
public SpecDataImpl getSpecDataImpl()
{
return impl;
}
/**
* Finalise object. Free any resources associated with member variables.
*
* @exception Throwable Description of the Exception
*/
protected void finalize()
throws Throwable
{
this.impl = null;
this.xPos = null;
this.yPos = null;
this.yPosOri = null;
this.yErr = null;
this.yErrOri = null;
this.astJ = null;
super.finalize();
}
// ================
// Public constants
// ================
/**
* Value of BAD (missing) data.
*/
public final static double BAD = -Double.MAX_VALUE;
//
// Plotting property symbolic constants.
//
/**
* Set or query line thickness.
*/
public final static int LINE_THICKNESS = 0;
/**
* Set or query line drawing style.
*/
public final static int LINE_STYLE = 1;
/**
* Set or query line colour.
*/
public final static int LINE_COLOUR = 2;
/**
* Set or query line drawing style.
*/
public final static int PLOT_STYLE = 3;
/**
* Set or query the marker drawing type.
*/
public final static int POINT_TYPE = 4;
/**
* Set or query the marker size.
*/
public final static int POINT_SIZE = 5;
/**
* Set or query alpha composite value.
*/
public final static int LINE_ALPHA_COMPOSITE = 6;
/**
* Set or query error bar colour.
*/
public final static int ERROR_COLOUR = 7;
/**
* Set or query the number of sigma error bars are drawn at.
*/
public final static int ERROR_NSIGMA = 8;
/**
* Set or query the frequency error bars are drawn at.
*/
public final static int ERROR_FREQUENCY = 9;
//
// Symbolic contants defining the possible plotting styles.
//
/**
* Use polyline plotting style.
*/
public final static int POLYLINE = 1;
/**
* Use histogram plotting style.
*/
public final static int HISTOGRAM = 2;
/**
* Use a point plotting style.
*/
public final static int POINT = 3;
//
// Types of spectral data. The default is UNCLASSIFIED.
// Nothing is done with this information here, it's just for external
// tagging. USERTYPE is just a spare.
//
/**
* Spectrum is unclassified.
*/
public final static int UNCLASSIFIED = 0;
/**
* Spectrum is a target (observation).
*/
public final static int TARGET = 1;
/**
* Spectrum is an arc.
*/
public final static int ARC = 2;
/**
* Spectrum is a twilight sky exposure.
*/
public final static int SKY = 3;
/**
* Spectrum is a polynomial.
*/
public final static int POLYNOMIAL = 4;
/**
* Spectrum is a line fit.
*/
public final static int LINEFIT = 5;
/**
* Spectrum is a user defined type.
*/
public final static int USERTYPE = 6;
//
// Limits for the number of digits used in a formatted value.
//
public final static int MAX_DIGITS = 17; // Perfect IEEE double precision
public final static int MIN_DIGITS = 7; // AST uses 7
/**
* Serialization version ID string (generated by serialver on original
* star.jspec.data.SpecData class).
*/
final static long serialVersionUID = 1719961247707612529L;
// ===================
// Protected variables
// ===================
/**
* Reference to the data access adaptor. This object is not kept during
* serialisation as all restored objects use a memory implementation (disk
* file associations are difficult to maintain).
*/
protected transient SpecDataImpl impl = null;
/**
* The X data values for the spectrum.
*/
protected double[] xPos = null;
/**
* The Y data values for the spectrum.
*/
protected double[] yPos = null;
protected double[] yPosOri = null;
/**
* The Y data errors for the spectrum.
*/
protected double[] yErr = null;
protected double[] yErrOri = null;
/**
* Symbolic name of the spectrum.
*/
protected String shortName = null;
/**
* Full name of the spectrum.
*/
protected String fullName = null;
/**
* Whether symbolic names should be truncated when equal to the full name.
* Shared by all instances.
*/
protected static boolean simplifyShortNames = false;
/**
* The range of coordinates spanned (min/max values in xPos and yPos).
*/
protected double[] range = new double[4];
/**
* The full range of coordinates spanned (i.e. min/max values
* in xPos and yPos, plus the standard deviations * nsigma in yPos).
*/
protected double[] fullRange = new double[4];
/**
* The coordinates and data values of the points used to define the
* range. These may be needed when a transformation of the region that the
* spectrum is drawn into is performed (the actual points are required for
* potentially non-linear transformations, like flux when it depends on
* wavelength).
*/
protected double[] xEndPoints = new double[4];
protected double[] yEndPoints = new double[4];
/**
* The coordinates and data values of the points used to define the
* full range. These may be needed when a transformation of the region
* that the spectrum is drawn into is performed (the actual points are
* required for potentially non-linear transformations, like flux when it
* depends on wavelength). Note that the X versions are same as xEndPoints.
*/
protected double[] yFullEndPoints = new double[4];
/**
* Reference to ASTJ object that contains an AST FrameSet that wraps
* the spectrum FrameSet so that it can be plotted (i.e. makes it
* suitably two dimensional). Marked "transient" it should always be
* re-generated when a spectrum is loaded.
*/
protected transient ASTJ astJ = null;
/**
* The "graphics" line thickness.
*/
protected double lineThickness = 1.0;
/**
* The "graphics" line style.
*/
protected double lineStyle = 1.0;
/**
* The "graphics" line alpha composite value (SRC_OVER).
*/
protected double alphaComposite = 1.0;
/**
* The "graphics" line colour.
*/
protected double lineColour = (double) Color.blue.getRGB();
/**
* The colour used to drawn error bars.
*/
protected double errorColour = (double) Color.red.getRGB();
/**
* The number of sigma any error bars are drawn at.
*/
protected int errorNSigma = 1;
/**
* The frequency (that is how often) error bars are drawn.
*/
protected int errorFrequency = 1;
/**
* The spectrum plot style.
*/
protected int plotStyle = POLYLINE;
/**
* Whether error bars should be drawn.
*/
protected boolean drawErrorBars = false;
/**
* Whether this spectrum should be used when auto-ranging (certain classes
* of spectra, i.e.<!-- --> generated ones, could be expected to have artificial
* ranges).
*/
protected boolean useInAutoRanging = true;
/**
* Slack added to full data range to stop error bar serifs from just
* running along axes.
*/
private final static double SLACK = 0.02;
/**
* Half length of error bar serifs.
*/
private final static double SERIF_LENGTH = 2.5;
/**
* The type of data stored in this spectrum. This is purely symbolic and
* is meant for use in organisational duties.
*/
protected int type = UNCLASSIFIED;
/**
* Whether the spectrum coordinates are monotonic.
*/
protected boolean monotonic = true;
/**
* The type of point that is drawn.
*/
protected int pointType = DefaultGrfMarker.DOT;
/**
* The size of any points.
*/
protected double pointSize = 5.0;
/**
* Serialized form of the backing implementation AST FrameSet. This is
* only used when the object is serialized itself and cannot be relied on
* at any time.
*/
protected String[] serializedFrameSet = null;
/**
* Data units and label for storage in serialized form. These are only
* used when the object is serialized and cannot be used for any other
* purpose.
*/
protected String serializedDataUnits = null;
protected String serializedDataLabel = null;
/**
* Most significant axis being used when the spectrum was serialised.
* This will continue to be used when deserialised when the original
* data axes has been lost.
*/
protected int serializedSigAxis = 0;
/**
* The apparent data units. If possible conversion from the actual data
* units to these values will occur (this is achieved by transforming the
* data values using the FluxFrame part of the spectral AST FrameSet). If
* not possible then these will be ignored.
*/
protected String apparentDataUnits = null;
/**
* Whether to search for spectral coordinate frames when creating the plot
* FrameSets. If true then a SpecFrame anywhere in the original WCS of an
* instance will be used, or if possible a spectral coordinate system will
* be deduced from any labelling and units. If false SpecFrames will only
* be used it they are in the current coordinate system. Applies to the
* whole application.
*/
protected static boolean searchForSpecFrames = true;
/**
* An offset to apply to the Y physical coordinates so that spectra
* can be displayed offset from one another.
*/
private double yoffset = 0.0;
/**
* Whether the Y offsets to coordinates should be applied.
*/
private boolean applyYOffset = false;
// ==============
// Public methods
// ==============
/**
* Get the full name for spectrum (cannot edit, this is usually the
* filename).
*
* @return the full name.
*/
public String getFullName()
{
return fullName;
}
/**
* Get a symbolic name for spectrum. This will be "simplified" if
* {@link simplyShortNames} is currently true and the symbolic name is the
* same as the full name (usually the disk file name).
* <p>
* Simplication means removing all but the last part of the path (parent
* directory) and the filename.
*
* @return the short name.
*/
public String getShortName()
{
String sName = shortName;
if ( simplifyShortNames && sName.equals( fullName ) ) {
File file = new File( sName );
File par = file.getParentFile();
if ( par != null ) {
String parPar = par.getParent();
if ( parPar != null ) {
// Short name has a fuller path than we want remove this.
sName = sName.substring( parPar.length() + 1 );
}
}
}
return sName;
}
/**
* Change the symbolic name of a spectrum.
*
* @param shortName new short name for the spectrum.
*/
public void setShortName( String shortName )
{
this.shortName = shortName;
}
/**
* Set whether to simplify all short names when they are requested.
* Applies to all instances of SpecData.
*
* @param simplify whether to simplify short names.
*/
public static void setSimplifiedShortNames( boolean simplify )
{
simplifyShortNames = simplify;
}
/**
* Get whether we're simplifying all short names when they are requested.
* Applies to all instances of SpecData.
*
* @return the current state
*/
public static boolean isSimplifiedShortNames()
{
return simplifyShortNames;
}
/**
* Get references to spectrum X data (the coordinates as a single array).
*
* @return reference to spectrum X data.
*/
public double[] getXData()
{
return xPos;
}
/**
* Get references to spectrum Y data (the data values).
*
* @return reference to spectrum Y data.
*/
public double[] getYData()
{
return yPos;
}
/**
* Get references to spectrum Y data errors (the data errors).
*
* @return reference to spectrum Y data errors.
*/
public double[] getYDataErrors()
{
return yErr;
}
/**
* Return if data errors are available.
*
* @return true if Y data has errors.
*/
public boolean haveYDataErrors()
{
return ( yErr != null );
}
/**
* Swap the data and the data errors, so that the spectral data are the
* errors. This can be used to plot the errors as a line rather than as
* errorbars. Does nothing there are no errors. Call again to undo the
* effect. Note does not affect the underlying implementation, so
* refreshing from that will also reset this.
*/
public void swapDataAndErrors()
{
if ( yErr != null ) {
double tmp[] = yPos;
yPos = yErr;
yErr = tmp;
tmp = yPosOri;
yPosOri = yErrOri;
yErrOri = tmp;
// Reset ranges.
setRangePrivate();
}
}
/**
* Set the data units of the underlying representation. This will not
* cause any modification of the data value themselves.
*
* @param dataUnits data units string in AST format.
*/
public void setDataUnits( String dataUnits )
{
impl.setDataUnits( dataUnits );
}
/**
* Get the underlying data units. This should be set to "unknown" when
* unknown.
*/
public String getDataUnits()
{
return impl.getDataUnits();
}
/**
* Get the current data units. These will be the apparent data units when
* they are in force, otherwise they will be the underlying data units.
*/
public String getCurrentDataUnits()
{
if ( apparentDataUnits == null ) {
return impl.getDataUnits();
}
return apparentDataUnits;
}
/**
* Set the data label.
*
* @param dataLabel label describing the data values.
*/
public void setDataLabel( String dataLabel )
{
impl.setDataLabel( dataLabel );
}
/**
* Get the data label. This should be set to "data values" when unknown.
*/
public String getDataLabel()
{
return impl.getDataLabel();
}
/**
* Set the apparent data units. If possible the spectral FrameSet will
* present the data values in these units. This usually requires a
* FluxFrame, i.e. the underlying data must have recognised data units.
* <p>
* These units will not be used until the next regeneration of the
* spectral FrameSet. A null value will return to the original units.
*
* @param dataUnits apparent data units string in AST format.
*/
public void setApparentDataUnits( String dataUnits )
{
apparentDataUnits = dataUnits;
}
/**
* Get the apparent data units currently in use. These are null then they
* have not been set, or have been found invalid.
*/
public String getApparentDataUnits()
{
return apparentDataUnits;
}
/**
* Set the offset used to stack this spectra. A number in the physical
* coordinates.
*/
public void setYOffset( double yoffset )
{
this.yoffset = yoffset;
}
/**
* Get stacking offset.
*/
public double getYOffset()
{
return yoffset;
}
/**
* Set whether to use the stacking offset.
*/
public void setApplyYOffset( boolean applyYOffset )
{
this.applyYOffset = applyYOffset;
}
/**
* Get whether we're using the stacking offset.
*/
public boolean isApplyYOffset()
{
return applyYOffset;
}
/**
* Return a keyed value from the FITS headers. Returns "" if not
* found. Standard properties are made available with specific methods
* ({@link #getDataLabel} etc.), which should be used to access those.
*/
public String getProperty( String property )
{
return impl.getProperty( property );
}
/**
* Return the FITS headers as a whole, if any are available.
*/
public Header getHeaders()
{
if ( impl instanceof FITSHeaderSource ) {
return ((FITSHeaderSource)impl).getFitsHeaders();
}
return null;
}
/**
* Save the spectrum to disk (if supported). Uses the current state of the
* spectrum (i.e. any file names etc.) to decide how to do this.
*
* @exception SplatException thown if an error occurs during save.
*/
public void save()
throws SplatException
{
try {
impl.save();
}
catch (Exception e) {
throw new SplatException( "Failed to save spectrum", e );
}
}
/**
* Create a new spectrum by extracting sections of this spectrum. The
* section extents are defined in physical coordinates. Each section will
* not contain any values that lie outside of its physical coordinate
* range. <p>
*
* The spectrum created here is not added to any lists or created with any
* configuration other than the default values (i.e. you must do this part
* yourself) and is only kept in memory.
*
* @param name short name for the spectrum.
* @param ranges an array of pairs of physical coordinates. These define
* the extents of the ranges to extract.
* @return a spectrum that contains data only from the given ranges. May
* be null if no values can be located.
*/
public SpecData getSect( String name, double[] ranges )
{
// Locate the index of the positions just below and above our
// physical value pairs and count the number of values that
// will be extracted.
int nRanges = ranges.length / 2;
int[] lower = new int[nRanges];
int[] upper = new int[nRanges];
int[] low;
int[] high;
int nvals = 0;
for ( int i = 0, j = 0; j < nRanges; i += 2, j++ ) {
low = bound( ranges[i] );
lower[j] = low[1];
high = bound( ranges[i + 1] );
upper[j] = high[0];
nvals += high[0] - low[1] + 1;
}
if ( nvals < 0 ) {
// Coordinates run in a reversed direction.
nvals = Math.abs( nvals ) + 2 * nRanges;
high = lower;
lower = upper;
upper = high;
}
// Equal sets of bounds give no extraction.
if ( nvals == 0 ) {
return null;
}
// Add room for any gaps.
nvals += nRanges - 1;
// Copy extracted values.
double[] newCoords = new double[nvals];
double[] newData = new double[nvals];
int k = 0;
int length = 0;
for ( int j = 0; j < nRanges; j++ ) {
if ( j != 0 ) {
// Need a gap in the spectrum.
newCoords[k] = xPos[upper[j - 1]] +
( xPos[lower[j]] - xPos[upper[j - 1]] ) * 0.5;
newData[k] = BAD;
k++;
}
length = upper[j] - lower[j] + 1;
System.arraycopy( xPos, lower[j], newCoords, k, length );
System.arraycopy( yPos, lower[j], newData, k, length );
k += length;
}
// Same for errors, if have any.
double[] newErrors = null;
if ( haveYDataErrors() ) {
newErrors = new double[nvals];
k = 0;
length = 0;
for ( int j = 0; j < nRanges; j++ ) {
if ( j != 0 ) {
newErrors[k] = BAD;
k++;
}
length = upper[j] - lower[j] + 1;
System.arraycopy( yErr, lower[j], newErrors, k, length );
k += length;
}
}
// And create the memory spectrum.
return createNewSpectrum( name, newCoords, newData, newErrors );
}
/**
* Create a new spectrum by deleting sections of this spectrum. The
* section extents are defined in physical coordinates. Each section will
* not contain any values that lie outside of its physical coordinate
* range. <p>
*
* The spectrum created here is not added to any lists or created with any
* configuration other than the default values (i.e. you must do this part
* yourself) and is only kept in memory.
*
* @param name short name for the spectrum.
* @param ranges an array of pairs of physical coordinates. These define
* the extents of the ranges to delete.
* @return a spectrum that contains data only from outside the
* given ranges. May be null if all values are to be deleted.
*/
public SpecData getSubSet( String name, double[] ranges )
{
// Locate the index of the positions just below and above our
// physical value pairs and count the number of values that will be
// deleted.
int nRanges = ranges.length / 2;
int[] lower = new int[nRanges];
int[] upper = new int[nRanges];
int[] low;
int[] high;
int ndelete = 0;
for ( int i = 0, j = 0; j < nRanges; i += 2, j++ ) {
low = bound( ranges[i] );
lower[j] = low[1];
high = bound( ranges[i + 1] );
upper[j] = high[0];
ndelete += high[0] - low[1] + 1;
}
if ( ndelete < 0 ) {
// Coordinates run in a reversed direction.
ndelete = Math.abs( ndelete ) + 2 * nRanges;
high = lower;
lower = upper;
upper = high;
// The ranges must increase.
Sort.insertionSort2( lower, upper );
}
if ( ndelete >= xPos.length || ndelete == 0 ) {
return null;
}
// Copy remaining data. The size of result spectrum is the current
// size, minus the number of positions that will be erased, plus one
// per range to hold the BAD value to form the break.
int nkeep = xPos.length - ndelete + nRanges;
double[] newCoords = new double[nkeep];
double[] newData = new double[nkeep];
int length = 0;
for ( int i = 0, j = 0, k = 0; i < xPos.length; i++ ) {
if ( i >= lower[j] && i <= upper[j] ) {
// Arrived within a range, so mark one mid-range
// position BAD (so show the break) and skip to the
// end. Set for next valid range.
+ newCoords[k] = xPos[i];
newData[k] = BAD;
k++;
if ( j + 1 == nRanges ) {
// No more ranges, so just complete the copy.
for ( int l = upper[j] + 1; l < xPos.length; l++ ) {
if ( k < nkeep ) {
newCoords[k] = xPos[l];
newData[k] = yPos[l];
}
k++;
}
i = xPos.length;
break;
}
i = upper[j];
j++;
}
else {
newCoords[k] = xPos[i];
newData[k] = yPos[i];
k++;
}
}
// Same for errors, if have any.
double[] newErrors = null;
if ( haveYDataErrors() ) {
newErrors = new double[nkeep];
for ( int i = 0, j = 0, k = 0; i < xPos.length; i++ ) {
if ( i >= lower[j] && i <= upper[j] ) {
newErrors[k] = BAD;
k++;
if ( j + 1 == nRanges ) {
for ( int l = upper[j] + 1; l < xPos.length; l++ ) {
if ( k < nkeep ) {
newErrors[k] = yErr[l];
}
k++;
}
i = xPos.length;
break;
}
i = upper[j];
j++;
}
else {
newErrors[k] = yErr[i];
k++;
}
}
}
// Final task, trim off any BAD values at ends if ranges
// included those.
if ( lower[0] <= 0 || upper[upper.length-1] >= ( xPos.length - 1 ) ) {
int i1 = 0;
int i2 = newData.length;
if ( lower[0] <= 0 ) {
i1++;
}
if ( upper[upper.length-1] >= ( xPos.length - 1 ) ) {
i2--;
}
int trimlength = i2 - i1;
double trimCoords[] = new double[trimlength];
System.arraycopy( newCoords, i1, trimCoords, 0, trimlength );
newCoords = trimCoords;
double trimData[] = new double[trimlength];
System.arraycopy( newData, i1, trimData, 0, trimlength );
newData = trimData;
double trimErrors[] = null;
if ( newErrors != null ) {
trimErrors = new double[trimlength];
System.arraycopy( newErrors, i1, trimErrors, 0, trimlength );
newErrors = trimErrors;
}
}
// And create the memory spectrum.
return createNewSpectrum( name, newCoords, newData, newErrors );
}
/**
* Create a new spectrum by deleting sections of this spectrum and linear
* interpolating across the sections. The section extents are defined in
* physical coordinates. <p>
*
* The spectrum created here is not added to any lists or created with any
* configuration other than the default values (i.e. you must do this part
* yourself) and is only kept in memory.
*
* @param name short name for the spectrum.
* @param ranges an array of pairs of physical coordinates. These define
* the extents of the ranges to remove and interpolate.
* @return the new spectrum.
*/
public SpecData getInterpolatedSubSet( String name, double[] ranges )
{
// Locate the index of the positions just below and above our
// physical value pairs.
int nRanges = ranges.length / 2;
int[] lower = new int[nRanges];
int[] upper = new int[nRanges];
int[] low;
int[] high;
int ninterp = 0;
for ( int i = 0, j = 0; j < nRanges; i += 2, j++ ) {
low = bound( ranges[i] );
lower[j] = low[1];
high = bound( ranges[i + 1] );
upper[j] = high[0];
ninterp += high[0] - low[1] + 1;
}
if ( ninterp < 0 ) {
// Coordinates run in a reversed direction.
ninterp = Math.abs( ninterp ) + 2 * nRanges;
high = lower;
lower = upper;
upper = high;
// The ranges must increase.
Sort.insertionSort2( lower, upper );
}
if ( ninterp >= xPos.length || ninterp == 0 ) {
return null;
}
// Copy data.
int nkeep = xPos.length;
double[] newCoords = new double[xPos.length];
double[] newData = new double[xPos.length];
System.arraycopy( xPos, 0, newCoords, 0, xPos.length );
System.arraycopy( yPos, 0, newData, 0, xPos.length );
LinearInterp interp;
double x[] = new double[2];
double y[] = new double[2];
for ( int i = 0, j = 0; i < xPos.length; i++ ) {
if ( i >= lower[j] && i <= upper[j] ) {
// Arrived within a range. Need to interpolate.
x[0] = xPos[lower[j]];
x[1] = xPos[upper[j]];
y[0] = yPos[lower[j]];
y[1] = yPos[upper[j]];
interp = new LinearInterp( x, y );
for ( ; i <= upper[j]; i++ ) {
newData[i] = interp.interpolate( xPos[i] );
}
// Next range or done.
if ( j + 1 == nRanges ) break;
j++;
}
}
// Dump errors.
// And create the memory spectrum.
return createNewSpectrum( name, newCoords, newData, null );
}
/**
* Create a new (memory-resident) spectrum using the given data and
* coordinates, but based on this instance.
* <p>
* This looses the full WCS as the new coordinates are assumed no longer
* directly related, i.e.<!-- --> indices of data do not map to proper
* coordinates using the WCS, but the coordinate system of the spectrum
* should be preserved (using the SpecFrame to reconstruct a new WCS).
*/
protected SpecData createNewSpectrum( String name, double[] coords,
double[] data, double[] errors )
{
EditableSpecData newSpec = null;
try {
newSpec = SpecDataFactory.getInstance().createEditable( name,
this );
FrameSet frameSet = ASTJ.get1DFrameSet( astJ.getRef(), 1 );
newSpec.setSimpleUnitDataQuick( frameSet, coords,
getCurrentDataUnits(), data,
errors );
applyRenderingProperties( newSpec );
}
catch ( Exception e ) {
e.printStackTrace();
newSpec = null;
}
return newSpec;
}
/**
* Copy some rendering properties so that another spectrum seems to
* inherit this one.
*/
public void applyRenderingProperties( SpecData newSpec )
{
newSpec.setLineThickness( lineThickness );
newSpec.setLineStyle( lineStyle );
newSpec.setAlphaComposite( alphaComposite );
newSpec.setLineColour( (int) lineColour );
newSpec.setErrorColour( (int) errorColour );
newSpec.setPlotStyle( plotStyle );
newSpec.setPointType( pointType );
newSpec.setPointSize( pointSize );
}
/**
* Get the data ranges in the X and Y axes. Does not include data errors.
*
* @return reference to array of 4 values, xlow, xhigh, ylow, yhigh.
*/
public double[] getRange()
{
return range;
}
/**
* Get the data ranges in the X and Y axes, including the standard
* deviations.
*
* @return reference to array of 4 values, xlow, xhigh, ylow, yhigh.
*/
public double[] getFullRange()
{
return fullRange;
}
/**
* Get the coordinates of the points used to define the range in the X axis.
*
* @return reference to array of 4 values, x1, y1, y2, y2.
*/
public double[] getXEndPoints()
{
return xEndPoints;
}
/**
* Get the coordinates of the points used to define the range in the Y axis.
*
* @return reference to array of 4 values, x1, y1, y2, y2.
*/
public double[] getYEndPoints()
{
return yEndPoints;
}
/**
* Get the coordinates of the points used to define the full range in the
* X axis.
*
* @return reference to array of 4 values, x1, y1, y2, y2.
*/
public double[] getXFullEndPoints()
{
return xEndPoints;
}
/**
* Get the coordinates of the points used to define the full range in the
* Y axis.
*
* @return reference to array of 4 values, x1, y1, y2, y2.
*/
public double[] getYFullEndPoints()
{
return yFullEndPoints;
}
/**
* Get reference to ASTJ object set up to specify the
* transformations for plotting coordinates against data values.
*
* @return ASTJ object describing plottable axis transformations.
*/
public ASTJ getAst()
{
return astJ;
}
/**
* Get reference to the FrameSet that is used by the SpecDataImpl. Note
* this may not be 1D. It is made available mainly for creating copies of
* SpecData (the ASTJ FrameSet is not suitable for writing directly to
* disk file). Do not confuse this with the {@link #getAst()} FrameSet, it
* is the original dataset FrameSet.
*/
public FrameSet getFrameSet()
{
return impl.getAst();
}
/**
* Return the "channel spacing". Determined by getting increment of moving
* one pixel along the first axis. Can be in units other than default by
* supplying an attribute string (System=FREQ,Unit=MHz).
*
* @param atts an AST attribute string, use to set the coordinates that
* the channel spacing is required in.
*
* @return the channel spacing
*/
public double channelSpacing( String atts )
{
// Get the axis from the underlying dataset AST FrameSet. Cannot
// use the plot FrameSet as it may be currently modified by an
// in progress redraw of the main plot (base frame will be
// incorrect).
FrameSet frameSet = impl.getAst();
int axis = getMostSignificantAxis();
FrameSet mapping = ASTJ.extract1DFrameSet( frameSet, axis );
// Apply the attributes.
if ( ! "".equals( atts ) ) {
mapping.set( atts );
}
// Delta of one pixel in base frame, around the centre.
int first = xPos.length / 2;
double xin[] = new double[]{ first, first + 1 };
double xout[] = mapping.tran1( 2, xin, true );
double dnu = Math.abs( xout[1] - xout[0] );
return dnu;
}
/**
* Get the size of the spectrum.
*
* @return number of coordinate positions in spectrum.
*/
public int size()
{
return xPos.length;
}
/**
* Return the data format as a suitable name.
*
* @return the data format as a simple string (FITS, NDF, etc.).
*/
public String getDataFormat()
{
return impl.getDataFormat();
}
/**
* Set the thickness of the line used to plot the spectrum.
*
* @param lineThickness the line width to be used when plotting.
*/
public void setLineThickness( double lineThickness )
{
this.lineThickness = lineThickness;
}
/**
* Get the width of the line to be used when plotting the spectrum. The
* meaning of this value isn't defined.
*
* @return the line thickness.
*/
public double getLineThickness()
{
return lineThickness;
}
/**
* Set the style of the line used to plot the spectrum.
*
* @param lineStyle the line style to be used when plotting.
*/
public void setLineStyle( double lineStyle )
{
this.lineStyle = lineStyle;
}
/**
* Get the line type to be used when plotting the spectrum. The meaning of
* this value is not defined.
*
* @return the line style in use.
*/
public double getLineStyle()
{
return lineStyle;
}
/**
* Set the alpha composite value of the line used plot the spectrum.
*
* @param alphaComposite the alpha composite value (0.0 to 1.0).
*/
public void setAlphaComposite( double alphaComposite )
{
this.alphaComposite = alphaComposite;
}
/**
* Get the alpha composite value.
*
* @return the current alpha composite value.
*/
public double getAlphaComposite()
{
return alphaComposite;
}
/**
* Set the colour index to be used when plotting the spectrum.
*
* @param lineColour the colour as an RGB integer.
*/
public void setLineColour( int lineColour )
{
this.lineColour = (double) lineColour;
}
/**
* Get the colour of the line to be used when plotting the spectrum.
*
* @return the line colour (an RGB integer).
*/
public int getLineColour()
{
return (int) lineColour;
}
/**
* Set the colour index to be used when drawing error bars.
*
* @param errorColour the colour as an RGB integer.
*/
public void setErrorColour( int errorColour )
{
this.errorColour = errorColour;
}
/**
* Get the colour used when drawing error bars.
*
* @return the error bar colour (an RGB integer).
*/
public int getErrorColour()
{
return (int) errorColour;
}
/**
* Set the number of sigma error bars are drawn at.
*
* @param nsigma the number of sigma
*/
public void setErrorNSigma( int nsigma )
{
this.errorNSigma = nsigma;
}
/**
* Get the number of sigma error bars are drawn at.
*
* @return the number of sigma.
*/
public double getErrorNSigma()
{
return errorNSigma;
}
/**
* Set the frequency that error bars are drawn.
*
* @param freq the frequency (runs from 1 upwards).
*/
public void setErrorFrequency( int freq )
{
this.errorFrequency = Math.max( 1, Math.abs( freq ) );
}
/**
* Get the frequency that error bars are drawn.
*
* @return the frequency
*/
public double getErrorFrequency()
{
return errorFrequency;
}
/**
* Set the type of spectral lines that are drawn (these can be polylines
* or histogram-like, simple markers are a possibility for a future
* implementation). The value should be one of the symbolic constants
* "POLYLINE", "HISTOGRAM" or "POINT".
*
* @param style one of the symbolic contants SpecData.POLYLINE,
* SpecData.HISTOGRAM or SpecData.POINT.
*/
public void setPlotStyle( int style )
{
this.plotStyle = style;
}
/**
* Get the value of plotStyle.
*
* @return the current plotting type (SpecData.POLYLINE,
* SpecData.HISTOGRAM or SpecData.POINT).
*/
public int getPlotStyle()
{
return plotStyle;
}
/**
* Set the type of marker used when drawing spectra with a "POINT"
* style. The marker types are defined by the underlying AST graphics
* implementation - {@link DefaultGrfMarker}.
*
* @param type one of the symbolic values used in {@link DefaultGrfMarker}.
*/
public void setPointType( int type )
{
this.pointType = type;
}
/**
* Get the type of marker that will be used if the spectrum is drawing
* using a "POINT" style.
*
* @return the current marker type.
*/
public int getPointType()
{
return pointType;
}
/**
* Set the size used when drawing using a point type.
*
* @param pointSize the size of a point.g
*/
public void setPointSize( double pointSize )
{
this.pointSize = pointSize;
}
/**
* Get the size used when drawing using a point type.
*
* @return the size of points
*/
public double getPointSize()
{
return pointSize;
}
/**
* Set a known numeric spectral property.
*
* @param what either LINE_THICKNESS, LINE_STYLE, LINE_COLOUR, PLOT_STYLE,
* POINT_TYPE, POINT_SIZE, LINE_ALPHA_COMPOSITE or ERROR_COLOUR.
* @param value container for numeric value. These depend on property
* being set.
*/
public void setKnownNumberProperty( int what, Number value )
{
switch ( what ) {
case LINE_THICKNESS:
{
setLineThickness( value.doubleValue() );
break;
}
case LINE_STYLE:
{
setLineStyle( value.doubleValue() );
break;
}
case LINE_COLOUR:
{
setLineColour( value.intValue() );
break;
}
case PLOT_STYLE:
{
setPlotStyle( value.intValue() );
break;
}
case POINT_TYPE:
{
setPointType( value.intValue() );
break;
}
case POINT_SIZE:
{
setPointSize( value.doubleValue() );
break;
}
case LINE_ALPHA_COMPOSITE:
{
setAlphaComposite( value.doubleValue() );
break;
}
case ERROR_COLOUR:
{
setErrorColour( value.intValue() );
break;
}
case ERROR_NSIGMA:
{
setErrorNSigma( value.intValue() );
break;
}
case ERROR_FREQUENCY:
{
setErrorFrequency( value.intValue() );
break;
}
}
}
/**
* Set the type of the spectral data.
*
* @param type either UNCLASSIFIED, TARGET, ARC, SKY, POLYNOMIAL or
* LINEFIT or USERTYPE.
*/
public void setType( int type )
{
this.type = type;
}
/**
* Get the type of the spectral data.
*
* @return type either UNCLASSIFIED, TARGET, ARC, SKY, POLYNOMIAL or
* LINEFIT or USERTYPE.
*/
public int getType()
{
return type;
}
/**
* Get whether the spectrum coordinates are monotonic or not.
*/
public boolean isMonotonic()
{
return monotonic;
}
/**
* Set whether the spectrum should have its errors drawn as error bars, or
* not. If no errors are available then this is always false.
*
* @param state true to draw error bars, if possible.
*/
public void setDrawErrorBars( boolean state )
{
if ( yErr != null && state ) {
drawErrorBars = true;
}
else {
drawErrorBars = false;
}
}
/**
* Find out if we're drawing error bars.
*
* @return true if we're drawing error bars.
*/
public boolean isDrawErrorBars()
{
return drawErrorBars;
}
/**
* Set whether the spectrum should be used when deriving auto-ranged
* values.
*
* @param state if true then this spectrum should be used when determining
* data limits (artificial spectra could have unreasonable ranges
* when extrapolated).
*/
public void setUseInAutoRanging( boolean state )
{
this.useInAutoRanging = state;
}
/**
* Find out if we should be used when determining an auto-range.
*
* @return whether this spectrum is used when auto-ranging.
*/
public boolean isUseInAutoRanging()
{
return useInAutoRanging;
}
/**
* Set if searching should be done for suitable spectral coordinate
* systems when creating the plot framesets. If changed after the
* application starts it requires {@link initialiseAst()} to be invoked on
* all spectra before the change will be seen.
*/
public static void setSearchForSpecFrames( boolean searchForSpecFrames )
{
SpecData.searchForSpecFrames = searchForSpecFrames;
}
/**
* Find out if searching for a suitable spectral coordinate
* systems will be made when creating plot framesets.
*/
public static boolean isSearchForSpecFrames()
{
return SpecData.searchForSpecFrames;
}
/**
* Read the data from the spectrum into local arrays. This also
* initialises a suitable AST frameset to describe the coordinate system
* in use and establishes the minimum and maximum ranges for both
* coordinates (X, i.e. the wavelength and Y, i.e. data count).
*
* @exception SplatException thrown if an error condition is encountered.
*/
protected void readData()
throws SplatException
{
readDataPrivate();
}
/**
* Private version of readData as called from constructor.
*/
private void readDataPrivate()
throws SplatException
{
// Get the spectrum data counts and errors (can be null).
try {
apparentDataUnits = null;
yPos = impl.getData();
yPosOri = yPos;
yErr = impl.getDataErrors();
yErrOri = yPos;
}
catch (RuntimeException e) {
// None specific errors, like no data...
throw new SplatException( "Failed to read data: " +
e.getMessage() );
}
// Check we have some data.
if ( yPos == null ) {
throw new SplatException( "Spectrum does not contain any data" );
}
initialiseAst();
}
/**
* Initialise the spectral coordinates. Uses the AST information of the
* underlying implementation to generate a FrameSet suitable for plotting
* coordinates against data values and generates the "getXData()" array.
*/
public void initialiseAst()
throws SplatException
{
// Create the init "wavelength" positions as simple
// increasing vector (this places them at centre of pixels).
xPos = new double[yPos.length];
for ( int i = 0; i < yPos.length; i++ ) {
xPos[i] = (double) ( i + 1 );
}
// Get the dimensionality of the spectrum. If more than 1 we
// need to pick out a significant axis to work with.
int sigaxis = getMostSignificantAxis();
// Get the AST component (this should define the wavelength
// axis coordinates, somehow).
FrameSet astref = impl.getAst();
if ( astref == null ) {
throw new SplatException("spectrum has no coordinate information");
}
else {
// Create the required ASTJ object to manipulate the AST
// frameset.
ASTJ ast = new ASTJ( astref );
// If the sigaxis isn't 1 then we may have a 3D spectrum
// where the other axes define an extraction position.
// Check for this and record that position.
checkForExtractionPosition( astref, sigaxis );
// Create a frameset that is suitable for displaying a
// "spectrum". This has a coordinate X axis and a data Y
// axis. The coordinates are chosen to run along the sigaxis (if
// input data has more than one dimension) and may be a distance,
// rather than absolute coordinate.
FrameSet specref = null;
try {
specref = ast.makeSpectral( sigaxis, 0, yPos.length,
getDataLabel(), getDataUnits(),
false, searchForSpecFrames );
}
catch (AstException e) {
throw new SplatException( "Failed to find a valid spectral " +
"coordinate system", e );
}
try {
astJ = new ASTJ( specref );
// Get the mapping for the X axis and check that it is
// useful, i.e. we can invert it. If this isn't the case then
// many operations will fail, so record this so that we can
// check.
Mapping oned = astJ.get1DMapping( 1 );
monotonic = ( oned.getI( "TranInverse" ) == 1 );
if ( ! monotonic ) {
logger.info( impl.getFullName() + ": " +
" coordinates are not" +
" monotonic this means some" +
" operations will fail" );
}
// Get the centres of the pixel positions in current
// coordinates (so we can eventually go from current
// coordinates through to graphics coordinates when
// actually drawing the spectrum).
double[] tPos = ASTJ.astTran1( oned, xPos, true );
xPos = tPos;
tPos = null;
// Set the apparent data units, if possible.
convertToApparentDataUnits();
// Set the axis range.
setRangePrivate();
// Establish the digits value used to format the wavelengths,
// if not already set in the original data (the plot may
// override this).
setFormatDigits();
}
catch (Exception e) {
throw new SplatException( e );
}
}
}
/**
* If not set in the original spectral axis WCS set a value for the digits
* attribute that makes sure that each wavelength value (assuming a linear
* scale) can be distinguished.
*/
protected void setFormatDigits()
{
FrameSet frameSet = astJ.getRef();
if ( ! frameSet.test( "digits(1)" ) && xPos.length > 1 ) {
// Number of decimals needed for channel spacing. Only used
// if the necessary precision is fractional (less than 0).
// We try to keep two figures, not just one.
int first = xPos.length / 2;
double dvalue = xPos[first] - xPos[first-1];
double value = Math.abs( dvalue );
double deltapower = Math.log( value ) / Math.log( 10.0 );
int ideltapower = (int) deltapower;
// 2nd figure in fractional precision.
if ( ideltapower <= 0 ) {
ideltapower -= 2;
}
// Number of figures needed for maximum X coordinate, without
// a fractional part.
dvalue = range[1];
value = Math.abs( dvalue );
double power = Math.log( value ) / Math.log( 10.0 );
int ipower = 1 + (int) power;
// If we need fractional precision, add those figures to those
// for the maximum X coordinate.
int digits;
if ( ideltapower <= 0 ) {
digits = Math.abs( ideltapower ) + ipower;
}
else {
// Otherwise just enough figures for the X coordinate.
digits = ipower;
}
// Keep the number of digits in a sensible range.
digits = Math.min( MAX_DIGITS, Math.max( MIN_DIGITS, digits ) );
// Set the value.
frameSet.setI( "Digits(1)", digits );
}
}
/**
* Convert the data units to some new value, if possible.
*/
protected void convertToApparentDataUnits()
{
if ( apparentDataUnits == null ||
apparentDataUnits.equals( "Unknown" ) ) {
return;
}
// To do this we need to modify the data values and then set the
// data units of the Frame representing the data value to
// match. This necessarily means creating a memory copy of the
// data values. We work with the full Frame, rather than extracting
// the second axis, as FluxFrames will only transform properly when
// part of a SpecFluxFrame (to get from pre frequency to per
// wavelength requires the spectral coordinate).
// Get a reference to the current Frame. This should be a
// SpecFluxFrame or a plain CmpFrame.
FrameSet frameSet = astJ.getRef();
Frame currentFrame = frameSet.getFrame( FrameSet.AST__CURRENT );
// Make a copy of this and set the new units.
Frame targetFrame = (Frame) currentFrame.copy();
targetFrame.setActiveUnit( true );
targetFrame.set( "unit(2)=" + apparentDataUnits );
// Now try to convert between them
currentFrame.setActiveUnit( true );
Mapping mapping = currentFrame.convert( targetFrame, "" );
if ( mapping == null ) {
// If fails then just use the values we have.
logger.info( shortName + ": cannot convert data units from " +
currentFrame.getC( "unit" ) + " to " +
apparentDataUnits );
apparentDataUnits = null;
return;
}
// Now transform the original data values, not ones that may have
// already been transformed. The FrameSet will match these.
try {
double[][] tmp1 = mapping.tran2( yPos.length, xPos, yPosOri,
true );
if ( yErr != null ) {
double[][] tmp2 = mapping.tran2( yPos.length, xPos, yErrOri,
true );
yErr = new double[yPos.length];
for ( int i = 0; i < yPos.length; i++ ) {
yErr[i] = tmp2[1][i];
}
}
yPos = new double[yPos.length];
for ( int i = 0; i < yPos.length; i++ ) {
yPos[i] = tmp1[1][i];
}
}
catch (AstException e) {
logger.info( shortName + ": failed to convert to new data units ( "
+ e.getMessage() + " )" );
apparentDataUnits = null;
return;
}
// And set the data units.
currentFrame.setActiveUnit( false );
currentFrame.set( "unit(2)=" + apparentDataUnits );
}
/**
* Return the most significant axis of the data held by the
* implemenation. This is the default axis that is used when the
* underlying data has more than one dimension. The value returned is an
* AST index (starts at 1).
*/
public int getMostSignificantAxis()
{
// If this is a de-serialized spectrum the connection to the WCS
// axes, if any, has been lost - handle that.
if ( serializedSigAxis != 0 ) {
return serializedSigAxis;
}
int sigaxis = 1;
int dims[] = impl.getDims();
if ( dims.length > 1 ) {
for ( int i = 0; i < dims.length; i++ ) {
if ( dims[i] > 1 ) {
sigaxis = i + 1;
break;
}
}
}
return sigaxis;
}
/**
* If this is a nD dataset with WCS record the position of the
* spectrum in the standard properties, if possible.
*/
protected void checkForExtractionPosition( FrameSet astref, int sigaxis )
{
if ( impl instanceof FITSHeaderSource ) {
int dims[] = impl.getDims();
if ( dims.length > 1 ) {
// Get the coordinates for the grid position 1,1,1.
double basepos[] = new double[dims.length];
for ( int i = 0; i < dims.length; i++ ) {
basepos[i] = 1.0;
}
int nout = astref.getI( "Nout" );
try {
double out[] = astref.tranN( 1, dims.length, basepos,
true, nout );
int lonaxis = astref.getI( "lonaxis" );
int lataxis = astref.getI( "lataxis" );
Header header = getHeaders();
String ra = astref.format( lonaxis, out[lonaxis-1] );
String dec = astref.format( lataxis, out[lataxis-1] );
header.addValue( "EXRAX", ra, "Spectral position" );
header.addValue( "EXDECX", dec, "Spectral position" );
}
catch (Exception e) {
logger.info( "Failed to get spectral position ( " +
e.getMessage() + " )" );
e.printStackTrace();
}
}
}
}
/**
* Set/reset the current range of the data.
*/
public void setRange()
{
setRangePrivate();
}
/**
* Private version of setRange. Called from constructor so should not be
* directly overridden.
*/
private void setRangePrivate()
{
double xMin = Double.MAX_VALUE;
double xMinY = 0.0;
double xMax = -Double.MAX_VALUE;
double xMaxY = 0.0;
double yMin = xMin;
double yMinX = 0.0;
double yMax = xMax;
double yMaxX = 0.0;
double fullYMin = xMin;
double fullYMinX = 0.0;
double fullYMax = xMax;
double fullYMaxX = 0.0;
double tmp;
if ( yErr != null ) {
for ( int i = yPos.length - 1; i >= 0; i-- ) {
if ( yPos[i] != SpecData.BAD ) {
if ( xPos[i] < xMin ) {
xMin = xPos[i];
xMinY = yPos[i];
}
if ( xPos[i] > xMax ) {
xMax = xPos[i];
xMaxY = yPos[i];
}
if ( yPos[i] < yMin ) {
yMin = yPos[i];
yMinX = xPos[i];
}
if ( yPos[i] > yMax ) {
yMax = yPos[i];
yMaxX = xPos[i];
}
tmp = yPos[i] - ( yErr[i] * errorNSigma );
if ( tmp < fullYMin ) {
fullYMin = tmp;
fullYMinX = xPos[i];
}
tmp = yPos[i] + ( yErr[i] * errorNSigma );
if ( tmp > fullYMax ) {
fullYMax = tmp;
fullYMaxX = xPos[i];
}
}
}
}
else {
for ( int i = yPos.length - 1; i >= 0 ; i-- ) {
if ( yPos[i] != SpecData.BAD ) {
if ( xPos[i] < xMin ) {
xMin = xPos[i];
xMinY = yPos[i];
}
if ( xPos[i] > xMax ) {
xMax = xPos[i];
xMaxY = yPos[i];
}
if ( yPos[i] < yMin ) {
yMin = yPos[i];
yMinX = xPos[i];
}
if ( yPos[i] > yMax ) {
yMax = yPos[i];
yMaxX = xPos[i];
}
}
}
fullYMin = yMin;
fullYMax = yMax;
fullYMinX = yMinX;
fullYMaxX = yMaxX;
}
if ( xMin == Double.MAX_VALUE ) {
xMin = 0.0;
xMinY = 0.0;
}
if ( xMax == -Double.MAX_VALUE ) {
xMax = 0.0;
xMaxY = 0.0;
}
// Record plain range.
range[0] = xMin;
range[1] = xMax;
range[2] = yMin;
range[3] = yMax;
// And the "full" version.
fullRange[0] = xMin;
fullRange[1] = xMax;
fullRange[2] = fullYMin;
fullRange[3] = fullYMax;
// Add slack so that error bars do not abutt the edges.
double slack = ( fullRange[3] - fullRange[2] ) * SLACK;
fullRange[2] = fullRange[2] - slack;
fullRange[3] = fullRange[3] + slack;
// Coordinates of positions used to determine plain range.
xEndPoints[0] = xMin;
xEndPoints[1] = xMinY;
xEndPoints[2] = xMax;
xEndPoints[3] = xMaxY;
yEndPoints[0] = yMinX;
yEndPoints[1] = yMin;
yEndPoints[2] = yMaxX;
yEndPoints[3] = yMax;
// Coordinates of positions used to determine full range.
yFullEndPoints[0] = fullYMinX;
yFullEndPoints[1] = fullRange[2];
yFullEndPoints[2] = fullYMaxX;
yFullEndPoints[3] = fullRange[3];
}
/**
* Draw the spectrum onto the given widget using a suitable AST GRF
* object.
*
* @param grf Grf object that can be drawn into using AST primitives.
* @param plot reference to Plot defining transformation from physical
* coordinates into graphics coordinates.
* @param clipLimits limits of the region to draw used to clip graphics.
* These can be in physical or graphics coordinates.
* @param physical whether limits are physical or graphical.
* @param fullLimits full limits of drawing area in graphics coordinates.
* May be used for positioning when clipping limits are
* not used.
*/
public void drawSpec( Grf grf, Plot plot, double[] clipLimits,
boolean physical, double[] fullLimits )
{
// Get a list of positions suitable for transforming.
// Note BAD value is same for graphics (AST, Grf) and data,
// so tests can be missed (should only be in yPos).
double[] xypos = null;
double yoffset = 0.0;
if ( applyYOffset ) {
yoffset = this.yoffset;
}
if ( plotStyle == POLYLINE || plotStyle == POINT ) {
xypos = new double[xPos.length * 2];
for ( int i = 0, j = 0; j < xPos.length; j++, i += 2 ) {
xypos[i] = xPos[j];
xypos[i + 1] = yPos[j] + yoffset;
}
}
else {
// Draw a histogram style plot. Need to generate a list
// of positions that can be connected like a normal
// spectrum, but looks like a histogram. Create a list
// with positions at each "corner":
//
// x * x
// x * x
// x * x
//
// i.e. generate "x" positions for each "*" position. Use
// different backwards and forwards width of bin as step
// could be non-linear.
double bwidth = 0.0; // backwards width
double fwidth = 0.0; // forwards width
int i = 0; // position in xypos array (pairs of X,Y coordinates)
int j = 0; // position xPos & yPos arrays
xypos = new double[xPos.length * 4];
// First point has no backwards width, so use double
// forward width.
fwidth = ( xPos[j + 1] - xPos[j] ) * 0.5;
xypos[i] = xPos[j] - fwidth;
xypos[i + 2] = xPos[j] + fwidth;
xypos[i + 1] = yPos[j] + yoffset;
xypos[i + 3] = yPos[j] + yoffset;
j++;
i += 4;
// Do normal positions.
for ( ; j < xPos.length - 1; j++, i += 4 ) {
fwidth = ( xPos[j + 1] - xPos[j] ) * 0.5;
bwidth = ( xPos[j] - xPos[j - 1] ) * 0.5;
xypos[i] = xPos[j] - bwidth;
xypos[i + 2] = xPos[j] + fwidth;
xypos[i + 1] = yPos[j] + yoffset;
xypos[i + 3] = yPos[j] + yoffset;
}
// Until final final point which is also unpaired forward
// so use double backwards width.
bwidth = ( xPos[j] - xPos[j - 1] ) * 0.5;
xypos[i] = xPos[j] - bwidth;
xypos[i + 2] = xPos[j] + bwidth;
xypos[i + 1] = yPos[j] + yoffset;
xypos[i + 3] = yPos[j] + yoffset;
}
// Transform positions into graphics coordinates.
double[][] xygpos = astJ.astTran2( (Mapping) plot, xypos, false );
int np = xygpos[0].length;
double[] xpos = new double[np];
double[] ypos = new double[np];
for ( int j = 0; j < np; j++ ) {
xpos[j] = xygpos[0][j];
ypos[j] = xygpos[1][j];
}
// Do the same for the clip region.
Rectangle cliprect = null;
if ( clipLimits != null ) {
if ( physical ) {
double[][] clippos = astJ.astTran2( plot, clipLimits, false );
cliprect =
new Rectangle( (int) clippos[0][0],
(int) clippos[1][1],
(int) ( clippos[0][1] - clippos[0][0] ),
(int) ( clippos[1][0] - clippos[1][1] ) );
}
else {
cliprect = new Rectangle((int) clipLimits[0],
(int) clipLimits[3],
(int) (clipLimits[2]-clipLimits[0]),
(int) (clipLimits[1]-clipLimits[3]));
}
}
// Plot using the GRF primitive, rather than astPolyCurve, as
// we are just plotting spectra and require only straight
// lines, not geodesics (this makes it much faster). Need to
// establish line properites first, draw polyline and then
// restore properties.
boolean line = ( plotStyle != POINT );
DefaultGrf defaultGrf = (DefaultGrf) grf;
DefaultGrfState oldState = setGrfAttributes( defaultGrf, line );
defaultGrf.setClipRegion( cliprect );
if ( line ) {
renderSpectrum( defaultGrf, xpos, ypos );
}
else {
renderPointSpectrum( defaultGrf, xpos, ypos, pointType );
}
// Set line characteristics for error bars. Need to do this as they
// will not be set when drawing markers.
defaultGrf.attribute( Grf.GRF__COLOUR, errorColour, Grf.GRF__LINE );
defaultGrf.attribute( Grf.GRF__WIDTH, lineThickness, Grf.GRF__LINE );
defaultGrf.attribute( Grf.GRF__STYLE, lineStyle, Grf.GRF__LINE );
defaultGrf.attribute( defaultGrf.GRF__ALPHA, alphaComposite,
Grf.GRF__LINE );
renderErrorBars( defaultGrf, plot );
defaultGrf.setClipRegion( null );
resetGrfAttributes( defaultGrf, oldState, line );
}
/**
* Draw the spectrum using the current spectrum plotting style.
*
* @param grf DefaultGrf object that can be drawn into using AST
* primitives.
* @param xpos graphics X coordinates of spectrum
* @param ypos graphics Y coordinates of spectrum
*/
protected void renderSpectrum( DefaultGrf grf, double[] xpos,
double[] ypos )
{
grf.polyline( xpos, ypos );
}
/**
* Draw the spectrum using markers.
*
* @param grf DefaultGrf object that can be drawn into using AST
* primitives.
* @param xpos graphics X coordinates of spectrum
* @param ypos graphics Y coordinates of spectrum
* @param type the type of marker to use
*/
protected void renderPointSpectrum( DefaultGrf grf, double[] xpos,
double[] ypos, int type )
{
grf.marker( xpos, ypos, type );
}
/**
* Draw error bars. These are quite simple lines above and below positions
* by number of standard deviations, with a serif at each end.
*
* @param grf DefaultGrf object that can be drawn into using AST
* primitives.
* @param plot reference to Plot defining transformation from physical
* coordinates into graphics coordinates.
*/
protected void renderErrorBars( DefaultGrf grf, Plot plot )
{
if ( drawErrorBars && yErr != null ) {
double[] xypos = new double[4];
double[][] xygpos = null;
double[] xpos = null;
double[] ypos = null;
double half = 0.0;
for ( int i = 0; i < xPos.length; i += errorFrequency ) {
if ( yErr[i] != SpecData.BAD ) {
half = yErr[i] * errorNSigma;
xypos[0] = xPos[i];
xypos[1] = yPos[i] - half;
xypos[2] = xPos[i];
xypos[3] = yPos[i] + half;
xygpos = astJ.astTran2( plot, xypos, false );
xpos = new double[2];
ypos = new double[2];
xpos[0] = xygpos[0][0];
xpos[1] = xygpos[0][1];
ypos[0] = xygpos[1][0];
ypos[1] = xygpos[1][1];
grf.polyline( xpos, ypos );
// Add the serifs.
xpos = new double[2];
ypos = new double[2];
xpos[0] = xygpos[0][0] - SERIF_LENGTH;
xpos[1] = xygpos[0][0] + SERIF_LENGTH;
ypos[0] = xygpos[1][0];
ypos[1] = xygpos[1][0];
grf.polyline( xpos, ypos );
xpos = new double[2];
ypos = new double[2];
xpos[0] = xygpos[0][1] - SERIF_LENGTH;
xpos[1] = xygpos[0][1] + SERIF_LENGTH;
ypos[0] = xygpos[1][1];
ypos[1] = xygpos[1][1];
grf.polyline( xpos, ypos );
}
}
}
}
/**
* Apply the current state to a Grf object, returning its existing state,
* so that it can be restored.
*
* @param grf Grf object that can be drawn into using AST primitives.
* @return the graphics state of the Grf object before being modified by
* this method.
*/
protected DefaultGrfState setGrfAttributes( DefaultGrf grf, boolean line )
{
DefaultGrfState oldState = new DefaultGrfState();
if ( line ) {
oldState.setColour( grf.attribute( Grf.GRF__COLOUR, BAD,
Grf.GRF__LINE ) );
oldState.setStyle( grf.attribute( Grf.GRF__STYLE, BAD,
Grf.GRF__LINE ) );
oldState.setWidth( grf.attribute( Grf.GRF__WIDTH, BAD,
Grf.GRF__LINE ) );
oldState.setAlpha( grf.attribute( grf.GRF__ALPHA, BAD,
Grf.GRF__LINE ) );
// Set new one from object members.
grf.attribute( Grf.GRF__WIDTH, lineThickness, Grf.GRF__LINE );
grf.attribute( Grf.GRF__STYLE, lineStyle, Grf.GRF__LINE );
grf.attribute( Grf.GRF__COLOUR, lineColour, Grf.GRF__LINE );
grf.attribute( grf.GRF__ALPHA, alphaComposite, Grf.GRF__LINE );
}
else {
oldState.setColour( grf.attribute( Grf.GRF__COLOUR, BAD,
Grf.GRF__MARK ) );
oldState.setSize( grf.attribute( Grf.GRF__SIZE, BAD,
Grf.GRF__MARK ) );
oldState.setAlpha( grf.attribute( grf.GRF__ALPHA, BAD,
Grf.GRF__MARK ) );
// Set new one from object members.
grf.attribute( Grf.GRF__SIZE, pointSize, Grf.GRF__MARK );
grf.attribute( Grf.GRF__COLOUR, lineColour, Grf.GRF__MARK );
grf.attribute( grf.GRF__ALPHA, alphaComposite, Grf.GRF__MARK );
}
return oldState;
}
/**
* Restore an existing Grf object to a given state.
*
* @param grf Grf object being used.
* @param oldState the state to return Grf object to.
*/
protected void resetGrfAttributes( DefaultGrf grf,
DefaultGrfState oldState,
boolean line )
{
if ( line ) {
grf.attribute( Grf.GRF__COLOUR, oldState.getColour(),
Grf.GRF__LINE );
grf.attribute( Grf.GRF__STYLE, oldState.getStyle(),
Grf.GRF__LINE );
grf.attribute( Grf.GRF__WIDTH, oldState.getWidth(),
Grf.GRF__LINE );
grf.attribute( grf.GRF__ALPHA, oldState.getAlpha(),
Grf.GRF__LINE );
}
else {
grf.attribute( Grf.GRF__COLOUR, oldState.getColour(),
Grf.GRF__MARK );
grf.attribute( Grf.GRF__SIZE, oldState.getSize(),
Grf.GRF__MARK );
grf.attribute( grf.GRF__ALPHA, oldState.getAlpha(),
Grf.GRF__MARK );
}
}
/**
* Draw a fake spectrum using some given graphics coordinates
* as the X and Y positions. This is intended for use when
* a small representation of the spectrum is required, for
* instance as part of a plot legend. See {@link drawSpec}.
*
* Note if a histogram style is being used that will be ignored.
*
* @param grf Grf object that can be drawn into using AST primitives.
* @param xpos the graphics X positions.
* @param ypos the graphics Y positions.
*/
public void drawLegendSpec( Grf grf, double xpos[], double ypos[] )
{
boolean line = ( plotStyle != POINT );
DefaultGrf defaultGrf = (DefaultGrf) grf;
DefaultGrfState oldState = setGrfAttributes( defaultGrf, line );
if ( line ) {
renderSpectrum( defaultGrf, xpos, ypos );
}
else {
renderPointSpectrum( defaultGrf, xpos, ypos, pointType );
}
resetGrfAttributes( defaultGrf, oldState, line );
}
/**
* Lookup the index nearest to a given physical coordinate.
*
* @param x X coordinate
* @return the index.
*/
public int nearestIndex( double x )
{
// Bound our value.
int[] bounds = bound( x );
// Find which position is nearest.
double[] result = new double[2];
if ( Math.abs(x - xPos[bounds[0]]) < Math.abs(xPos[bounds[1]] - x) ) {
return bounds[0];
}
return bounds[1];
}
/**
* Lookup the nearest physical values (wavelength and data value)
* to a given physical coordinate.
*
* @param x X coordinate
* @return array of two doubles. The wavelength and data values.
*/
public double[] nearest( double x )
{
int index = nearestIndex( x );
double[] result = new double[2];
result[0] = xPos[index];
result[1] = yPos[index];
return result;
}
/**
* Lookup the physical values (wavelength and data value) that correspond
* to a graphics X coordinate.
*
* @param xg X graphics coordinate
* @param plot AST plot needed to transform graphics position into
* physical coordinates
* @return array of two doubles. The wavelength and data values.
*/
public double[] lookup( int xg, Plot plot )
{
// Get the physical coordinate that corresponds to our
// graphics position.
double[] xypos = new double[2];
xypos[0] = (double) xg;
xypos[1] = 0.0;
double[][] xyphys = ASTJ.astTran2( plot, xypos, true );
return nearest( xyphys[0][0] );
}
/**
* Locate the indices of the two coordinates that lie closest to a given
* coordinate. In the case of an exact match or value that lies
* beyond the edges, then both indices are returned as the same value.
*
* @param xcoord the coordinate value to bound.
* @return array of two integers, the lower and upper indices.
*/
public int[] bound( double xcoord )
{
int bounds[] = new int[2];
int low = 0;
int high = xPos.length - 1;
boolean increases = ( xPos[low] < xPos[high] );
// Check off scale.
if ( ( increases && xcoord < xPos[low] ) ||
( ! increases && xcoord > xPos[low] ) ) {
high = low;
}
else if ( ( increases && xcoord > xPos[high] ) ||
( ! increases && xcoord < xPos[high] ) ) {
low = high;
}
else {
// Use a binary search as values should be sorted to increase
// in either direction (wavelength, pixel coordinates etc.).
int mid = 0;
if ( increases ) {
while ( low < high - 1 ) {
mid = ( low + high ) / 2;
if ( xcoord < xPos[mid] ) {
high = mid;
}
else if ( xcoord > xPos[mid] ) {
low = mid;
}
else {
// Exact match.
low = high = mid;
break;
}
}
}
else {
while ( low < high - 1 ) {
mid = ( low + high ) / 2;
if ( xcoord > xPos[mid] ) {
high = mid;
}
else if ( xcoord < xPos[mid] ) {
low = mid;
}
else {
// Exact match.
low = high = mid;
break;
}
}
}
}
bounds[0] = low;
bounds[1] = high;
return bounds;
}
/**
* Lookup the physical values (i.e. wavelength and data value) that
* correspond to a graphics X coordinate. Value is returned as formatted
* strings for the selected axis (could be sky coordinates for instance).
*
* @param xg X graphics coordinate
* @param plot AST plot needed to transform graphics position into
* physical coordinates
* @return array of two Strings, the formatted wavelength and data values
*/
public String[] formatLookup( int xg, Plot plot )
{
double[] xypos = lookup( xg, plot );
// Let AST format the values as appropriate for the axes.
String result[] = new String[2];
result[0] = ASTJ.astFormat( 1, plot, xypos[0] );
result[1] = ASTJ.astFormat( 2, plot, xypos[1] );
return result;
}
/**
* Return interpolated physical values (i.e. wavelength and
* data value) that correspond to a graphics X coordinate.
*
* @param xg X graphics coordinate
* @param plot AST plot needed to transform graphics position into
* physical coordinates
* @return the physical coordinate and value. These are linearly
* interpolated.
*/
public String[] formatInterpolatedLookup( int xg, Plot plot )
{
// Convert the graphics coordinate to a physical coordinate.
double[] xypos = new double[2];
xypos[0] = (double) xg;
xypos[1] = 0.0;
double[][] xyphys = ASTJ.astTran2( plot, xypos, true );
// Get the indices of surrounding positions.
int[] bounds = bound( xyphys[0][0] );
if ( bounds[0] == bounds[1] ) {
xyphys[1][0] = yPos[bounds[0]];
}
else {
// interpolate for the data value.
xyphys[1][0] = yPos[bounds[0]] +
( yPos[bounds[0]] - yPos[bounds[1]] ) /
( xPos[bounds[0]] - xPos[bounds[1]] ) *
( xyphys[0][0] - xPos[bounds[0]] );
}
// Let AST format the values as appropriate for the axes.
String result[] = new String[2];
result[0] = ASTJ.astFormat( 1, plot, xyphys[0][0] );
result[1] = ASTJ.astFormat( 2, plot, xyphys[1][0] );
return result;
}
/**
* Convert a formatted coordinate string into a double precision value
* (could be celestial coordinates for example).
*
* @param axis the axis to use for formatting rules.
* @param plot AST plot that defines the coordinate formats.
* @param value the formatted value.
* @return the unformatted value.
*/
public double unFormat( int axis, Plot plot, String value )
{
return ASTJ.astUnFormat( axis, plot, value );
}
/**
* Convert a coordinate value into a formatted String suitable for a given
* axis (could be celestial coordinates for example).
*
* @param axis the axis to use for formatting rules.
* @param value the value.
* @param plot AST plot that defines the coordinate formats.
* @return the formatted value.
*/
public String format( int axis, Plot plot, double value )
{
return ASTJ.astFormat( axis, plot, value );
}
//
// Column names and control (optional within the implementation).
//
/**
* Return if the implementation supports the modification of
* columns.
*/
public boolean isColumnMutable()
{
return ( getColumnNames() != null );
}
/**
* Return the names of all the available columns, if they can be
* modified. Returns null otherwise.
*/
public String[] getColumnNames()
{
return impl.getColumnNames();
}
/**
* Return the name of the column associated with the coordinates.
* If modification is not supported then this name is only symbolic.
*/
public String getXDataColumnName()
{
return impl.getCoordinateColumnName();
}
/**
* Set the name of the column associated with the coordinates. If
* the underlying implementation supports it this will result in a
* modification of the coordinate system and coordinate values.
*/
public void setXDataColumnName( String name )
throws SplatException
{
setXDataColumnName( name, false );
}
/**
* Set the name of the column associated with the coordinates. If
* the underlying implementation supports it this will result in a
* modification of the coordinate system and coordinate values.
* The update to the AST coordinate systems can be suppressed using this
* method, only do this if you know an update will happen anyway.
*/
public void setXDataColumnName( String name, boolean updateAST )
throws SplatException
{
if ( isColumnMutable() ) {
String currentName = getXDataColumnName();
if ( ! currentName.equals( name ) ) {
impl.setCoordinateColumnName( name );
if ( updateAST ) {
initialiseAst();
}
}
}
}
/**
* Return the name of the column associated with the data values.
* If modification is not supported then this name is only symbolic.
*/
public String getYDataColumnName()
{
return impl.getDataColumnName();
}
/**
* Set the name of the column associated with the data values. If
* the underlying implementation supports it this will result in a
* modification of values. Returns true if the name didn't match the
* previous value, and names are mutable (in this instance a re-read of
* the data has occurred and the coordinate systems have been updated).
*/
public boolean setYDataColumnName( String name )
throws SplatException
{
if ( isColumnMutable() ) {
String currentName = getYDataColumnName();
if ( ! currentName.equals( name ) ) {
impl.setDataColumnName( name );
readData();
return true;
}
}
return false;
}
/**
* Return the name of the column associated with the data errors.
* If modification is not supported then this name is only symbolic.
*/
public String getYDataErrorColumnName()
{
return impl.getDataErrorColumnName();
}
/**
* Set the name of the column associated with the data errors. If
* the underlying implementation supports it this will result in a
* modification of values.
*/
public void setYDataErrorColumnName( String name )
throws SplatException
{
if ( isColumnMutable() ) {
String currentName = getYDataErrorColumnName();
if ( ! currentName.equals( name ) ) {
impl.setDataErrorColumnName( name );
yErr = impl.getDataErrors();
}
}
}
//
// AnalyticSpectrum implementation.
// TODO: flux conversation and error estimation, proper model
// types (i.e. use another object to compute values).
//
/**
* Return the value of the spectrum at an arbitrary X position.
*
* @param x the coordinate at which to evaluate this spectrum.
* @return data value of this spectrum at the given coordinate.
*/
public double evalYData( double x )
{
// Locate the bounds of the point.
int[] bounds = bound( x );
int low = bounds[0];
int high = bounds[1];
if ( low == high ) {
return yPos[low];
}
else if ( yPos[low] == SpecData.BAD || yPos[high] == SpecData.BAD ) {
return SpecData.BAD;
}
else {
if ( low > high ) {
int tmp = low;
low = high;
high = tmp;
}
// Interpolate a data value;
double m = ( yPos[low] - yPos[high] ) / ( xPos[low] - xPos[high] );
return x * m + ( yPos[low] - ( xPos[low] * m ) );
}
}
/**
* Return the value of the spectrum evaluated at series of arbitrary X
* positions.
*
* @param x the coordiantes at which to evaluate this spectrum.
* @return data values of this spectrum at the given coordinates.
*/
public double[] evalYDataArray( double[] x )
{
double[] y = new double[x.length];
for ( int i = 0; i < x.length; i++ ) {
y[i] = evalYData( x[i] );
}
return y;
}
//
// Serializable interface.
//
/**
* Store this object in a serialized state. The main purpose of providing
* this method is to also accommodate the serialization of the current
* implementation FrameSet (by AST).
*/
private void writeObject( ObjectOutputStream out )
throws IOException
{
// Serialize the AST FrameSet.
serializedFrameSet = new String[1];
ASTChannel chan = new ASTChannel( serializedFrameSet );
chan.write( impl.getAst() );
serializedFrameSet = new String[chan.getIndex()];
chan.setArray( serializedFrameSet );
chan.write( impl.getAst() );
// Store data units and label.
serializedDataUnits = getCurrentDataUnits();
serializedDataLabel = getDataLabel();
// Store signficant axis, so correct axis of the WCS is
// used on restoration.
serializedSigAxis = getMostSignificantAxis();
// And store all member variables.
out.defaultWriteObject();
// Finished.
serializedFrameSet = null;
serializedDataUnits = null;
serializedDataLabel = null;
}
/**
* Restore an object from a serialized state. Note all objects restored by
* this route are assigned a MEMSpecDataImpl object, as the association
* between a disk file and deserialized object cannot be guaranteed
* (TODO: might like to store some details about the original file
* somewhere). This method is also necessary so that AST objects can be
* restored.
*
* @param in the serialized stream containing object of this class.
* @exception IOException Description of the Exception
* @exception ClassNotFoundException Description of the Exception
*/
private void readObject( ObjectInputStream in )
throws IOException, ClassNotFoundException
{
try {
// Restore state of member variables.
in.defaultReadObject();
// Create the backing impl.
MEMSpecDataImpl newImpl = new MEMSpecDataImpl( shortName );
fullName = null;
// Restore the AST FrameSet, if available.
if ( serializedFrameSet != null ) {
ASTChannel chan = new ASTChannel( serializedFrameSet );
FrameSet frameSet = (FrameSet) chan.read();
serializedFrameSet = null;
if ( serializedDataUnits != null ) {
newImpl.setDataUnits( serializedDataUnits );
serializedDataUnits = null;
}
if ( serializedDataLabel != null ) {
newImpl.setDataLabel( serializedDataLabel );
serializedDataLabel = null;
}
if ( haveYDataErrors() ) {
newImpl.setFullData( frameSet, newImpl.getDataUnits(),
getYData(), getYDataErrors() );
}
else {
newImpl.setFullData( frameSet, newImpl.getDataUnits(),
getYData() );
}
}
else {
if ( haveYDataErrors() ) {
newImpl.setSimpleData( getXData(), newImpl.getDataUnits(),
getYData(), getYDataErrors() );
}
else {
newImpl.setSimpleData( getXData(), newImpl.getDataUnits(),
getYData() );
}
}
this.impl = newImpl;
// Full reset of state.
readDataPrivate();
}
catch ( SplatException e ) {
e.printStackTrace();
}
}
}
| true | true | public SpecData getSubSet( String name, double[] ranges )
{
// Locate the index of the positions just below and above our
// physical value pairs and count the number of values that will be
// deleted.
int nRanges = ranges.length / 2;
int[] lower = new int[nRanges];
int[] upper = new int[nRanges];
int[] low;
int[] high;
int ndelete = 0;
for ( int i = 0, j = 0; j < nRanges; i += 2, j++ ) {
low = bound( ranges[i] );
lower[j] = low[1];
high = bound( ranges[i + 1] );
upper[j] = high[0];
ndelete += high[0] - low[1] + 1;
}
if ( ndelete < 0 ) {
// Coordinates run in a reversed direction.
ndelete = Math.abs( ndelete ) + 2 * nRanges;
high = lower;
lower = upper;
upper = high;
// The ranges must increase.
Sort.insertionSort2( lower, upper );
}
if ( ndelete >= xPos.length || ndelete == 0 ) {
return null;
}
// Copy remaining data. The size of result spectrum is the current
// size, minus the number of positions that will be erased, plus one
// per range to hold the BAD value to form the break.
int nkeep = xPos.length - ndelete + nRanges;
double[] newCoords = new double[nkeep];
double[] newData = new double[nkeep];
int length = 0;
for ( int i = 0, j = 0, k = 0; i < xPos.length; i++ ) {
if ( i >= lower[j] && i <= upper[j] ) {
// Arrived within a range, so mark one mid-range
// position BAD (so show the break) and skip to the
// end. Set for next valid range.
newData[k] = BAD;
k++;
if ( j + 1 == nRanges ) {
// No more ranges, so just complete the copy.
for ( int l = upper[j] + 1; l < xPos.length; l++ ) {
if ( k < nkeep ) {
newCoords[k] = xPos[l];
newData[k] = yPos[l];
}
k++;
}
i = xPos.length;
break;
}
i = upper[j];
j++;
}
else {
newCoords[k] = xPos[i];
newData[k] = yPos[i];
k++;
}
}
// Same for errors, if have any.
double[] newErrors = null;
if ( haveYDataErrors() ) {
newErrors = new double[nkeep];
for ( int i = 0, j = 0, k = 0; i < xPos.length; i++ ) {
if ( i >= lower[j] && i <= upper[j] ) {
newErrors[k] = BAD;
k++;
if ( j + 1 == nRanges ) {
for ( int l = upper[j] + 1; l < xPos.length; l++ ) {
if ( k < nkeep ) {
newErrors[k] = yErr[l];
}
k++;
}
i = xPos.length;
break;
}
i = upper[j];
j++;
}
else {
newErrors[k] = yErr[i];
k++;
}
}
}
// Final task, trim off any BAD values at ends if ranges
// included those.
if ( lower[0] <= 0 || upper[upper.length-1] >= ( xPos.length - 1 ) ) {
int i1 = 0;
int i2 = newData.length;
if ( lower[0] <= 0 ) {
i1++;
}
if ( upper[upper.length-1] >= ( xPos.length - 1 ) ) {
i2--;
}
int trimlength = i2 - i1;
double trimCoords[] = new double[trimlength];
System.arraycopy( newCoords, i1, trimCoords, 0, trimlength );
newCoords = trimCoords;
double trimData[] = new double[trimlength];
System.arraycopy( newData, i1, trimData, 0, trimlength );
newData = trimData;
double trimErrors[] = null;
if ( newErrors != null ) {
trimErrors = new double[trimlength];
System.arraycopy( newErrors, i1, trimErrors, 0, trimlength );
newErrors = trimErrors;
}
}
// And create the memory spectrum.
return createNewSpectrum( name, newCoords, newData, newErrors );
}
| public SpecData getSubSet( String name, double[] ranges )
{
// Locate the index of the positions just below and above our
// physical value pairs and count the number of values that will be
// deleted.
int nRanges = ranges.length / 2;
int[] lower = new int[nRanges];
int[] upper = new int[nRanges];
int[] low;
int[] high;
int ndelete = 0;
for ( int i = 0, j = 0; j < nRanges; i += 2, j++ ) {
low = bound( ranges[i] );
lower[j] = low[1];
high = bound( ranges[i + 1] );
upper[j] = high[0];
ndelete += high[0] - low[1] + 1;
}
if ( ndelete < 0 ) {
// Coordinates run in a reversed direction.
ndelete = Math.abs( ndelete ) + 2 * nRanges;
high = lower;
lower = upper;
upper = high;
// The ranges must increase.
Sort.insertionSort2( lower, upper );
}
if ( ndelete >= xPos.length || ndelete == 0 ) {
return null;
}
// Copy remaining data. The size of result spectrum is the current
// size, minus the number of positions that will be erased, plus one
// per range to hold the BAD value to form the break.
int nkeep = xPos.length - ndelete + nRanges;
double[] newCoords = new double[nkeep];
double[] newData = new double[nkeep];
int length = 0;
for ( int i = 0, j = 0, k = 0; i < xPos.length; i++ ) {
if ( i >= lower[j] && i <= upper[j] ) {
// Arrived within a range, so mark one mid-range
// position BAD (so show the break) and skip to the
// end. Set for next valid range.
newCoords[k] = xPos[i];
newData[k] = BAD;
k++;
if ( j + 1 == nRanges ) {
// No more ranges, so just complete the copy.
for ( int l = upper[j] + 1; l < xPos.length; l++ ) {
if ( k < nkeep ) {
newCoords[k] = xPos[l];
newData[k] = yPos[l];
}
k++;
}
i = xPos.length;
break;
}
i = upper[j];
j++;
}
else {
newCoords[k] = xPos[i];
newData[k] = yPos[i];
k++;
}
}
// Same for errors, if have any.
double[] newErrors = null;
if ( haveYDataErrors() ) {
newErrors = new double[nkeep];
for ( int i = 0, j = 0, k = 0; i < xPos.length; i++ ) {
if ( i >= lower[j] && i <= upper[j] ) {
newErrors[k] = BAD;
k++;
if ( j + 1 == nRanges ) {
for ( int l = upper[j] + 1; l < xPos.length; l++ ) {
if ( k < nkeep ) {
newErrors[k] = yErr[l];
}
k++;
}
i = xPos.length;
break;
}
i = upper[j];
j++;
}
else {
newErrors[k] = yErr[i];
k++;
}
}
}
// Final task, trim off any BAD values at ends if ranges
// included those.
if ( lower[0] <= 0 || upper[upper.length-1] >= ( xPos.length - 1 ) ) {
int i1 = 0;
int i2 = newData.length;
if ( lower[0] <= 0 ) {
i1++;
}
if ( upper[upper.length-1] >= ( xPos.length - 1 ) ) {
i2--;
}
int trimlength = i2 - i1;
double trimCoords[] = new double[trimlength];
System.arraycopy( newCoords, i1, trimCoords, 0, trimlength );
newCoords = trimCoords;
double trimData[] = new double[trimlength];
System.arraycopy( newData, i1, trimData, 0, trimlength );
newData = trimData;
double trimErrors[] = null;
if ( newErrors != null ) {
trimErrors = new double[trimlength];
System.arraycopy( newErrors, i1, trimErrors, 0, trimlength );
newErrors = trimErrors;
}
}
// And create the memory spectrum.
return createNewSpectrum( name, newCoords, newData, newErrors );
}
|
diff --git a/src/net/cscott/sdr/calls/lists/BasicList.java b/src/net/cscott/sdr/calls/lists/BasicList.java
index 0b15243..0a1b342 100644
--- a/src/net/cscott/sdr/calls/lists/BasicList.java
+++ b/src/net/cscott/sdr/calls/lists/BasicList.java
@@ -1,556 +1,558 @@
package net.cscott.sdr.calls.lists;
import static java.util.Arrays.asList;
import static net.cscott.sdr.calls.parser.CallFileLexer.PART;
import static net.cscott.sdr.util.Tools.foreach;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import net.cscott.jdoctest.JDoctestRunner;
import net.cscott.sdr.calls.BadCallException;
import net.cscott.sdr.calls.Call;
import net.cscott.sdr.calls.DanceState;
import net.cscott.sdr.calls.Dancer;
import net.cscott.sdr.calls.DancerPath;
import net.cscott.sdr.calls.Evaluator;
import net.cscott.sdr.calls.ExactRotation;
import net.cscott.sdr.calls.Formation;
import net.cscott.sdr.calls.FormationList;
import net.cscott.sdr.calls.FormationMatch;
import net.cscott.sdr.calls.MatcherList;
import net.cscott.sdr.calls.Position;
import net.cscott.sdr.calls.Program;
import net.cscott.sdr.calls.Selector;
import net.cscott.sdr.calls.StandardDancer;
import static net.cscott.sdr.calls.StandardDancer.*;
import net.cscott.sdr.calls.TaggedFormation;
import net.cscott.sdr.calls.ast.Apply;
import net.cscott.sdr.calls.ast.Comp;
import net.cscott.sdr.calls.ast.Expr;
import net.cscott.sdr.calls.ast.In;
import net.cscott.sdr.calls.ast.Part;
import static net.cscott.sdr.calls.ast.Part.Divisibility.*;
import net.cscott.sdr.calls.ast.Seq;
import net.cscott.sdr.calls.ast.SeqCall;
import net.cscott.sdr.calls.grm.Grm;
import net.cscott.sdr.calls.grm.Rule;
import net.cscott.sdr.calls.lists.C1List.ConcentricEvaluator;
import net.cscott.sdr.calls.lists.C1List.ConcentricType;
import net.cscott.sdr.calls.transform.Fractional;
import net.cscott.sdr.util.Fraction;
import net.cscott.sdr.util.Point;
import net.cscott.sdr.util.Tools.F;
import org.junit.runner.RunWith;
/**
* The <code>BasicList</code> class contains complex call
* and concept definitions which are on the 'basic' program.
* Note that "simple" calls and concepts are defined in
* the resource file at
* <a href="doc-files/basic.calls"><code>net/cscott/sdr/calls/lists/basic.calls</code></a>;
* this class contains only those definitions for which an
* executable component is required.
* @author C. Scott Ananian
* @version $Id: BasicList.java,v 1.20 2009-02-05 06:13:31 cananian Exp $
*/
@RunWith(value=JDoctestRunner.class)
public abstract class BasicList {
// hide constructor.
private BasicList() { }
private static abstract class BasicCall extends Call {
private final String name;
BasicCall(String name) { this.name = name; }
@Override
public final String getName() { return name; }
@Override
public final Program getProgram() { return Program.BASIC; }
@Override
public Rule getRule() { return null; }
@Override
public List<Expr> getDefaultArguments() {
return Collections.emptyList();
}
}
/** Simple combining concept. */
public static final Call AND = new BasicCall("and") {
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args) {
assert args.size()>=1;
List<SeqCall> l = foreach(args, new F<Expr,SeqCall>(){
@Override
public Apply map(Expr e) { return new Apply(e); }
});
return new Evaluator.Standard(new Seq(l));
}
@Override
public int getMinNumberOfArguments() { return 1; }
@Override
public Rule getRule() {
// this introduces ambiguities into the grammar; ban 'and'
// as a simple connector.
if (true) return null;
Grm g = Grm.parse("<0=anything> and <1=anything>");
return new Rule("anything", g, Fraction.valueOf(-30));
}
};
/** Time readjustment. */
public static final Call IN = new BasicCall("_in") {
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
Evaluator arg = args.get(1).evaluate(Evaluator.class, ds);
// if this is a simple call, expand it directly
Comp result;
if (arg.hasSimpleExpansion())
result = arg.simpleExpansion();
// for complicated calls, use a Seq(Apply(...))
else
result = new Seq(new Apply(args.get(1)));
return new Evaluator.Standard(new In(args.get(0), result));
}
@Override
public int getMinNumberOfArguments() {
return 2;
}
};
// LEFT means 'do each part LEFT' but collisions are still resolved to
// right hands. (opposed to MIRROR, where collisions are to left hands).
public static final Call LEFT = new BasicCall("left") {
@Override
public int getMinNumberOfArguments() { return 1; }
@Override
public Rule getRule() {
Grm g = Grm.parse("left <0=leftable_anything>");
return new Rule("anything", g, Fraction.TWO); // bind tight
}
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args) {
assert args.size()==1;
return new LRMEvaluator(LRMType.LEFT, args.get(0));
}
};
public static final Call REVERSE = new BasicCall("reverse") {
@Override
public int getMinNumberOfArguments() { return 1; }
@Override
public Rule getRule() {
Grm g = Grm.parse("reverse <0=reversable_anything>");
return new Rule("anything", g, Fraction.TWO); // bind tight
}
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args) {
assert args.size()==1;
return new LRMEvaluator(LRMType.REVERSE, args.get(0));
}
};
/** Enumeration: left, reverse, or mirror. */
public static enum LRMType { LEFT, MIRROR, REVERSE; }
/** Evaluator for left, reverse, and mirror. */
public static class LRMEvaluator extends Evaluator {
private final LRMType which;
private final Expr comp;
public LRMEvaluator(LRMType which, Expr arg) {
this.which = which;
this.comp = arg;
}
@Override
public Evaluator evaluate(DanceState ds) {
boolean mirrorShoulderPass = (which == LRMType.MIRROR);
// XXX NEED A LEFT MEANS MIRROR FLAG, which is does, generally;
// otherwise 'left pass thru' passes right shoulders (!)
mirrorShoulderPass = true;
// Mirror the current formation.
// (any existing collisions should resolve 'mirror')
Formation nf = ds.currentFormation().mirror(true);
DanceState nds = ds.cloneAndClear(nf);
// do the call in the mirrored formation
new Apply(this.comp).evaluator(nds).evaluateAll(nds);
// now re-mirror the resulting paths.
for (Dancer d : nds.dancers()) {
for (DancerPath dp : nds.movements(d)) {
ds.add(d, dp.mirror(mirrorShoulderPass));
}
}
// no more to evaluate
return null;
}
};
/**
* The "with designated" concept saves the designated dancers (in the
* {@link DanceState}) so that they can be referred to later in the call.
* This is used for '<anyone> hop' and even for the humble
* '<anyone> run'.
* Takes at least two arguments; all except the last are tag names; dancers
* who match any of these tags are saved as the 'designated' ones. (Note
* that you can add 'DESIGNATED' as one of the tags in order to grow the
* designated tag set after performing another match; not sure if that
* would ever be necessary.)
* @doc.test
* Show how this concept is used for 'designees run':
* js> importPackage(net.cscott.sdr.calls.ast)
* js> a1 = Expr.literal("_designees run")
* '_designees run
* js> a = new Apply(new Expr("_with designated", Expr.literal("boy"), a1))
* (Apply (Expr _with designated 'boy '_designees run))
*/
public static final Call _WITH_DESIGNATED = new BasicCall("_with designated") {
@Override
public int getMinNumberOfArguments() { return 2; }
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
// all but the last argument are names of tags
assert args.size()==2;
final Selector selector =
args.get(0).evaluate(Selector.class, ds);
// fetch the subcall, and make an evaluator which will eventually
// pop the designated dancers to clean up.
final Evaluator subEval =
args.get(1).evaluate(Evaluator.class, ds);
final Evaluator popEval = new Evaluator() {
private Evaluator next = subEval;
@Override
public Evaluator evaluate(DanceState ds) {
this.next = next.evaluate(ds);
if (this.next == null) {
// we're finally done with the subcall!
ds.popDesignated();
return null;
}
return this;
}
};
// return an evaluator which matches the tags against the current
// formation, mutates the dance state, and then delegates to the
// popEval to do the actual evaluation and eventual cleanup
return new Evaluator() {
@Override
public Evaluator evaluate(DanceState ds) {
// get the current tagged formation, match, push
Formation f = ds.currentFormation();
TaggedFormation tf = TaggedFormation.coerce(f);
Set<Dancer> matched = selector.select(tf);
ds.pushDesignated(matched);
// delegate, eventually clean up
return popEval.evaluate(ds);
}
};
}
};
/** Like the "concentric" concept, but no adjustment for ends. What's
* usually meant by "centers X while the ends do Y". */
public static final Call QUASI_CONCENTRIC = new BasicCall("_quasi concentric") {
@Override
public int getMinNumberOfArguments() { return 2; }
@Override
public Rule getRule() { return null; /* internal call */ }
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args) {
assert args.size() == 2;
return new ConcentricEvaluator(args.get(0), args.get(1),
ConcentricType.QUASI);
}
};
// complex concept -- not sure correct program here?
// XXX: support further subdivision of DOSADO 1 1/2 by allowing an
// integer argument to Part which specifies how many parts
// it should be considered as?
/**
* The "fractional" concept.
* @doc.test
* Evaluate TWICE DOSADO and the DOSADO 1 1/2. Note that we prohibit
* further subdivision of the DOSADO 1 1/2.
* js> importPackage(net.cscott.sdr.calls)
* js> importPackage(net.cscott.sdr.calls.ast)
* js> ds = new DanceState(new DanceProgram(Program.C4), Formation.SQUARED_SET); undefined;
* js> a1 = Expr.literal("dosado")
* 'dosado
* js> a = new Expr("_fractional", Expr.literal("2"), a1)
* (Expr _fractional '2 'dosado)
* js> BasicList._FRACTIONAL.getEvaluator(ds, a.args).simpleExpansion()
* (Seq (Apply 'dosado) (Apply 'dosado))
* js> a = new Expr("_fractional", Expr.literal("1 1/2"), a1)
* (Expr _fractional '1 1/2 'dosado)
* js> BasicList._FRACTIONAL.getEvaluator(ds, a.args).simpleExpansion()
* (Seq (Part 'INDETERMINATE '1 (Seq (Apply 'dosado) (Part 'DIVISIBLE '1 (In (Expr _multiply num '1/2 '6) (Opt (From 'ANY (Seq (Part 'INDIVISIBLE '1 (Seq (Apply '_mixed touch))) (Part 'DIVISIBLE '3 (In (Expr _multiply num '1/3 '6) (Opt (From 'RH MINIWAVE (Seq (Prim 1, 1, none, 1, SASHAY_FINISH))))))))))))))
*/
public static final Call _FRACTIONAL = new BasicCall("_fractional") {
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
Fractional fv = new Fractional(ds); // visitor singleton
boolean isDivisible = true;
assert args.size()==2;
Fraction n = args.get(0).evaluate(Fraction.class, ds);
Apply a = new Apply(args.get(1));
if (n.compareTo(Fraction.ZERO) <= 0)
throw new BadCallException("Non-positive fractions are not allowed");
int whole = n.floor();
List<SeqCall> l = new ArrayList<SeqCall>(whole+1);
// easy case: do the whole repetitions of the
// call.
for (int i=0; i<whole; i++)
l.add(a);
// now add the fraction, if there is one.
// note this does not get wrapped in a PART:
// we can't further fractionalize (say)
// swing thru 1 1/2.
n=n.subtract(Fraction.valueOf(whole));
if (!Fraction.ZERO.equals(n)) {
l.add(fv.visit(a, n));
if (whole!=0)
isDivisible=false;
}
Comp result = new Seq(l);
// OPTIMIZATION: SEQ(PART(c)) = c
if (l.size()==1 && l.get(0).type==PART) {
Part p = (Part) l.get(0);
if (p.divisibility==DIVISIBLE)
result = p.child;
} else if (!isDivisible)
// we don't support subdivision of "swing thru 2 1/2"
result = new Seq(new Part(INDETERMINATE, Fraction.ONE, result));
return new Evaluator.Standard(result);
}
@Override
public int getMinNumberOfArguments() { return 2; }
@Override
public Rule getRule() {
String rule = "do <0=fraction> (of (a|an)?)? <1=anything>" +
"| <1=anything> <0=times>";
Grm g = Grm.parse(rule);
return new Rule("anything", g, Fraction.valueOf(-10));
}
};
/** Grammar tweak: allow "do half of a ..." in addition to the
* longer-winded "do one half of a..." or "do a half of a...". */
public static final Call _HALF = new BasicCall("_half") {
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
assert args.size()==1;
return _FRACTIONAL.getEvaluator
(ds, asList(Expr.literal(Fraction.ONE_HALF), args.get(0)));
}
@Override
public int getMinNumberOfArguments() { return 1; }
@Override
public Rule getRule() {
String rule = "do half of (a|an)? <0=anything>";
Grm g = Grm.parse(rule);
return new Rule("anything", g, Fraction.valueOf(-10));
}
};
/**
* Adjust circle to its other orientation. Used for 'circle choreography'
* like allemande left, swing thru from an alamo ring, etc.
*
* @doc.test Basic application from a squared set/circle.
* js> importPackage(net.cscott.sdr.calls);
* js> importPackage(net.cscott.sdr.calls.ast);
* js> ds = new DanceState(new DanceProgram(Program.BASIC), Formation.SQUARED_SET); undefined;
* js> ds.currentFormation().toStringDiagram("|");
* | 3Gv 3Bv
* |
* |4B> 2G<
* |
* |4G> 2B<
* |
* | 1B^ 1G^
* js> comp = AstNode.valueOf("(Seq (Apply '_circle adjust))");
* (Seq (Apply '_circle adjust))
* js> new Evaluator.Standard(comp).evaluateAll(ds);
* js> Breather.breathe(ds.currentFormation()).toStringDiagram("|");
* | 3GQ 3BL
* |
* |4BQ 2GL
* |
* |
* |
* |4G7 2B`
* |
* | 1B7 1G`
* js> new Evaluator.Standard(comp).evaluateAll(ds);
* js> Breather.breathe(ds.currentFormation()).toStringDiagram("|");
* | 3Gv 3Bv
* |
* |4B> 2G<
* |
* |4G> 2B<
* |
* | 1B^ 1G^
* @doc.test Works from non-squared O spots as well
* js> importPackage(net.cscott.sdr.calls);
* js> importPackage(net.cscott.sdr.calls.ast);
* js> ds = new DanceState(new DanceProgram(Program.BASIC), Formation.SQUARED_SET); undefined;
* js> comp = AstNode.valueOf("(Seq (Apply 'face out) (Apply '_circle adjust))");
* (Seq (Apply 'face out) (Apply '_circle adjust))
* js> new Evaluator.Standard(comp).evaluateAll(ds);
* js> Breather.breathe(ds.currentFormation()).toStringDiagram("|");
* | 3GL 3BQ
* |
* |4B7 2G`
* |
* |
* |
* |4GQ 2BL
* |
* | 1B` 1G7
*/
public static final Call _CIRCLE_ADJUST = new BasicCall("_circle adjust") {
@Override
public int getMinNumberOfArguments() { return 0; }
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
return new Evaluator() {
@Override
public Evaluator evaluate(DanceState ds) {
Formation f = ds.currentFormation();
/*
* 0 1
* 2 3
* 4 5
* 6 7
*/
// moving one spot CW
int[] rOrder = new int[] { 1, 3, 0, 5, 2, 7, 4, 6 };
// some positions have to turn a corner
boolean[] rCorner= new boolean[]{ false, true, true, false,
false, true, true, false};
// match the O spots to get normalized formation
FormationMatch fm = MatcherList.O_SPOTS.match(f);
assert fm.meta.dancers().size() == 1;
Dancer metaD = fm.meta.dancers().iterator().next();
TaggedFormation from = fm.matches.get(metaD);
List<Dancer> sortedDancers = from.sortedDancers();
assert sortedDancers.size() == rOrder.length;
// the meta dancer is going to get an extra 1/8 rotation
Position mP = fm.meta.location(metaD)
.turn(Fraction.valueOf(-1,8), false);
ExactRotation mR = (ExactRotation) mP.facing;
// now map every dancer to their new rotated formation
for (int i=0 ; i < sortedDancers.size() ; i++) {
Dancer d = sortedDancers.get(i);
Position fP = from.location(d);
// base position rotates one spot CW
Position tP = from.location
(sortedDancers.get(rOrder[i]));
tP = fP.relocate(tP.x, tP.y, fP.facing);
// some dancers need to have facing dir turn the corner
if (rCorner[i])
tP = tP.relocate
(tP.x, tP.y, tP.facing.add(Fraction.ONE_QUARTER));
// rotate whole formation 1/8
tP = tP.rotateAroundOrigin(mR);
// make a dancer path
DancerPath dp = new DancerPath
(f.location(d), tP, Fraction.ONE, null);
ds.add(d, dp);
}
return null;
}
};
}
};
/** Used for 'scramble home' call. */
public static final Call _SCRAMBLE_HOME = new BasicCall("_scramble home") {
@Override
public int getMinNumberOfArguments() { return 0; }
@Override
public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
return new Evaluator() {
@Override
public Evaluator evaluate(DanceState ds) {
Formation currentFormation = ds.currentFormation();
for (Dancer d : currentFormation.dancers()) {
if (!(d instanceof StandardDancer)) continue;
StandardDancer sd = (StandardDancer) d;
Position current = currentFormation.location(sd);
Position target = targetFormation.location(sd);
Fraction time = Fraction.ZERO;
DancerPath dp;
// roll if needed to face w/in 1/4 of proper direction.
ExactRotation curR = (ExactRotation) current.facing;
ExactRotation tarR = (ExactRotation) target.facing;
Fraction sweep = curR.minSweep(tarR);
if (sweep.abs().compareTo(Fraction.ONE_QUARTER) > 0) {
dp = rollToTarget(current, target);
ds.add(sd, dp);
current = dp.to;
curR = (ExactRotation) current.facing;
time = time.add(dp.time);
}
// odd special case: sometimes the 1/4-off rotations
// leaves the dancer initially walking *backwards*
// turn 1/4 more if necessary to prevent that.
dp = new DancerPath(current, target, time, null);
Point initialTangent = dp.tangentStart();
- ExactRotation initialDir = ExactRotation.fromXY
- (initialTangent.x, initialTangent.y);
- sweep = curR.minSweep(initialDir);
- if (sweep.abs().compareTo(Fraction.ONE_QUARTER) > 0) {
- dp = rollToTarget(current, target);
- ds.add(sd, dp);
- current = dp.to;
- time = time.add(dp.time);
+ if (!Point.ZERO.equals(initialTangent)) {
+ ExactRotation initialDir = ExactRotation.fromXY
+ (initialTangent.x, initialTangent.y);
+ sweep = curR.minSweep(initialDir);
+ if (sweep.abs().compareTo(Fraction.ONE_QUARTER)>0) {
+ dp = rollToTarget(current, target);
+ ds.add(sd, dp);
+ current = dp.to;
+ time = time.add(dp.time);
+ }
}
// now make a DancerPath for the rest of the distance
// travel speed is 1 unit/beat, so estimate appropriate
// path time based on distance to travel
Fraction dist2 = target.x.subtract(current.x).pow(2);
dist2 = dist2.add(target.y.subtract(current.y).pow(2));
double dist = Math.sqrt(dist2.doubleValue());
if (false)
time = Fraction.valueOf(Math.ceil(dist));
else {
// XXX using real times screws up breathing. Use fixed
// time for now.
time = Fraction.THREE.subtract(time);
}
dp = new DancerPath(current, target, time, null);
ds.add(sd, dp);
}
return null;
}
private DancerPath rollToTarget(Position current, Position target) {
ExactRotation curR = (ExactRotation) current.facing;
ExactRotation tarR = (ExactRotation) target.facing;
Fraction sweep = curR.minSweep(tarR);
// can't rotate more than 1/4 in each step.
if (sweep.compareTo(Fraction.ONE_QUARTER) > 0)
sweep = Fraction.ONE_QUARTER;
if (sweep.compareTo(Fraction.mONE_QUARTER) < 0)
sweep = Fraction.mONE_QUARTER;
Position newPos = current.turn(sweep, false);
return new DancerPath(current, newPos, Fraction.ONE, null);
}
};
}
final Formation targetFormation =
FormationList.STATIC_SQUARE_FACING_OUT.mapStd
(COUPLE_3_BOY, COUPLE_3_GIRL, COUPLE_4_GIRL, COUPLE_2_BOY);
};
}
| true | true | public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
return new Evaluator() {
@Override
public Evaluator evaluate(DanceState ds) {
Formation currentFormation = ds.currentFormation();
for (Dancer d : currentFormation.dancers()) {
if (!(d instanceof StandardDancer)) continue;
StandardDancer sd = (StandardDancer) d;
Position current = currentFormation.location(sd);
Position target = targetFormation.location(sd);
Fraction time = Fraction.ZERO;
DancerPath dp;
// roll if needed to face w/in 1/4 of proper direction.
ExactRotation curR = (ExactRotation) current.facing;
ExactRotation tarR = (ExactRotation) target.facing;
Fraction sweep = curR.minSweep(tarR);
if (sweep.abs().compareTo(Fraction.ONE_QUARTER) > 0) {
dp = rollToTarget(current, target);
ds.add(sd, dp);
current = dp.to;
curR = (ExactRotation) current.facing;
time = time.add(dp.time);
}
// odd special case: sometimes the 1/4-off rotations
// leaves the dancer initially walking *backwards*
// turn 1/4 more if necessary to prevent that.
dp = new DancerPath(current, target, time, null);
Point initialTangent = dp.tangentStart();
ExactRotation initialDir = ExactRotation.fromXY
(initialTangent.x, initialTangent.y);
sweep = curR.minSweep(initialDir);
if (sweep.abs().compareTo(Fraction.ONE_QUARTER) > 0) {
dp = rollToTarget(current, target);
ds.add(sd, dp);
current = dp.to;
time = time.add(dp.time);
}
// now make a DancerPath for the rest of the distance
// travel speed is 1 unit/beat, so estimate appropriate
// path time based on distance to travel
Fraction dist2 = target.x.subtract(current.x).pow(2);
dist2 = dist2.add(target.y.subtract(current.y).pow(2));
double dist = Math.sqrt(dist2.doubleValue());
if (false)
time = Fraction.valueOf(Math.ceil(dist));
else {
// XXX using real times screws up breathing. Use fixed
// time for now.
time = Fraction.THREE.subtract(time);
}
dp = new DancerPath(current, target, time, null);
ds.add(sd, dp);
}
return null;
}
private DancerPath rollToTarget(Position current, Position target) {
ExactRotation curR = (ExactRotation) current.facing;
ExactRotation tarR = (ExactRotation) target.facing;
Fraction sweep = curR.minSweep(tarR);
// can't rotate more than 1/4 in each step.
if (sweep.compareTo(Fraction.ONE_QUARTER) > 0)
sweep = Fraction.ONE_QUARTER;
if (sweep.compareTo(Fraction.mONE_QUARTER) < 0)
sweep = Fraction.mONE_QUARTER;
Position newPos = current.turn(sweep, false);
return new DancerPath(current, newPos, Fraction.ONE, null);
}
};
}
| public Evaluator getEvaluator(DanceState ds, List<Expr> args)
throws EvaluationException {
return new Evaluator() {
@Override
public Evaluator evaluate(DanceState ds) {
Formation currentFormation = ds.currentFormation();
for (Dancer d : currentFormation.dancers()) {
if (!(d instanceof StandardDancer)) continue;
StandardDancer sd = (StandardDancer) d;
Position current = currentFormation.location(sd);
Position target = targetFormation.location(sd);
Fraction time = Fraction.ZERO;
DancerPath dp;
// roll if needed to face w/in 1/4 of proper direction.
ExactRotation curR = (ExactRotation) current.facing;
ExactRotation tarR = (ExactRotation) target.facing;
Fraction sweep = curR.minSweep(tarR);
if (sweep.abs().compareTo(Fraction.ONE_QUARTER) > 0) {
dp = rollToTarget(current, target);
ds.add(sd, dp);
current = dp.to;
curR = (ExactRotation) current.facing;
time = time.add(dp.time);
}
// odd special case: sometimes the 1/4-off rotations
// leaves the dancer initially walking *backwards*
// turn 1/4 more if necessary to prevent that.
dp = new DancerPath(current, target, time, null);
Point initialTangent = dp.tangentStart();
if (!Point.ZERO.equals(initialTangent)) {
ExactRotation initialDir = ExactRotation.fromXY
(initialTangent.x, initialTangent.y);
sweep = curR.minSweep(initialDir);
if (sweep.abs().compareTo(Fraction.ONE_QUARTER)>0) {
dp = rollToTarget(current, target);
ds.add(sd, dp);
current = dp.to;
time = time.add(dp.time);
}
}
// now make a DancerPath for the rest of the distance
// travel speed is 1 unit/beat, so estimate appropriate
// path time based on distance to travel
Fraction dist2 = target.x.subtract(current.x).pow(2);
dist2 = dist2.add(target.y.subtract(current.y).pow(2));
double dist = Math.sqrt(dist2.doubleValue());
if (false)
time = Fraction.valueOf(Math.ceil(dist));
else {
// XXX using real times screws up breathing. Use fixed
// time for now.
time = Fraction.THREE.subtract(time);
}
dp = new DancerPath(current, target, time, null);
ds.add(sd, dp);
}
return null;
}
private DancerPath rollToTarget(Position current, Position target) {
ExactRotation curR = (ExactRotation) current.facing;
ExactRotation tarR = (ExactRotation) target.facing;
Fraction sweep = curR.minSweep(tarR);
// can't rotate more than 1/4 in each step.
if (sweep.compareTo(Fraction.ONE_QUARTER) > 0)
sweep = Fraction.ONE_QUARTER;
if (sweep.compareTo(Fraction.mONE_QUARTER) < 0)
sweep = Fraction.mONE_QUARTER;
Position newPos = current.turn(sweep, false);
return new DancerPath(current, newPos, Fraction.ONE, null);
}
};
}
|
diff --git a/core/src/main/java/com/edu/webapp/action/SignupAction.java b/core/src/main/java/com/edu/webapp/action/SignupAction.java
index 333d067..9654a6a 100644
--- a/core/src/main/java/com/edu/webapp/action/SignupAction.java
+++ b/core/src/main/java/com/edu/webapp/action/SignupAction.java
@@ -1,115 +1,116 @@
package com.edu.webapp.action;
import org.apache.struts2.ServletActionContext;
import com.edu.Constants;
import com.edu.model.User;
import com.edu.service.UserExistsException;
import com.edu.webapp.util.RequestUtil;
import org.springframework.mail.MailException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* Action to allow new users to sign up.
*/
public class SignupAction extends BaseAction {
private static final long serialVersionUID = 6558317334878272308L;
private User user;
private String cancel;
public void setCancel(String cancel) {
this.cancel = cancel;
}
public void setUser(User user) {
this.user = user;
}
/**
* Return an instance of the user - to display when validation errors occur
* @return a populated user
*/
public User getUser() {
return user;
}
/**
* When method=GET, "input" is returned. Otherwise, "success" is returned.
* @return cancel, input or success
*/
public String execute() {
if (cancel != null) {
return CANCEL;
}
if (ServletActionContext.getRequest().getMethod().equals("GET")) {
return INPUT;
}
return SUCCESS;
}
/**
* Returns "input"
* @return "input" by default
*/
public String doDefault() {
return INPUT;
}
/**
* Save the user, encrypting their passwords if necessary
* @return success when good things happen
* @throws Exception when bad things happen
*/
public String save() throws Exception {
user.setEnabled(true);
// Set the default user role on this new user
- user.addRole(roleManager.getRole(Constants.USER_ROLE));
+ // TODO ignore the capability for now, grant admin role to all users
+ user.addRole(roleManager.getRole(Constants.ADMIN_ROLE));
try {
user = userManager.saveUser(user);
} catch (AccessDeniedException ade) {
// thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
log.warn(ade.getMessage());
getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (UserExistsException e) {
log.warn(e.getMessage());
List<Object> args = new ArrayList<Object>();
args.add(user.getUsername());
args.add(user.getEmail());
addActionError(getText("errors.existing.user", args));
// redisplay the unencrypted passwords
user.setPassword(user.getConfirmPassword());
return INPUT;
}
saveMessage(getText("user.registered"));
getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);
// log user in automatically
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
auth.setDetails(user);
SecurityContextHolder.getContext().setAuthentication(auth);
// Send an account information e-mail
mailMessage.setSubject(getText("signup.email.subject"));
try {
sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
} catch (MailException me) {
addActionError(me.getMostSpecificCause().getMessage());
}
return SUCCESS;
}
}
| true | true | public String save() throws Exception {
user.setEnabled(true);
// Set the default user role on this new user
user.addRole(roleManager.getRole(Constants.USER_ROLE));
try {
user = userManager.saveUser(user);
} catch (AccessDeniedException ade) {
// thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
log.warn(ade.getMessage());
getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (UserExistsException e) {
log.warn(e.getMessage());
List<Object> args = new ArrayList<Object>();
args.add(user.getUsername());
args.add(user.getEmail());
addActionError(getText("errors.existing.user", args));
// redisplay the unencrypted passwords
user.setPassword(user.getConfirmPassword());
return INPUT;
}
saveMessage(getText("user.registered"));
getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);
// log user in automatically
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
auth.setDetails(user);
SecurityContextHolder.getContext().setAuthentication(auth);
// Send an account information e-mail
mailMessage.setSubject(getText("signup.email.subject"));
try {
sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
} catch (MailException me) {
addActionError(me.getMostSpecificCause().getMessage());
}
return SUCCESS;
}
| public String save() throws Exception {
user.setEnabled(true);
// Set the default user role on this new user
// TODO ignore the capability for now, grant admin role to all users
user.addRole(roleManager.getRole(Constants.ADMIN_ROLE));
try {
user = userManager.saveUser(user);
} catch (AccessDeniedException ade) {
// thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
log.warn(ade.getMessage());
getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (UserExistsException e) {
log.warn(e.getMessage());
List<Object> args = new ArrayList<Object>();
args.add(user.getUsername());
args.add(user.getEmail());
addActionError(getText("errors.existing.user", args));
// redisplay the unencrypted passwords
user.setPassword(user.getConfirmPassword());
return INPUT;
}
saveMessage(getText("user.registered"));
getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);
// log user in automatically
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
auth.setDetails(user);
SecurityContextHolder.getContext().setAuthentication(auth);
// Send an account information e-mail
mailMessage.setSubject(getText("signup.email.subject"));
try {
sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
} catch (MailException me) {
addActionError(me.getMostSpecificCause().getMessage());
}
return SUCCESS;
}
|
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JsfJbide2362Test.java b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JsfJbide2362Test.java
index be18a02c0..9def64c31 100644
--- a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JsfJbide2362Test.java
+++ b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JsfJbide2362Test.java
@@ -1,206 +1,205 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jsf.vpe.jsf.test.jbide;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
import org.jboss.tools.jsf.vpe.jsf.test.JsfAllTests;
import org.jboss.tools.jst.jsp.jspeditor.JSPMultiPageEditor;
import org.jboss.tools.vpe.base.test.TestUtil;
import org.jboss.tools.vpe.base.test.VpeTest;
import org.jboss.tools.vpe.editor.VpeController;
import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
import org.jboss.tools.vpe.editor.mapping.VpeNodeMapping;
import org.jboss.tools.vpe.editor.util.SelectionUtil;
import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author sdzmitrovich
*
* http://jira.jboss.com/jira/browse/JBIDE-2362
*
*/
public class JsfJbide2362Test extends VpeTest {
private static final String SELECTION_PAGE_NAME = "JBIDE/2362/selection.jsp"; //$NON-NLS-1$
private static final String EDITING_PAGE_NAME = "JBIDE/2362/editing.jsp"; //$NON-NLS-1$
private static final List<String> ELEMENTS;
static {
ELEMENTS = new ArrayList<String>();
ELEMENTS.add("h:outputText"); //$NON-NLS-1$
ELEMENTS.add("h:outputFormat"); //$NON-NLS-1$
ELEMENTS.add("h:outputLabel"); //$NON-NLS-1$
ELEMENTS.add("h:outputLink"); //$NON-NLS-1$
ELEMENTS.add("h:inputText"); //$NON-NLS-1$
ELEMENTS.add("h:inputTextarea"); //$NON-NLS-1$
ELEMENTS.add("h:inputSecret"); //$NON-NLS-1$
}
public JsfJbide2362Test(String name) {
super(name);
}
/**
* It is simple selection test. We set cursor for each source node ( from
* VpeDomMapping). Then we compare visual nodes which was selected and which
* was associated with current source node.
*
* @throws Throwable
*/
public void testSimpleSourceSelection() throws Throwable {
TestUtil.waitForJobs();
// set exception
setException(null);
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(SELECTION_PAGE_NAME,
JsfAllTests.IMPORT_PROJECT_NAME);
IEditorInput input = new FileEditorInput(file);
// open and get editor
JSPMultiPageEditor part = openEditor(input);
TestUtil.getVpeController(part);
checkSourceSelection(part);
// check exception
if (getException() != null) {
throw getException();
}
}
/**
* This test checks selection after editing of source. If selection is not
* lost then test pass.
*
* @throws Throwable
*/
public void testEditingSourceSelection() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(EDITING_PAGE_NAME,
JsfAllTests.IMPORT_PROJECT_NAME);
IEditorInput input = new FileEditorInput(file);
// open and get editor
JSPMultiPageEditor part = openEditor(input);
// get controller
VpeController controller = TestUtil.getVpeController(part);
assertNotNull(controller);
// get dommapping
VpeDomMapping domMapping = controller.getDomMapping();
assertNotNull(domMapping);
// get source map
Map<Node, VpeNodeMapping> sourceMap = domMapping.getSourceMap();
assertNotNull(sourceMap);
// get collection of VpeNodeMapping
Collection<VpeNodeMapping> mappings = sourceMap.values();
assertNotNull(mappings);
// get editor control
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
assertNotNull(styledText);
// get xulrunner editor
XulRunnerEditor xulRunnerEditor = controller.getXulRunnerEditor();
assertNotNull(xulRunnerEditor);
IStructuredModel model = null;
IDOMDocument document =null;
try {
model = StructuredModelManager.getModelManager()
.getExistingModelForRead(controller.getSourceEditor().getTextViewer().getDocument());
document = ((IDOMModel)model).getDocument();
for (String tag : ELEMENTS) {
NodeList tagList = document.getElementsByTagName(tag);
if (tagList.getLength() > 0) {
Node node = tagList.item(0);
SelectionUtil.setSourceSelection(controller.getPageContext(),
node, 1, 0);
assertEquals(domMapping.getNearNodeMapping(node)
.getVisualNode(), xulRunnerEditor.getSelectedElement());
String insertedString = null;
int offset;
if (node.getNodeType() == node.ELEMENT_NODE) {
offset = ((IDOMElement) node).getStartEndOffset() - 1;
insertedString = " value=\"x\" "; //$NON-NLS-1$
} else {
offset = ((IDOMNode) node).getStartOffset();
insertedString = "someText"; //$NON-NLS-1$
}
for (int j = 0; j < insertedString.length(); j++) {
styledText.setCaretOffset(offset + j);
styledText.insert(String.valueOf(insertedString.charAt(j)));
- TestUtil.delay();
}
TestUtil.delay(VpeController.DEFAULT_UPDATE_DELAY_TIME * 2); // ensure that vpe is started to update
- TestUtil.waitForJobs();
+ TestUtil.waitForIdle();
assertNotNull(xulRunnerEditor.getSelectedElement());
}
}
} finally {
if(model!=null) {
model.releaseFromRead();
}
}
// check exception
if (getException() != null) {
throw getException();
}
}
}
| false | true | public void testEditingSourceSelection() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(EDITING_PAGE_NAME,
JsfAllTests.IMPORT_PROJECT_NAME);
IEditorInput input = new FileEditorInput(file);
// open and get editor
JSPMultiPageEditor part = openEditor(input);
// get controller
VpeController controller = TestUtil.getVpeController(part);
assertNotNull(controller);
// get dommapping
VpeDomMapping domMapping = controller.getDomMapping();
assertNotNull(domMapping);
// get source map
Map<Node, VpeNodeMapping> sourceMap = domMapping.getSourceMap();
assertNotNull(sourceMap);
// get collection of VpeNodeMapping
Collection<VpeNodeMapping> mappings = sourceMap.values();
assertNotNull(mappings);
// get editor control
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
assertNotNull(styledText);
// get xulrunner editor
XulRunnerEditor xulRunnerEditor = controller.getXulRunnerEditor();
assertNotNull(xulRunnerEditor);
IStructuredModel model = null;
IDOMDocument document =null;
try {
model = StructuredModelManager.getModelManager()
.getExistingModelForRead(controller.getSourceEditor().getTextViewer().getDocument());
document = ((IDOMModel)model).getDocument();
for (String tag : ELEMENTS) {
NodeList tagList = document.getElementsByTagName(tag);
if (tagList.getLength() > 0) {
Node node = tagList.item(0);
SelectionUtil.setSourceSelection(controller.getPageContext(),
node, 1, 0);
assertEquals(domMapping.getNearNodeMapping(node)
.getVisualNode(), xulRunnerEditor.getSelectedElement());
String insertedString = null;
int offset;
if (node.getNodeType() == node.ELEMENT_NODE) {
offset = ((IDOMElement) node).getStartEndOffset() - 1;
insertedString = " value=\"x\" "; //$NON-NLS-1$
} else {
offset = ((IDOMNode) node).getStartOffset();
insertedString = "someText"; //$NON-NLS-1$
}
for (int j = 0; j < insertedString.length(); j++) {
styledText.setCaretOffset(offset + j);
styledText.insert(String.valueOf(insertedString.charAt(j)));
TestUtil.delay();
}
TestUtil.delay(VpeController.DEFAULT_UPDATE_DELAY_TIME * 2); // ensure that vpe is started to update
TestUtil.waitForJobs();
assertNotNull(xulRunnerEditor.getSelectedElement());
}
}
} finally {
if(model!=null) {
model.releaseFromRead();
}
}
// check exception
if (getException() != null) {
throw getException();
}
}
| public void testEditingSourceSelection() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(EDITING_PAGE_NAME,
JsfAllTests.IMPORT_PROJECT_NAME);
IEditorInput input = new FileEditorInput(file);
// open and get editor
JSPMultiPageEditor part = openEditor(input);
// get controller
VpeController controller = TestUtil.getVpeController(part);
assertNotNull(controller);
// get dommapping
VpeDomMapping domMapping = controller.getDomMapping();
assertNotNull(domMapping);
// get source map
Map<Node, VpeNodeMapping> sourceMap = domMapping.getSourceMap();
assertNotNull(sourceMap);
// get collection of VpeNodeMapping
Collection<VpeNodeMapping> mappings = sourceMap.values();
assertNotNull(mappings);
// get editor control
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
assertNotNull(styledText);
// get xulrunner editor
XulRunnerEditor xulRunnerEditor = controller.getXulRunnerEditor();
assertNotNull(xulRunnerEditor);
IStructuredModel model = null;
IDOMDocument document =null;
try {
model = StructuredModelManager.getModelManager()
.getExistingModelForRead(controller.getSourceEditor().getTextViewer().getDocument());
document = ((IDOMModel)model).getDocument();
for (String tag : ELEMENTS) {
NodeList tagList = document.getElementsByTagName(tag);
if (tagList.getLength() > 0) {
Node node = tagList.item(0);
SelectionUtil.setSourceSelection(controller.getPageContext(),
node, 1, 0);
assertEquals(domMapping.getNearNodeMapping(node)
.getVisualNode(), xulRunnerEditor.getSelectedElement());
String insertedString = null;
int offset;
if (node.getNodeType() == node.ELEMENT_NODE) {
offset = ((IDOMElement) node).getStartEndOffset() - 1;
insertedString = " value=\"x\" "; //$NON-NLS-1$
} else {
offset = ((IDOMNode) node).getStartOffset();
insertedString = "someText"; //$NON-NLS-1$
}
for (int j = 0; j < insertedString.length(); j++) {
styledText.setCaretOffset(offset + j);
styledText.insert(String.valueOf(insertedString.charAt(j)));
}
TestUtil.delay(VpeController.DEFAULT_UPDATE_DELAY_TIME * 2); // ensure that vpe is started to update
TestUtil.waitForIdle();
assertNotNull(xulRunnerEditor.getSelectedElement());
}
}
} finally {
if(model!=null) {
model.releaseFromRead();
}
}
// check exception
if (getException() != null) {
throw getException();
}
}
|
diff --git a/publicMAIN/src/org/publicmain/common/Config.java b/publicMAIN/src/org/publicmain/common/Config.java
index 52f8cf4..8ffa2ae 100644
--- a/publicMAIN/src/org/publicmain/common/Config.java
+++ b/publicMAIN/src/org/publicmain/common/Config.java
@@ -1,297 +1,298 @@
package org.publicmain.common;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.Properties;
import org.publicmain.sql.DatabaseEngine;
/**
* Diese Klasse enth�lt wichtige Konfigurationsdaten zur Anwendung.
*
* @author ATRM
*
*/
public class Config {
public static Color BLUE = new Color(25,169,241);
public static Color BLUE2 = new Color(9,112,164);
public static Color BLUE3 = new Color(5,64,94);
public static Color ORANGE = new Color(255,133,18);
public static Color YELLOW = new Color(229,195,0);
public static Color GREEN= new Color(51,144,124);
public static Color GREEN2= new Color(123,195,165);
private static final String APPNAME = (System.getProperty("appname")==null)?"publicMAIN":System.getProperty("appname");
private static final int CURRENTVERSION = 5;
private static final int MINVERSION = 5;
private static final String APPDATA=System.getenv("APPDATA")+File.separator+"publicMAIN"+File.separator;
private static final String JARLOCATION=Config.class.getProtectionDomain().getCodeSource().getLocation().getFile();
private static final String lock_file_name = APPNAME+".loc";
private static final String system_conf_name = APPNAME+"_sys.cfg";
private static final String user_conf_name = APPNAME+".cfg";
private static File loc_file = new File(APPDATA,lock_file_name);
private static File system_conf = new File(new File(JARLOCATION).getParentFile(),system_conf_name);
private static File user_conf = new File(APPDATA,user_conf_name);
private static Config me;
private static DatabaseEngine de;
private ConfigData settings;
/**
* Getter welcher die aktuelle Konfiguration zur�ckliefert.
*
* @return
*/
public static synchronized ConfigData getConfig() {
if (me == null) {
me = new Config();
}
return me.settings;
}
public static synchronized ConfigData setConfig(ConfigData newConfig) {
if (me == null) {
me = new Config();
}
return me.settings=newConfig;
}
/**
* Schreibt die Konfiguration auf die Festplatte.
*/
@SuppressWarnings("static-access")
public static synchronized void write() {
if (me == null) {
me = new Config();
}
me.getConfig().setCurrentVersion(CURRENTVERSION);
if (de != null) {
de.writeConfig();
}
me.savetoDisk();
}
/**
* System-Konfiguration schreiben.
*
* @return
*/
public static synchronized boolean writeSystemConfiguration() {
try (FileOutputStream fos = new FileOutputStream(system_conf)) {
getSourceSettings().store(fos, "publicMAIN - SYSTEM - SETTINGS");
LogEngine.log(Config.class,
"System configurations file written to " + system_conf,
LogEngine.INFO);
return true;
} catch (IOException e) {
e.printStackTrace();
LogEngine.log(Config.class, "Could not write system settings: "
+ system_conf + " reason : " + e.getMessage(),
LogEngine.WARNING);
return false;
}
}
/**
* Melde die Datenbank f�r Schreibvorg�nge an der Konfiguration an.
*
* @param databaseengine
*/
public static void registerDatabaseEngine(DatabaseEngine databaseengine) {
de = databaseengine;
}
/**
* Method tries to Lock a file <code>pm.loc</code> in Users
* <code>APPDATA\publicMAIN</code> folder. And returns result as boolen. It
* also adds a shutdown hook to the VM to remove Lock from File if Program
* exits.
*
* @return <code>true</code> if File could be locked <code>false</code> if
* File has already been locked
*/
public static boolean getLock() {
try {
if (!loc_file.getParentFile().exists()) {
loc_file.getParentFile().mkdirs();
}
final RandomAccessFile randomAccessFile = new RandomAccessFile(
loc_file, "rw");
final FileLock fileLock = randomAccessFile.getChannel().tryLock();
if (fileLock != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
fileLock.release();
randomAccessFile.close();
loc_file.delete();
} catch (Exception e) {
LogEngine.log("ShutdownHook",
"Unable to remove lock file: " + loc_file,
LogEngine.ERROR);
}
}
});
return true;
}
} catch (Exception e) {
LogEngine.log("Config", "Unable to create and/or lock file: "
+ loc_file, LogEngine.ERROR);
}
return false;
}
/**
* Standart-Konstruktor f�r die Config-Klasse.
*/
private Config() {
me = this;
settings = new ConfigData(getSourceSettings());
LogEngine.log(
this,
"default settings loaded from source ["
+ ((system_conf.exists()) ? "S" : "0") + "|"
+ ((user_conf.exists()) ? "U" : "0") + "]",
LogEngine.INFO);
// Versuche die System-Einstellungen vom JAR zu �berladen
if (system_conf.canRead()) {
try (FileInputStream in = new FileInputStream(system_conf)) {
ConfigData system = new ConfigData(settings);
system.load(in);
LogEngine.log(this, "system settings loaded from "
+ system_conf, LogEngine.INFO);
this.settings = system;
} catch (IOException e1) {
e1.printStackTrace();
LogEngine.log(this, "error while loading system settings from "
+ system_conf, LogEngine.ERROR);
}
}
ConfigData user = new ConfigData(settings);
// Versuche die Benutzer-Einstellungen aus AppData zu �berladen
if (user_conf.canRead()) {
try (FileInputStream in = new FileInputStream(user_conf)) {
user.load(in);
if (user.getCurrentVersion() < MINVERSION) {
settings.setUserID(user.getUserID());
settings.setAlias(user.getAlias());
LogEngine.log(this,
"user settings outdated only userid and alias will be used from "
+ user_conf, LogEngine.INFO);
} else {
settings = user;
}
LogEngine.log(this, "user settings loaded from " + user_conf,
LogEngine.INFO);
} catch (IOException e) {
LogEngine.log(this, "default config could not be read. reason:"
+ e.getMessage(), LogEngine.WARNING);
}
}
+ LogEngine.setVerbosity(settings.getLogVerbosity());
}
/**
* Die Methode liefert die Standart-Einstellungen der Anwendung
*
* @return
*/
private static ConfigData getSourceSettings() {
ConfigData tmp = new ConfigData();
tmp.setCurrentVersion(CURRENTVERSION);
// Netzwerk-Parameter
tmp.setMCGroup("230.223.223.223");
tmp.setMCPort(6789);
tmp.setMCTTL(10);
tmp.setDiscoverTimeout(200);
tmp.setRootClaimTimeout(200);
tmp.setMaxConnections(3);
tmp.setTreeBuildTime(1000);
tmp.setPingInterval(30000);
tmp.setPingEnabled(false);
// Dateitransfer-Einstellungen
tmp.setMaxFileSize(5000000);
tmp.setFileTransferTimeout(120000);
tmp.setFileTransferInfoInterval(30000);
tmp.setDisableFileTransfer(false);
// Standart-Einstellungen der Anwendung
tmp.setLogVerbosity(4);
tmp.setMaxAliasLength(19);
tmp.setMaxGroupLength(19);
tmp.setMaxEingabefeldLength(200);
tmp.setFontFamily("Arial");
tmp.setFontSize(3);
tmp.setNamePattern("((([-_]?)([a-zA-Z0-9öäüÖÄÜßéá♥])+))+([-_])?");
tmp.setNotifyGroup(false);
tmp.setNotifyPrivate(false);
// Lokale mySQL Datenbank-Einstellungen
tmp.setLocalDBVersion(0);
tmp.setLocalDBDatabasename("db_publicMain");
tmp.setLocalDBPort("3306");
tmp.setLocalDBUser("publicMain");
tmp.setLocalDBPw("publicMain");
// daten fuer externen DB-Backup-Server
tmp.setBackupDBDatabasename("db_publicMain_backup");
tmp.setBackupDBPort("3306");
tmp.setBackupDBUser("backupPublicMain");
tmp.setBackupDBPw("backupPublicMain");
return tmp;
}
/**
* Einstellungen in einem Thread als Datei auf die Festplatte speichern.
*/
private void savetoDisk() {
Runnable target = new Runnable() {
public void run() {
try (final FileOutputStream fos = new FileOutputStream(
user_conf)) {
settings.store(fos, "publicMAIN - USER - SETTINGS");
LogEngine.log(Config.this, "User settings written to "
+ user_conf, LogEngine.WARNING);
} catch (IOException e1) {
LogEngine.log(Config.this,
"Could not write user settings: " + user_conf
+ " reason : " + e1.getMessage(),
LogEngine.WARNING);
}
}
};
new Thread(target).start();
}
/**
* TODO: Kommentar!
*
* @param tmp
*/
public static void importConfig(Properties tmp) {
ConfigData imported = new ConfigData(getConfig());
for (Object key : tmp.keySet()) {
if (tmp.get(key) != null) {
imported.put(key, tmp.get(key));
}
}
setConfig(imported);
}
/**
* TODO: Kommentar!
*
* @return
*/
public static Properties getNonDefault() {
Properties rueck = new Properties();
ConfigData defaults = getSourceSettings();
ConfigData current = getConfig();
for (Object key : current.keySet()) {
if (!current.get(key).equals(defaults.get(key)))
rueck.put(key, current.get(key));
}
return rueck;
}
}
| true | true | private Config() {
me = this;
settings = new ConfigData(getSourceSettings());
LogEngine.log(
this,
"default settings loaded from source ["
+ ((system_conf.exists()) ? "S" : "0") + "|"
+ ((user_conf.exists()) ? "U" : "0") + "]",
LogEngine.INFO);
// Versuche die System-Einstellungen vom JAR zu �berladen
if (system_conf.canRead()) {
try (FileInputStream in = new FileInputStream(system_conf)) {
ConfigData system = new ConfigData(settings);
system.load(in);
LogEngine.log(this, "system settings loaded from "
+ system_conf, LogEngine.INFO);
this.settings = system;
} catch (IOException e1) {
e1.printStackTrace();
LogEngine.log(this, "error while loading system settings from "
+ system_conf, LogEngine.ERROR);
}
}
ConfigData user = new ConfigData(settings);
// Versuche die Benutzer-Einstellungen aus AppData zu �berladen
if (user_conf.canRead()) {
try (FileInputStream in = new FileInputStream(user_conf)) {
user.load(in);
if (user.getCurrentVersion() < MINVERSION) {
settings.setUserID(user.getUserID());
settings.setAlias(user.getAlias());
LogEngine.log(this,
"user settings outdated only userid and alias will be used from "
+ user_conf, LogEngine.INFO);
} else {
settings = user;
}
LogEngine.log(this, "user settings loaded from " + user_conf,
LogEngine.INFO);
} catch (IOException e) {
LogEngine.log(this, "default config could not be read. reason:"
+ e.getMessage(), LogEngine.WARNING);
}
}
}
| private Config() {
me = this;
settings = new ConfigData(getSourceSettings());
LogEngine.log(
this,
"default settings loaded from source ["
+ ((system_conf.exists()) ? "S" : "0") + "|"
+ ((user_conf.exists()) ? "U" : "0") + "]",
LogEngine.INFO);
// Versuche die System-Einstellungen vom JAR zu �berladen
if (system_conf.canRead()) {
try (FileInputStream in = new FileInputStream(system_conf)) {
ConfigData system = new ConfigData(settings);
system.load(in);
LogEngine.log(this, "system settings loaded from "
+ system_conf, LogEngine.INFO);
this.settings = system;
} catch (IOException e1) {
e1.printStackTrace();
LogEngine.log(this, "error while loading system settings from "
+ system_conf, LogEngine.ERROR);
}
}
ConfigData user = new ConfigData(settings);
// Versuche die Benutzer-Einstellungen aus AppData zu �berladen
if (user_conf.canRead()) {
try (FileInputStream in = new FileInputStream(user_conf)) {
user.load(in);
if (user.getCurrentVersion() < MINVERSION) {
settings.setUserID(user.getUserID());
settings.setAlias(user.getAlias());
LogEngine.log(this,
"user settings outdated only userid and alias will be used from "
+ user_conf, LogEngine.INFO);
} else {
settings = user;
}
LogEngine.log(this, "user settings loaded from " + user_conf,
LogEngine.INFO);
} catch (IOException e) {
LogEngine.log(this, "default config could not be read. reason:"
+ e.getMessage(), LogEngine.WARNING);
}
}
LogEngine.setVerbosity(settings.getLogVerbosity());
}
|
diff --git a/src/com/oresomecraft/maps/arcade/games/BombDropMap.java b/src/com/oresomecraft/maps/arcade/games/BombDropMap.java
index 4b006a2..c92e0d7 100644
--- a/src/com/oresomecraft/maps/arcade/games/BombDropMap.java
+++ b/src/com/oresomecraft/maps/arcade/games/BombDropMap.java
@@ -1,230 +1,230 @@
package com.oresomecraft.maps.arcade.games;
import com.oresomecraft.OresomeBattles.api.events.BattleEndEvent;
import com.oresomecraft.maps.MapsPlugin;
import com.oresomecraft.maps.arcade.ArcadeMap;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.potion.*;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public abstract class BombDropMap extends ArcadeMap {
public Location loc1;
public Location loc2;
static List<Integer> bombs = new ArrayList<Integer>();
@EventHandler
public void onEnd(BattleEndEvent event) {
loc1 = null;
loc2 = null;
}
public void bombs() {
new BukkitRunnable() {
public void run() {
if (!getArena().equals(name)) {
bombs.clear();
this.cancel();
return;
}
Random rdom = new Random();
Location loc = getBlocks().get(rdom.nextInt(getBlocks().size())).getLocation();
bombs.add(1);
List<Class> type = new ArrayList<Class>();
type.add(Creeper.class);
if (bombs.size() > 20) type.add(Cow.class);
if (bombs.size() > 30) type.add(Pig.class);
if (bombs.size() > 40) type.add(Sheep.class);
if (bombs.size() > 50) type.add(Wolf.class);
if (bombs.size() > 55) {
type.add(Spider.class);
}
if (bombs.size() > 60) {
type.add(Silverfish.class);
type.add(CaveSpider.class);
}
if (bombs.size() > 65) {
type.add(Villager.class);
}
if (bombs.size() > 70) {
type.add(MushroomCow.class);
type.add(Slime.class);
}
if (bombs.size() > 80) type.add(Skeleton.class);
Class T = type.get(rdom.nextInt(type.size()));
loc.getWorld().spawn(loc, T);
}
}.runTaskTimer(MapsPlugin.getInstance(), 20, 20);
}
@EventHandler
public void onDrop(EntityDamageEvent event) {
if (!event.getEntity().getWorld().getName().equals(name)) return;
if (event.getEntity() instanceof Player) return;
final Entity e = event.getEntity();
EntityType et = e.getType();
final Location loc = e.getLocation();
if (event.getCause() == EntityDamageEvent.DamageCause.FALL) {
if (et == EntityType.CREEPER) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 4);
}
}, 30);
} else if (et == EntityType.COW) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.PIG) {
Random rdom = new Random();
loc.getWorld().spawnEntity(loc, EntityType.PIG_ZOMBIE).setVelocity(new Vector(rdom.nextDouble(), 3, rdom.nextDouble()));
} else if (et == EntityType.PIG_ZOMBIE) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 6);
}
}, 30);
} else if (et == EntityType.SHEEP) {
Random rdom = new Random();
for (int i = 0; i <= 10; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.WOOL, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 2, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.SQUID) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.WATER, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
} else if (et == EntityType.WOLF) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(3, 3, 3);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
- p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5, 1));
+ p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5 * 20, 1));
}
}
} else if (et == EntityType.OCELOT) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(3, 3, 3);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
- p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 5, 1));
+ p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 5 * 20, 1));
}
}
} else if (et == EntityType.SPIDER) {
Random rdom = new Random();
for (int i = 0; i <= 4; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.WEB, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.HORSE) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(10, 10, 10);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
- p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 5, 2));
- p.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20, 2));
+ p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 5 * 20, 2));
+ p.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20 * 20, 2));
}
}
} else if (et == EntityType.SKELETON) {
Random rdom = new Random();
for (int i = 0; i <= 4; i++) {
loc.getWorld().spawnEntity(loc, EntityType.ZOMBIE).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.SILVERFISH) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.MONSTER_EGGS, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 2);
}
}, 30);
} else if (et == EntityType.CAVE_SPIDER) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.SPIDER).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.WITHER_SKULL) {
Random rdom = new Random();
}
if (et == EntityType.ZOMBIE) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().strikeLightning(loc);
}
}, 30);
} else if (et == EntityType.IRON_GOLEM) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.VILLAGER).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.VILLAGER) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.ANVIL, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.MUSHROOM_COW) {
Random rdom = new Random();
for (int i = 0; i <= 5; i++) {
loc.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
}
if (et == EntityType.SLIME) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 6);
}
}, 30);
} else if (et == EntityType.SKELETON) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.LAVA, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
}
}
}
public List<Block> getBlocks() {
List<Block> blocks = new ArrayList<Block>();
if (loc1 == null || loc2 == null) return blocks;
for (int x = (int) Math.min(loc1.getX(), loc2.getX()); x <= (int) Math.max(loc1.getX(), loc2.getX()); x++) {
for (int y = (int) Math.min(loc1.getY(), loc2.getY()); y <= (int) Math.max(loc1.getY(), loc2.getY()); y++) {
for (int z = (int) Math.min(loc1.getZ(), loc2.getZ()); z <= (int) Math.max(loc1.getZ(), loc2.getZ()); z++) {
if (loc1.getWorld().getBlockAt(x, y, z).getType() == Material.AIR) {
blocks.add(loc1.getWorld().getBlockAt(x, y, z));
}
}
}
}
return blocks;
}
}
| false | true | public void onDrop(EntityDamageEvent event) {
if (!event.getEntity().getWorld().getName().equals(name)) return;
if (event.getEntity() instanceof Player) return;
final Entity e = event.getEntity();
EntityType et = e.getType();
final Location loc = e.getLocation();
if (event.getCause() == EntityDamageEvent.DamageCause.FALL) {
if (et == EntityType.CREEPER) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 4);
}
}, 30);
} else if (et == EntityType.COW) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.PIG) {
Random rdom = new Random();
loc.getWorld().spawnEntity(loc, EntityType.PIG_ZOMBIE).setVelocity(new Vector(rdom.nextDouble(), 3, rdom.nextDouble()));
} else if (et == EntityType.PIG_ZOMBIE) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 6);
}
}, 30);
} else if (et == EntityType.SHEEP) {
Random rdom = new Random();
for (int i = 0; i <= 10; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.WOOL, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 2, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.SQUID) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.WATER, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
} else if (et == EntityType.WOLF) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(3, 3, 3);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5, 1));
}
}
} else if (et == EntityType.OCELOT) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(3, 3, 3);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 5, 1));
}
}
} else if (et == EntityType.SPIDER) {
Random rdom = new Random();
for (int i = 0; i <= 4; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.WEB, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.HORSE) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(10, 10, 10);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 5, 2));
p.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20, 2));
}
}
} else if (et == EntityType.SKELETON) {
Random rdom = new Random();
for (int i = 0; i <= 4; i++) {
loc.getWorld().spawnEntity(loc, EntityType.ZOMBIE).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.SILVERFISH) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.MONSTER_EGGS, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 2);
}
}, 30);
} else if (et == EntityType.CAVE_SPIDER) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.SPIDER).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.WITHER_SKULL) {
Random rdom = new Random();
}
if (et == EntityType.ZOMBIE) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().strikeLightning(loc);
}
}, 30);
} else if (et == EntityType.IRON_GOLEM) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.VILLAGER).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.VILLAGER) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.ANVIL, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.MUSHROOM_COW) {
Random rdom = new Random();
for (int i = 0; i <= 5; i++) {
loc.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
}
if (et == EntityType.SLIME) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 6);
}
}, 30);
} else if (et == EntityType.SKELETON) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.LAVA, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
}
}
}
| public void onDrop(EntityDamageEvent event) {
if (!event.getEntity().getWorld().getName().equals(name)) return;
if (event.getEntity() instanceof Player) return;
final Entity e = event.getEntity();
EntityType et = e.getType();
final Location loc = e.getLocation();
if (event.getCause() == EntityDamageEvent.DamageCause.FALL) {
if (et == EntityType.CREEPER) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 4);
}
}, 30);
} else if (et == EntityType.COW) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.PIG) {
Random rdom = new Random();
loc.getWorld().spawnEntity(loc, EntityType.PIG_ZOMBIE).setVelocity(new Vector(rdom.nextDouble(), 3, rdom.nextDouble()));
} else if (et == EntityType.PIG_ZOMBIE) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 6);
}
}, 30);
} else if (et == EntityType.SHEEP) {
Random rdom = new Random();
for (int i = 0; i <= 10; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.WOOL, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 2, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.SQUID) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.WATER, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
} else if (et == EntityType.WOLF) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(3, 3, 3);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5 * 20, 1));
}
}
} else if (et == EntityType.OCELOT) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(3, 3, 3);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 5 * 20, 1));
}
}
} else if (et == EntityType.SPIDER) {
Random rdom = new Random();
for (int i = 0; i <= 4; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.WEB, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.HORSE) {
Random rdom = new Random();
List<Entity> l = e.getNearbyEntities(10, 10, 10);
for (Entity ee : l) {
if (ee instanceof Player) {
Player p = (Player) ee;
p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 5 * 20, 2));
p.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20 * 20, 2));
}
}
} else if (et == EntityType.SKELETON) {
Random rdom = new Random();
for (int i = 0; i <= 4; i++) {
loc.getWorld().spawnEntity(loc, EntityType.ZOMBIE).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.SILVERFISH) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.MONSTER_EGGS, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 2);
}
}, 30);
} else if (et == EntityType.CAVE_SPIDER) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.SPIDER).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.WITHER_SKULL) {
Random rdom = new Random();
}
if (et == EntityType.ZOMBIE) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().strikeLightning(loc);
}
}, 30);
} else if (et == EntityType.IRON_GOLEM) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnEntity(loc, EntityType.VILLAGER).setVelocity(new Vector(rdom.nextDouble() - 0.5, 3, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.VILLAGER) {
Random rdom = new Random();
for (int i = 0; i <= 3; i++) {
loc.getWorld().spawnFallingBlock(loc, Material.ANVIL, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
} else if (et == EntityType.MUSHROOM_COW) {
Random rdom = new Random();
for (int i = 0; i <= 5; i++) {
loc.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1.5, rdom.nextDouble() - 0.5));
}
}
if (et == EntityType.SLIME) {
Bukkit.getScheduler().runTaskLater(MapsPlugin.getInstance(), new Runnable() {
public void run() {
loc.getWorld().createExplosion(loc, (float) 6);
}
}, 30);
} else if (et == EntityType.SKELETON) {
Random rdom = new Random();
loc.getWorld().spawnFallingBlock(loc, Material.LAVA, (byte) 0).setVelocity(new Vector(rdom.nextDouble() - 0.5, 1, rdom.nextDouble() - 0.5));
}
}
}
|
diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
index 3959ed5..73eebcb 100644
--- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
+++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
@@ -1,1263 +1,1248 @@
/**
* Copyright (C) 2009-2012 enStratus Networks Inc
*
* ====================================================================
* 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.dasein.cloud.openstack.nova.os.compute;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudErrorType;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.compute.AbstractVMSupport;
import org.dasein.cloud.compute.Architecture;
import org.dasein.cloud.compute.ImageClass;
import org.dasein.cloud.compute.MachineImage;
import org.dasein.cloud.compute.Platform;
import org.dasein.cloud.compute.VMLaunchOptions;
import org.dasein.cloud.compute.VirtualMachine;
import org.dasein.cloud.compute.VirtualMachineProduct;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.identity.IdentityServices;
import org.dasein.cloud.identity.ShellKeySupport;
import org.dasein.cloud.network.Firewall;
import org.dasein.cloud.network.FirewallSupport;
import org.dasein.cloud.network.IPVersion;
import org.dasein.cloud.network.IpAddress;
import org.dasein.cloud.network.IpAddressSupport;
import org.dasein.cloud.network.NetworkServices;
import org.dasein.cloud.network.RawAddress;
import org.dasein.cloud.network.VLAN;
import org.dasein.cloud.network.VLANSupport;
import org.dasein.cloud.openstack.nova.os.NovaException;
import org.dasein.cloud.openstack.nova.os.NovaMethod;
import org.dasein.cloud.openstack.nova.os.NovaOpenStack;
import org.dasein.cloud.openstack.nova.os.network.NovaNetworkServices;
import org.dasein.cloud.openstack.nova.os.network.Quantum;
import org.dasein.cloud.util.APITrace;
import org.dasein.cloud.util.Cache;
import org.dasein.cloud.util.CacheLevel;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.dasein.util.uom.time.Day;
import org.dasein.util.uom.time.TimePeriod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Implements services supporting interaction with cloud virtual machines.
* @author George Reese ([email protected])
* @version 2012.09 addressed issue with alternate security group lookup in some OpenStack environments (issue #1)
* @version 2013.02 implemented setting kernel/ramdisk image IDs (see issue #40 in dasein-cloud-core)
* @version 2013.02 updated with support for Dasein Cloud 2013.02 model
* @version 2013.02 added support for fetching shell keys (issue #4)
* @since unknown
*/
public class NovaServer extends AbstractVMSupport {
static private final Logger logger = NovaOpenStack.getLogger(NovaServer.class, "std");
static public final String SERVICE = "compute";
NovaServer(NovaOpenStack provider) {
super(provider);
}
@Override
public @Nonnull String getConsoleOutput(@Nonnull String vmId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.getConsoleOutput");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("os-getConsoleOutput", new HashMap<String,Object>());
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
String console = method.postServersForString("/servers", vmId, new JSONObject(json), true);
return (console == null ? "" : console);
}
finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getProduct");
try {
for( VirtualMachineProduct product : listProducts(Architecture.I64) ) {
if( product.getProviderProductId().equals(productId) ) {
return product;
}
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) {
return "server";
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getVirtualMachine");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", vmId, true);
if( ob == null ) {
return null;
}
Iterable<IpAddress> ipv4, ipv6;
Iterable<VLAN> networks;
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipv4 = support.listIpPool(IPVersion.IPV4, false);
ipv6 = support.listIpPool(IPVersion.IPV6, false);
}
else {
ipv4 = ipv6 = Collections.emptyList();
}
VLANSupport vs = services.getVlanSupport();
if( vs != null ) {
networks = vs.listVlans();
}
else {
networks = Collections.emptyList();
}
}
else {
ipv4 = ipv6 = Collections.emptyList();
networks = Collections.emptyList();
}
try {
if( ob.has("server") ) {
JSONObject server = ob.getJSONObject("server");
VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, networks);
if( vm != null ) {
return vm;
}
}
}
catch( JSONException e ) {
logger.error("getVirtualMachine(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers");
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException {
return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.OPTIONAL);
}
@Override
public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException {
IdentityServices services = getProvider().getIdentityServices();
if( services == null ) {
return Requirement.NONE;
}
ShellKeySupport support = services.getShellKeySupport();
if( support == null ) {
return Requirement.NONE;
}
return Requirement.OPTIONAL;
}
@Override
public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException {
NetworkServices services = getProvider().getNetworkServices();
if( services == null ) {
return Requirement.NONE;
}
VLANSupport support = services.getVlanSupport();
if( support == null || !support.isSubscribed() ) {
return Requirement.NONE;
}
return Requirement.OPTIONAL;
}
@Override
public boolean isAPITerminationPreventable() throws CloudException, InternalException {
return false;
}
@Override
public boolean isBasicAnalyticsSupported() throws CloudException, InternalException {
return true;
}
@Override
public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.isSubscribed");
try {
return (getProvider().testContext() != null);
}
finally {
APITrace.end();
}
}
@Override
public boolean isUserDataSupported() throws CloudException, InternalException {
return true;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions options) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.launch");
try {
MachineImage targetImage = getProvider().getComputeServices().getImageSupport().getImage(options.getMachineImageId());
if( targetImage == null ) {
throw new CloudException("No such machine image: " + options.getMachineImageId());
}
HashMap<String,Object> wrapper = new HashMap<String,Object>();
HashMap<String,Object> json = new HashMap<String,Object>();
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
json.put("name", options.getHostName());
if( options.getUserData() != null ) {
try {
json.put("user_data", Base64.encodeBase64String(options.getUserData().getBytes("utf-8")));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
}
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
json.put("imageId", String.valueOf(options.getMachineImageId()));
json.put("flavorId", options.getStandardProductId());
}
else {
if( getProvider().getProviderName().equals("HP") ) {
json.put("imageRef", options.getMachineImageId());
}
else {
json.put("imageRef", ((NovaOpenStack)getProvider()).getComputeServices().getImageSupport().getImageRef(options.getMachineImageId()));
}
json.put("flavorRef", getFlavorRef(options.getStandardProductId()));
}
if( options.getVlanId() != null && ((NovaOpenStack)getProvider()).isRackspace() ) {
ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>();
HashMap<String,Object> vlan = new HashMap<String, Object>();
vlan.put("uuid", options.getVlanId());
vlans.add(vlan);
json.put("networks", vlans);
}
else {
if( options.getVlanId() != null && !((NovaOpenStack)getProvider()).isRackspace() ) {
try {
NovaNetworkServices services = ((NovaOpenStack)getProvider()).getNetworkServices();
if( services != null ) {
Quantum support = services.getVlanSupport();
if( support != null ) {
ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>();
HashMap<String,Object> vlan = new HashMap<String, Object>();
vlan.put("port", support.createPort(options.getVlanId(), options.getHostName()));
vlans.add(vlan);
json.put("networks", vlans);
}
}
}
catch( Throwable ignore ) {
// ignore this error
}
}
}
if( options.getBootstrapKey() != null ) {
json.put("key_name", options.getBootstrapKey());
}
if( options.getFirewallIds().length > 0 ) {
ArrayList<HashMap<String,Object>> firewalls = new ArrayList<HashMap<String,Object>>();
for( String id : options.getFirewallIds() ) {
NetworkServices services = getProvider().getNetworkServices();
Firewall firewall = null;
if( services != null ) {
FirewallSupport support = services.getFirewallSupport();
if( support != null ) {
firewall = support.getFirewall(id);
}
}
if( firewall != null ) {
HashMap<String,Object> fw = new HashMap<String, Object>();
fw.put("name", firewall.getName());
firewalls.add(fw);
}
}
json.put("security_groups", firewalls);
}
if( !targetImage.getPlatform().equals(Platform.UNKNOWN) ) {
options.withMetaData("org.dasein.platform", targetImage.getPlatform().name());
}
options.withMetaData("org.dasein.description", options.getDescription());
json.put("metadata", options.getMetaData());
wrapper.put("server", json);
JSONObject result = method.postServers("/servers", null, new JSONObject(wrapper), true);
if( result.has("server") ) {
try {
Collection<IpAddress> ips = Collections.emptyList();
Collection<VLAN> nets = Collections.emptyList();
JSONObject server = result.getJSONObject("server");
VirtualMachine vm = toVirtualMachine(server, ips, ips, nets);
if( vm != null ) {
return vm;
}
}
catch( JSONException e ) {
logger.error("launch(): Unable to understand launch response: " + e.getMessage());
if( logger.isTraceEnabled() ) {
e.printStackTrace();
}
throw new CloudException(e);
}
}
logger.error("launch(): No server was created by the launch attempt, and no error was returned");
throw new CloudException("No virtual machine was launched");
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFirewalls");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", vmId, true);
if( ob == null ) {
return Collections.emptyList();
}
try {
if( ob.has("server") ) {
JSONObject server = ob.getJSONObject("server");
if( server.has("security_groups") ) {
NetworkServices services = getProvider().getNetworkServices();
Collection<Firewall> firewalls = null;
if( services != null ) {
FirewallSupport support = services.getFirewallSupport();
if( support != null ) {
firewalls = support.list();
}
}
if( firewalls == null ) {
firewalls = Collections.emptyList();
}
JSONArray groups = server.getJSONArray("security_groups");
ArrayList<String> results = new ArrayList<String>();
for( int i=0; i<groups.length(); i++ ) {
JSONObject group = groups.getJSONObject(i);
if( group.has("name") ) {
String name = group.getString("name");
for( Firewall fw : firewalls ) {
if( fw.getName().equals(name) ) {
results.add(fw.getProviderFirewallId());
}
}
}
}
return results;
}
else {
ob = method.getServers("/servers", vmId + "/os-security-groups", true);
if( ob.has("security_groups") ) {
JSONArray groups = ob.getJSONArray("security_groups");
ArrayList<String> results = new ArrayList<String>();
for( int i=0; i<groups.length(); i++ ) {
JSONObject group = groups.getJSONObject(i);
if( group.has("id") ) {
results.add(group.getString("id"));
}
}
return results;
}
}
}
throw new CloudException("No such server: " + vmId);
}
catch( JSONException e ) {
logger.error("listFirewalls(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers");
}
}
finally {
APITrace.end();
}
}
static public class FlavorRef {
public String id;
public String[][] links;
VirtualMachineProduct product;
public String toString() { return (id + " -> " + product); }
}
private @Nonnull Iterable<FlavorRef> listFlavors() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFlavors");
try {
Cache<FlavorRef> cache = Cache.getInstance(getProvider(), "flavorRefs", FlavorRef.class, CacheLevel.REGION_ACCOUNT, new TimePeriod<Day>(1, TimePeriod.DAY));
Iterable<FlavorRef> refs = cache.get(getContext());
if( refs != null ) {
return refs;
}
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/flavors", null, true);
ArrayList<FlavorRef> flavors = new ArrayList<FlavorRef>();
try {
if( ob != null && ob.has("flavors") ) {
JSONArray list = ob.getJSONArray("flavors");
for( int i=0; i<list.length(); i++ ) {
JSONObject p = list.getJSONObject(i);
FlavorRef ref = new FlavorRef();
if( p.has("id") ) {
ref.id = p.getString("id");
}
else {
continue;
}
if( p.has("links") ) {
JSONArray links = p.getJSONArray("links");
ref.links = new String[links.length()][];
for( int j=0; j<links.length(); j++ ) {
JSONObject link = links.getJSONObject(j);
ref.links[j] = new String[2];
if( link.has("rel") ) {
ref.links[j][0] = link.getString("rel");
}
if( link.has("href") ) {
ref.links[j][1] = link.getString("href");
}
}
}
else {
ref.links = new String[0][];
}
ref.product = toProduct(p);
if( ref.product != null ) {
flavors.add(ref);
}
}
}
}
catch( JSONException e ) {
logger.error("listProducts(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors: " + e.getMessage());
}
cache.put(getContext(), flavors);
return flavors;
}
finally {
APITrace.end();
}
}
public @Nullable String getFlavorRef(@Nonnull String flavorId) throws InternalException, CloudException {
for( FlavorRef ref : listFlavors() ) {
if( ref.id.equals(flavorId) ) {
String def = null;
for( String[] link : ref.links ) {
if( link[0] != null && link[0].equals("self") && link[1] != null ) {
return link[1];
}
else if( def == null && link[1] != null ) {
def = link[1];
}
}
return def;
}
}
return null;
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException {
if( !architecture.equals(Architecture.I32) && !architecture.equals(Architecture.I64) ) {
return Collections.emptyList();
}
APITrace.begin(getProvider(), "VM.listProducts");
try {
ArrayList<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>();
for( FlavorRef flavor : listFlavors() ) {
products.add(flavor.product);
}
return products;
}
finally {
APITrace.end();
}
}
@Override
public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException {
ArrayList<Architecture> architectures = new ArrayList<Architecture>();
architectures.add(Architecture.I32);
architectures.add(Architecture.I64);
return architectures;
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachineStatus");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", null, true);
ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>();
try {
if( ob != null && ob.has("servers") ) {
JSONArray list = ob.getJSONArray("servers");
for( int i=0; i<list.length(); i++ ) {
JSONObject server = list.getJSONObject(i);
ResourceStatus vm = toStatus(server);
if( vm != null ) {
servers.add(vm);
}
}
}
}
catch( JSONException e ) {
logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace();
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString());
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachines");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", null, true);
ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>();
Iterable<IpAddress> ipv4 = Collections.emptyList(), ipv6 = Collections.emptyList();
Iterable<VLAN> nets = Collections.emptyList();
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipv4 = support.listIpPool(IPVersion.IPV4, false);
ipv6 = support.listIpPool(IPVersion.IPV6, false);
}
VLANSupport vs = services.getVlanSupport();
if( vs != null ) {
nets = vs.listVlans();
}
}
try {
if( ob != null && ob.has("servers") ) {
JSONArray list = ob.getJSONArray("servers");
for( int i=0; i<list.length(); i++ ) {
JSONObject server = list.getJSONObject(i);
VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, nets);
if( vm != null ) {
servers.add(vm);
}
}
}
}
catch( JSONException e ) {
logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace();
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString());
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public void pause(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.pause");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsPauseUnpause(vm) ) {
throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("pause", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void resume(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.resume");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsSuspendResume(vm) ) {
throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("resume", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.start");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsStartStop(vm) ) {
throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("os-start", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.stop");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsStartStop(vm) ) {
throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("os-stop", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void suspend(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.suspend");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsSuspendResume(vm) ) {
throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("suspend", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void unpause(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.unpause");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsPauseUnpause(vm) ) {
throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("unpause", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String vmId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.reboot");
try {
HashMap<String,Object> json = new HashMap<String,Object>();
HashMap<String,Object> action = new HashMap<String,Object>();
action.put("type", "HARD");
json.put("reboot", action);
NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider()));
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) {
return (!((NovaOpenStack)getProvider()).isHP() && (!((NovaOpenStack)getProvider()).isRackspace() || !getProvider().getCloudName().contains("Rackspace")));
}
@Override
public boolean supportsStartStop(@Nonnull VirtualMachine vm) {
return (!((NovaOpenStack)getProvider()).isHP() && (!((NovaOpenStack)getProvider()).isRackspace() || !getProvider().getCloudName().contains("Rackspace")));
}
@Override
public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) {
return (!((NovaOpenStack)getProvider()).isHP() && (!((NovaOpenStack)getProvider()).isRackspace() || !getProvider().getCloudName().contains("Rackspace")));
}
@Override
public void terminate(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.terminate");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR;
do {
try {
method.deleteServers("/servers", vmId);
return;
}
catch( NovaException e ) {
if( e.getHttpCode() != HttpServletResponse.SC_CONFLICT ) {
throw e;
}
}
try { Thread.sleep(CalendarWrapper.MINUTE); }
catch( InterruptedException e ) { /* ignore */ }
} while( System.currentTimeMillis() < timeout );
}
finally {
APITrace.end();
}
}
private @Nullable VirtualMachineProduct toProduct(@Nullable JSONObject json) throws JSONException, InternalException, CloudException {
if( json == null ) {
return null;
}
VirtualMachineProduct product = new VirtualMachineProduct();
if( json.has("id") ) {
product.setProviderProductId(json.getString("id"));
}
if( json.has("name") ) {
product.setName(json.getString("name"));
}
if( json.has("description") ) {
product.setDescription(json.getString("description"));
}
if( json.has("ram") ) {
product.setRamSize(new Storage<Megabyte>(json.getInt("ram"), Storage.MEGABYTE));
}
if( json.has("disk") ) {
product.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("disk"), Storage.GIGABYTE));
}
product.setCpuCount(1);
if( product.getProviderProductId() == null ) {
return null;
}
if( product.getName() == null ) {
product.setName(product.getProviderProductId());
}
if( product.getDescription() == null ) {
product.setDescription(product.getName());
}
return product;
}
private @Nullable ResourceStatus toStatus(@Nullable JSONObject server) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
String serverId = null;
if( server.has("id") ) {
serverId = server.getString("id");
}
if( serverId == null ) {
return null;
}
VmState state = VmState.PENDING;
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
state = VmState.RUNNING;
}
else if( s.equals("build") ) {
state = VmState.PENDING;
}
else if( s.equals("deleted") ) {
state = VmState.TERMINATED;
}
else if( s.equals("suspended") ) {
state = VmState.SUSPENDED;
}
else if( s.equalsIgnoreCase("paused") ) {
state = VmState.PAUSED;
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
state = VmState.STOPPED;
}
else if( s.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( s.equalsIgnoreCase("pausing") ) {
state = VmState.PAUSING;
}
else if( s.equalsIgnoreCase("suspending") ) {
state = VmState.SUSPENDING;
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
state = VmState.REBOOTING;
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
state = VmState.PENDING;
}
}
return new ResourceStatus(serverId, state);
}
private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
VirtualMachine vm = new VirtualMachine();
vm.setCurrentState(VmState.RUNNING);
vm.setArchitecture(Architecture.I64);
vm.setClonable(false);
vm.setCreationTimestamp(-1L);
vm.setImagable(false);
vm.setLastBootTimestamp(-1L);
vm.setLastPauseTimestamp(-1L);
vm.setPausable(false);
vm.setPersistent(true);
vm.setPlatform(Platform.UNKNOWN);
vm.setRebootable(true);
vm.setProviderOwnerId(getContext().getAccountNumber());
if( server.has("id") ) {
vm.setProviderVirtualMachineId(server.getString("id"));
}
if( server.has("name") ) {
vm.setName(server.getString("name"));
}
if( server.has("description") ) {
vm.setDescription(server.getString("description"));
}
if( server.has("kernel_id") ) {
vm.setProviderKernelImageId(server.getString("kernel_id"));
}
if( server.has("ramdisk_id") ) {
vm.setProviderRamdiskImageId(server.getString("ramdisk_id"));
}
if( vm.getDescription() == null ) {
HashMap<String,String> map = new HashMap<String,String>();
if( server.has("metadata") ) {
JSONObject md = server.getJSONObject("metadata");
if( md.has("org.dasein.description") && vm.getDescription() == null ) {
vm.setDescription(md.getString("org.dasein.description"));
}
else if( md.has("Server Label") ) {
vm.setDescription(md.getString("Server Label"));
}
if( md.has("org.dasein.platform") ) {
try {
vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform")));
}
catch( Throwable ignore ) {
// ignore
}
}
String[] keys = JSONObject.getNames(md);
if( keys != null ) {
for( String key : keys ) {
String value = md.getString(key);
if( value != null ) {
map.put(key, value);
}
}
}
}
if( vm.getDescription() == null ) {
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
vm.setDescription(vm.getName());
}
if( server.has("hostId") ) {
map.put("host", server.getString("hostId"));
}
vm.setTags(map);
}
if( server.has("image") ) {
JSONObject img = server.getJSONObject("image");
if( img.has("id") ) {
vm.setProviderMachineImageId(img.getString("id"));
}
}
if( server.has("flavor") ) {
JSONObject f = server.getJSONObject("flavor");
if( f.has("id") ) {
vm.setProductId(f.getString("id"));
}
}
else if( server.has("flavorId") ) {
vm.setProductId(server.getString("flavorId"));
}
if( server.has("adminPass") ) {
vm.setRootPassword("adminPass");
}
if( server.has("key_name") ) {
vm.setProviderShellKeyIds(server.getString("key_name"));
}
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
vm.setCurrentState(VmState.RUNNING);
}
else if( s.startsWith("build") ) {
vm.setCurrentState(VmState.PENDING);
}
else if( s.equals("deleted") ) {
vm.setCurrentState(VmState.TERMINATED);
}
else if( s.equals("suspended") ) {
vm.setCurrentState(VmState.SUSPENDED);
}
else if( s.equalsIgnoreCase("paused") ) {
vm.setCurrentState(VmState.PAUSED);
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
vm.setCurrentState(VmState.STOPPED);
}
else if( s.equalsIgnoreCase("stopping") ) {
vm.setCurrentState(VmState.STOPPING);
}
else if( s.equalsIgnoreCase("pausing") ) {
vm.setCurrentState(VmState.PAUSING);
}
else if( s.equalsIgnoreCase("suspending") ) {
vm.setCurrentState(VmState.SUSPENDING);
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
vm.setCurrentState(VmState.REBOOTING);
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
vm.setCurrentState(VmState.PENDING);
}
}
if( server.has("created") ) {
vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created")));
}
if( server.has("addresses") ) {
JSONObject addrs = server.getJSONObject("addresses");
String[] names = JSONObject.getNames(addrs);
if( names != null && names.length > 0 ) {
ArrayList<RawAddress> pub = new ArrayList<RawAddress>();
ArrayList<RawAddress> priv = new ArrayList<RawAddress>();
for( String name : names ) {
JSONArray arr = addrs.getJSONArray(name);
for( int i=0; i<arr.length(); i++ ) {
RawAddress addr = null;
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4);
}
else {
JSONObject a = arr.getJSONObject(i);
if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV4);
}
else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV6);
}
}
if( addr != null ) {
if( addr.isPublicIpAddress() ) {
pub.add(addr);
}
else {
priv.add(addr);
}
}
}
if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) {
for( VLAN network : networks ) {
if( network.getName().equals(name) ) {
vm.setProviderVlanId(network.getProviderVlanId());
break;
}
}
}
}
vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()]));
vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()]));
}
RawAddress[] raw = vm.getPublicAddresses();
if( raw != null ) {
for( RawAddress addr : vm.getPublicAddresses() ) {
if( addr.getVersion().equals(IPVersion.IPV4) ) {
for( IpAddress a : ipv4 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
else if( addr.getVersion().equals(IPVersion.IPV6) ) {
for( IpAddress a : ipv6 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
- raw = vm.getPrivateAddresses();
- if( raw != null ) {
- for( RawAddress addr :raw ) {
- if( addr.getVersion().equals(IPVersion.IPV4) ) {
- for( IpAddress a : ipv4 ) {
- if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
- vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
- break;
- }
- }
- }
- else if( addr.getVersion().equals(IPVersion.IPV6) ) {
- for( IpAddress a : ipv6 ) {
- if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
- vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
- break;
- }
- }
- }
+ for( IpAddress addr : ipv4 ) {
+ if( addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
+ vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
+ break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
if( vm.getDescription() == null ) {
vm.setDescription(vm.getName());
}
vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING));
vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING));
if( vm.getPlatform().equals(Platform.UNKNOWN) ) {
Platform p = Platform.guess(vm.getName() + " " + vm.getDescription());
if( p.equals(Platform.UNKNOWN) ) {
MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId());
if( img != null ) {
p = img.getPlatform();
}
}
vm.setPlatform(p);
}
return vm;
}
}
| true | true | private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
VirtualMachine vm = new VirtualMachine();
vm.setCurrentState(VmState.RUNNING);
vm.setArchitecture(Architecture.I64);
vm.setClonable(false);
vm.setCreationTimestamp(-1L);
vm.setImagable(false);
vm.setLastBootTimestamp(-1L);
vm.setLastPauseTimestamp(-1L);
vm.setPausable(false);
vm.setPersistent(true);
vm.setPlatform(Platform.UNKNOWN);
vm.setRebootable(true);
vm.setProviderOwnerId(getContext().getAccountNumber());
if( server.has("id") ) {
vm.setProviderVirtualMachineId(server.getString("id"));
}
if( server.has("name") ) {
vm.setName(server.getString("name"));
}
if( server.has("description") ) {
vm.setDescription(server.getString("description"));
}
if( server.has("kernel_id") ) {
vm.setProviderKernelImageId(server.getString("kernel_id"));
}
if( server.has("ramdisk_id") ) {
vm.setProviderRamdiskImageId(server.getString("ramdisk_id"));
}
if( vm.getDescription() == null ) {
HashMap<String,String> map = new HashMap<String,String>();
if( server.has("metadata") ) {
JSONObject md = server.getJSONObject("metadata");
if( md.has("org.dasein.description") && vm.getDescription() == null ) {
vm.setDescription(md.getString("org.dasein.description"));
}
else if( md.has("Server Label") ) {
vm.setDescription(md.getString("Server Label"));
}
if( md.has("org.dasein.platform") ) {
try {
vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform")));
}
catch( Throwable ignore ) {
// ignore
}
}
String[] keys = JSONObject.getNames(md);
if( keys != null ) {
for( String key : keys ) {
String value = md.getString(key);
if( value != null ) {
map.put(key, value);
}
}
}
}
if( vm.getDescription() == null ) {
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
vm.setDescription(vm.getName());
}
if( server.has("hostId") ) {
map.put("host", server.getString("hostId"));
}
vm.setTags(map);
}
if( server.has("image") ) {
JSONObject img = server.getJSONObject("image");
if( img.has("id") ) {
vm.setProviderMachineImageId(img.getString("id"));
}
}
if( server.has("flavor") ) {
JSONObject f = server.getJSONObject("flavor");
if( f.has("id") ) {
vm.setProductId(f.getString("id"));
}
}
else if( server.has("flavorId") ) {
vm.setProductId(server.getString("flavorId"));
}
if( server.has("adminPass") ) {
vm.setRootPassword("adminPass");
}
if( server.has("key_name") ) {
vm.setProviderShellKeyIds(server.getString("key_name"));
}
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
vm.setCurrentState(VmState.RUNNING);
}
else if( s.startsWith("build") ) {
vm.setCurrentState(VmState.PENDING);
}
else if( s.equals("deleted") ) {
vm.setCurrentState(VmState.TERMINATED);
}
else if( s.equals("suspended") ) {
vm.setCurrentState(VmState.SUSPENDED);
}
else if( s.equalsIgnoreCase("paused") ) {
vm.setCurrentState(VmState.PAUSED);
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
vm.setCurrentState(VmState.STOPPED);
}
else if( s.equalsIgnoreCase("stopping") ) {
vm.setCurrentState(VmState.STOPPING);
}
else if( s.equalsIgnoreCase("pausing") ) {
vm.setCurrentState(VmState.PAUSING);
}
else if( s.equalsIgnoreCase("suspending") ) {
vm.setCurrentState(VmState.SUSPENDING);
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
vm.setCurrentState(VmState.REBOOTING);
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
vm.setCurrentState(VmState.PENDING);
}
}
if( server.has("created") ) {
vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created")));
}
if( server.has("addresses") ) {
JSONObject addrs = server.getJSONObject("addresses");
String[] names = JSONObject.getNames(addrs);
if( names != null && names.length > 0 ) {
ArrayList<RawAddress> pub = new ArrayList<RawAddress>();
ArrayList<RawAddress> priv = new ArrayList<RawAddress>();
for( String name : names ) {
JSONArray arr = addrs.getJSONArray(name);
for( int i=0; i<arr.length(); i++ ) {
RawAddress addr = null;
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4);
}
else {
JSONObject a = arr.getJSONObject(i);
if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV4);
}
else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV6);
}
}
if( addr != null ) {
if( addr.isPublicIpAddress() ) {
pub.add(addr);
}
else {
priv.add(addr);
}
}
}
if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) {
for( VLAN network : networks ) {
if( network.getName().equals(name) ) {
vm.setProviderVlanId(network.getProviderVlanId());
break;
}
}
}
}
vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()]));
vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()]));
}
RawAddress[] raw = vm.getPublicAddresses();
if( raw != null ) {
for( RawAddress addr : vm.getPublicAddresses() ) {
if( addr.getVersion().equals(IPVersion.IPV4) ) {
for( IpAddress a : ipv4 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
else if( addr.getVersion().equals(IPVersion.IPV6) ) {
for( IpAddress a : ipv6 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
raw = vm.getPrivateAddresses();
if( raw != null ) {
for( RawAddress addr :raw ) {
if( addr.getVersion().equals(IPVersion.IPV4) ) {
for( IpAddress a : ipv4 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
else if( addr.getVersion().equals(IPVersion.IPV6) ) {
for( IpAddress a : ipv6 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
if( vm.getDescription() == null ) {
vm.setDescription(vm.getName());
}
vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING));
vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING));
if( vm.getPlatform().equals(Platform.UNKNOWN) ) {
Platform p = Platform.guess(vm.getName() + " " + vm.getDescription());
if( p.equals(Platform.UNKNOWN) ) {
MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId());
if( img != null ) {
p = img.getPlatform();
}
}
vm.setPlatform(p);
}
return vm;
}
| private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
VirtualMachine vm = new VirtualMachine();
vm.setCurrentState(VmState.RUNNING);
vm.setArchitecture(Architecture.I64);
vm.setClonable(false);
vm.setCreationTimestamp(-1L);
vm.setImagable(false);
vm.setLastBootTimestamp(-1L);
vm.setLastPauseTimestamp(-1L);
vm.setPausable(false);
vm.setPersistent(true);
vm.setPlatform(Platform.UNKNOWN);
vm.setRebootable(true);
vm.setProviderOwnerId(getContext().getAccountNumber());
if( server.has("id") ) {
vm.setProviderVirtualMachineId(server.getString("id"));
}
if( server.has("name") ) {
vm.setName(server.getString("name"));
}
if( server.has("description") ) {
vm.setDescription(server.getString("description"));
}
if( server.has("kernel_id") ) {
vm.setProviderKernelImageId(server.getString("kernel_id"));
}
if( server.has("ramdisk_id") ) {
vm.setProviderRamdiskImageId(server.getString("ramdisk_id"));
}
if( vm.getDescription() == null ) {
HashMap<String,String> map = new HashMap<String,String>();
if( server.has("metadata") ) {
JSONObject md = server.getJSONObject("metadata");
if( md.has("org.dasein.description") && vm.getDescription() == null ) {
vm.setDescription(md.getString("org.dasein.description"));
}
else if( md.has("Server Label") ) {
vm.setDescription(md.getString("Server Label"));
}
if( md.has("org.dasein.platform") ) {
try {
vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform")));
}
catch( Throwable ignore ) {
// ignore
}
}
String[] keys = JSONObject.getNames(md);
if( keys != null ) {
for( String key : keys ) {
String value = md.getString(key);
if( value != null ) {
map.put(key, value);
}
}
}
}
if( vm.getDescription() == null ) {
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
vm.setDescription(vm.getName());
}
if( server.has("hostId") ) {
map.put("host", server.getString("hostId"));
}
vm.setTags(map);
}
if( server.has("image") ) {
JSONObject img = server.getJSONObject("image");
if( img.has("id") ) {
vm.setProviderMachineImageId(img.getString("id"));
}
}
if( server.has("flavor") ) {
JSONObject f = server.getJSONObject("flavor");
if( f.has("id") ) {
vm.setProductId(f.getString("id"));
}
}
else if( server.has("flavorId") ) {
vm.setProductId(server.getString("flavorId"));
}
if( server.has("adminPass") ) {
vm.setRootPassword("adminPass");
}
if( server.has("key_name") ) {
vm.setProviderShellKeyIds(server.getString("key_name"));
}
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
vm.setCurrentState(VmState.RUNNING);
}
else if( s.startsWith("build") ) {
vm.setCurrentState(VmState.PENDING);
}
else if( s.equals("deleted") ) {
vm.setCurrentState(VmState.TERMINATED);
}
else if( s.equals("suspended") ) {
vm.setCurrentState(VmState.SUSPENDED);
}
else if( s.equalsIgnoreCase("paused") ) {
vm.setCurrentState(VmState.PAUSED);
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
vm.setCurrentState(VmState.STOPPED);
}
else if( s.equalsIgnoreCase("stopping") ) {
vm.setCurrentState(VmState.STOPPING);
}
else if( s.equalsIgnoreCase("pausing") ) {
vm.setCurrentState(VmState.PAUSING);
}
else if( s.equalsIgnoreCase("suspending") ) {
vm.setCurrentState(VmState.SUSPENDING);
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
vm.setCurrentState(VmState.REBOOTING);
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
vm.setCurrentState(VmState.PENDING);
}
}
if( server.has("created") ) {
vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created")));
}
if( server.has("addresses") ) {
JSONObject addrs = server.getJSONObject("addresses");
String[] names = JSONObject.getNames(addrs);
if( names != null && names.length > 0 ) {
ArrayList<RawAddress> pub = new ArrayList<RawAddress>();
ArrayList<RawAddress> priv = new ArrayList<RawAddress>();
for( String name : names ) {
JSONArray arr = addrs.getJSONArray(name);
for( int i=0; i<arr.length(); i++ ) {
RawAddress addr = null;
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4);
}
else {
JSONObject a = arr.getJSONObject(i);
if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV4);
}
else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV6);
}
}
if( addr != null ) {
if( addr.isPublicIpAddress() ) {
pub.add(addr);
}
else {
priv.add(addr);
}
}
}
if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) {
for( VLAN network : networks ) {
if( network.getName().equals(name) ) {
vm.setProviderVlanId(network.getProviderVlanId());
break;
}
}
}
}
vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()]));
vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()]));
}
RawAddress[] raw = vm.getPublicAddresses();
if( raw != null ) {
for( RawAddress addr : vm.getPublicAddresses() ) {
if( addr.getVersion().equals(IPVersion.IPV4) ) {
for( IpAddress a : ipv4 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
else if( addr.getVersion().equals(IPVersion.IPV6) ) {
for( IpAddress a : ipv6 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv4 ) {
if( addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
if( vm.getDescription() == null ) {
vm.setDescription(vm.getName());
}
vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING));
vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING));
if( vm.getPlatform().equals(Platform.UNKNOWN) ) {
Platform p = Platform.guess(vm.getName() + " " + vm.getDescription());
if( p.equals(Platform.UNKNOWN) ) {
MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId());
if( img != null ) {
p = img.getPlatform();
}
}
vm.setPlatform(p);
}
return vm;
}
|
diff --git a/src/edu/jas/ring/EReductionSeq.java b/src/edu/jas/ring/EReductionSeq.java
index b12cca4f..70f4c972 100644
--- a/src/edu/jas/ring/EReductionSeq.java
+++ b/src/edu/jas/ring/EReductionSeq.java
@@ -1,362 +1,379 @@
/*
* $Id$
*/
package edu.jas.ring;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import edu.jas.poly.ExpVector;
import edu.jas.poly.GenPolynomial;
import edu.jas.structure.RingElem;
/**
* Polynomial E-Reduction sequential use algorithm.
* Implements normalform.
* @author Heinz Kredel
*/
public class EReductionSeq<C extends RingElem<C>>
extends DReductionSeq<C>
implements EReduction<C> {
private static final Logger logger = Logger.getLogger(DReductionSeq.class);
/**
* Constructor.
*/
public EReductionSeq() {
}
/**
* Is top reducible.
* @typeparam C coefficient type.
* @param A polynomial.
* @param P polynomial list.
* @return true if A is top reducible with respect to P.
*/
//SuppressWarnings("unchecked") // not jet working
public boolean isTopReducible(List<GenPolynomial<C>> P,
GenPolynomial<C> A) {
if ( P == null || P.isEmpty() ) {
return false;
}
if ( A == null || A.isZERO() ) {
return false;
}
boolean mt = false;
ExpVector e = A.leadingExpVector();
C a = A.leadingBaseCoefficient();
for ( GenPolynomial<C> p : P ) {
mt = ExpVector.EVMT( e, p.leadingExpVector() );
if ( mt ) {
C b = p.leadingBaseCoefficient();
C r = a.remainder( b );
mt = !r.equals(a);
if ( mt ) {
return true;
}
}
}
return false;
}
/**
* Is in Normalform.
* @typeparam C coefficient type.
* @param Ap polynomial.
* @param Pp polynomial list.
* @return true if Ap is in normalform with respect to Pp.
*/
//SuppressWarnings("unchecked") // not jet working
public boolean isNormalform(List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return true;
}
if ( Ap == null || Ap.isZERO() ) {
return true;
}
int l;
GenPolynomial<C>[] P;
synchronized (Pp) {
l = Pp.size();
P = new GenPolynomial[l];
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
C[] lbc = (C[]) new RingElem[ l ]; // want <C>
GenPolynomial<C>[] p = new GenPolynomial[ l ];
Map.Entry<ExpVector,C> m;
int i;
int j = 0;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
boolean mt = false;
Map<ExpVector,C> Am = Ap.getMap();
for ( ExpVector e : Am.keySet() ) {
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) {
C a = Am.get(e);
C r = a.remainder( lbc[i] );
mt = !r.equals(a);
if ( mt ) {
return false;
}
}
}
}
return true;
}
/**
* Normalform using e-reduction.
* @typeparam C coefficient type.
* @param Ap polynomial.
* @param Pp polynomial list.
* @return e-nf(Ap) with respect to Pp.
*/
//SuppressWarnings("unchecked") // not jet working
public GenPolynomial<C> normalform(List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
int l;
GenPolynomial<C>[] P;
synchronized (Pp) {
l = Pp.size();
P = (GenPolynomial<C>[])new GenPolynomial[l];
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i).abs();
}
}
Map.Entry<ExpVector,C> m;
ExpVector[] htl = new ExpVector[ l ];
C[] lbc = (C[]) new RingElem[ l ]; // want <C>
GenPolynomial<C>[] p = (GenPolynomial<C>[])new GenPolynomial[ l ];
int i;
int j = 0;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e = null;
+ ExpVector f = null;
C a = null;
+ C b = null;
+ C r = null;
GenPolynomial<C> R = Ap.ring.getZERO();
GenPolynomial<C> T = Ap.ring.getZERO();
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
+ try {
while ( S.length() > 0 ) {
boolean mt = false;
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) {
- ExpVector f = ExpVector.EVDIF( e, htl[i] );
+ f = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + f);
- C r = a.remainder( lbc[i] );
- C b = a.divide( lbc[i] );
- Q = p[i].multiply( b, f );
+ r = a.remainder( lbc[i] );
+ b = a.divide( lbc[i] );
+ if ( f == null ) {
+ System.out.println("f = null: " + e + ", " + htl[i]);
+ Q = p[i].multiply( b );
+ } else {
+ Q = p[i].multiply( b, f );
+ }
S = S.subtract( Q ); // ok also with reductum
//System.out.println(" r = " + r);
a = r;
if ( r.isZERO() ) {
break;
}
}
}
if ( !a.isZERO() ) { //! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
//S = S.subtract( a, e );
S = S.reductum();
}
//System.out.println(" R = " + R);
//System.out.println(" S = " + S);
}
+ } catch (Exception ex) {
+ System.out.println("R = " + R);
+ System.out.println("S = " + S);
+ System.out.println("f = " + f + ", " + e + ", " + htl[i]);
+ System.out.println("a = " + a + ", " + b + ", " + r + ", " + lbc[i]);
+ //throw ex;
+ return T;
+ }
return R.abs();
}
/**
* Normalform with recording.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,Ap), the normal form of Ap wrt. Pp.
*/
@SuppressWarnings("unchecked") // not jet working
public GenPolynomial<C>
normalform(List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
throw new RuntimeException("not jet implemented");
/*
int l = Pp.size();
GenPolynomial<C>[] P = new GenPolynomial[l];
synchronized (Pp) {
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want <C>
GenPolynomial<C>[] p = new GenPolynomial[ l ];
Map.Entry<ExpVector,C> m;
int j = 0;
int i;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> zero = Ap.ring.getZERO();
GenPolynomial<C> R = Ap.ring.getZERO();
GenPolynomial<C> fac = null;
// GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
//throw new RuntimeException("Syzygy no GB");
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C)lbc[i];
a = a.divide( c );
Q = p[i].multiply( a, e );
S = S.subtract( Q );
fac = row.get(i);
if ( fac == null ) {
fac = zero.sum( a, e );
} else {
fac = fac.sum( a, e );
}
row.set(i,fac);
}
}
return R;
*/
}
/**
* Irreducible set.
* @typeparam C coefficient type.
* @param Pp polynomial list.
* @return a list P of polynomials which are in normalform wrt. P.
*/
public List<GenPolynomial<C>> irreducibleSet(List<GenPolynomial<C>> Pp) {
ArrayList<GenPolynomial<C>> P = new ArrayList<GenPolynomial<C>>();
if ( Pp == null ) {
return null;
}
for ( GenPolynomial<C> a : Pp ) {
if ( !a.isZERO() ) {
P.add( a );
}
}
int l = P.size();
if ( l <= 1 ) return P;
int irr = 0;
ExpVector e;
ExpVector f;
C c;
C d;
GenPolynomial<C> a;
Iterator<GenPolynomial<C>> it;
logger.debug("irr = ");
while ( irr != l ) {
//it = P.listIterator();
a = P.get(0); //it.next();
P.remove(0);
e = a.leadingExpVector();
c = a.leadingBaseCoefficient();
a = normalform( P, a );
logger.debug(String.valueOf(irr));
if ( a.isZERO() ) { l--;
if ( l <= 1 ) { return P; }
} else {
f = a.leadingExpVector();
d = a.leadingBaseCoefficient();
if ( e.equals( f ) && c.equals(d) ) {
irr++;
} else {
irr = 0;
}
P.add( a );
}
}
//System.out.println();
return P;
}
}
| false | true | public GenPolynomial<C> normalform(List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
int l;
GenPolynomial<C>[] P;
synchronized (Pp) {
l = Pp.size();
P = (GenPolynomial<C>[])new GenPolynomial[l];
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i).abs();
}
}
Map.Entry<ExpVector,C> m;
ExpVector[] htl = new ExpVector[ l ];
C[] lbc = (C[]) new RingElem[ l ]; // want <C>
GenPolynomial<C>[] p = (GenPolynomial<C>[])new GenPolynomial[ l ];
int i;
int j = 0;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e = null;
C a = null;
GenPolynomial<C> R = Ap.ring.getZERO();
GenPolynomial<C> T = Ap.ring.getZERO();
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
boolean mt = false;
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) {
ExpVector f = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + f);
C r = a.remainder( lbc[i] );
C b = a.divide( lbc[i] );
Q = p[i].multiply( b, f );
S = S.subtract( Q ); // ok also with reductum
//System.out.println(" r = " + r);
a = r;
if ( r.isZERO() ) {
break;
}
}
}
if ( !a.isZERO() ) { //! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
//S = S.subtract( a, e );
S = S.reductum();
}
//System.out.println(" R = " + R);
//System.out.println(" S = " + S);
}
return R.abs();
}
/**
* Normalform with recording.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,Ap), the normal form of Ap wrt. Pp.
*/
@SuppressWarnings("unchecked") // not jet working
public GenPolynomial<C>
normalform(List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
throw new RuntimeException("not jet implemented");
/*
int l = Pp.size();
GenPolynomial<C>[] P = new GenPolynomial[l];
synchronized (Pp) {
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want <C>
GenPolynomial<C>[] p = new GenPolynomial[ l ];
Map.Entry<ExpVector,C> m;
int j = 0;
int i;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> zero = Ap.ring.getZERO();
GenPolynomial<C> R = Ap.ring.getZERO();
GenPolynomial<C> fac = null;
// GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
//throw new RuntimeException("Syzygy no GB");
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C)lbc[i];
a = a.divide( c );
Q = p[i].multiply( a, e );
S = S.subtract( Q );
fac = row.get(i);
if ( fac == null ) {
fac = zero.sum( a, e );
} else {
fac = fac.sum( a, e );
}
row.set(i,fac);
}
}
return R;
*/
}
/**
* Irreducible set.
* @typeparam C coefficient type.
* @param Pp polynomial list.
* @return a list P of polynomials which are in normalform wrt. P.
*/
public List<GenPolynomial<C>> irreducibleSet(List<GenPolynomial<C>> Pp) {
ArrayList<GenPolynomial<C>> P = new ArrayList<GenPolynomial<C>>();
if ( Pp == null ) {
return null;
}
for ( GenPolynomial<C> a : Pp ) {
if ( !a.isZERO() ) {
P.add( a );
}
}
int l = P.size();
if ( l <= 1 ) return P;
int irr = 0;
ExpVector e;
ExpVector f;
C c;
C d;
GenPolynomial<C> a;
Iterator<GenPolynomial<C>> it;
logger.debug("irr = ");
while ( irr != l ) {
//it = P.listIterator();
a = P.get(0); //it.next();
P.remove(0);
e = a.leadingExpVector();
c = a.leadingBaseCoefficient();
a = normalform( P, a );
logger.debug(String.valueOf(irr));
if ( a.isZERO() ) { l--;
if ( l <= 1 ) { return P; }
} else {
f = a.leadingExpVector();
d = a.leadingBaseCoefficient();
if ( e.equals( f ) && c.equals(d) ) {
irr++;
} else {
irr = 0;
}
P.add( a );
}
}
//System.out.println();
return P;
}
}
| public GenPolynomial<C> normalform(List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
int l;
GenPolynomial<C>[] P;
synchronized (Pp) {
l = Pp.size();
P = (GenPolynomial<C>[])new GenPolynomial[l];
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i).abs();
}
}
Map.Entry<ExpVector,C> m;
ExpVector[] htl = new ExpVector[ l ];
C[] lbc = (C[]) new RingElem[ l ]; // want <C>
GenPolynomial<C>[] p = (GenPolynomial<C>[])new GenPolynomial[ l ];
int i;
int j = 0;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e = null;
ExpVector f = null;
C a = null;
C b = null;
C r = null;
GenPolynomial<C> R = Ap.ring.getZERO();
GenPolynomial<C> T = Ap.ring.getZERO();
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
try {
while ( S.length() > 0 ) {
boolean mt = false;
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) {
f = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + f);
r = a.remainder( lbc[i] );
b = a.divide( lbc[i] );
if ( f == null ) {
System.out.println("f = null: " + e + ", " + htl[i]);
Q = p[i].multiply( b );
} else {
Q = p[i].multiply( b, f );
}
S = S.subtract( Q ); // ok also with reductum
//System.out.println(" r = " + r);
a = r;
if ( r.isZERO() ) {
break;
}
}
}
if ( !a.isZERO() ) { //! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
//S = S.subtract( a, e );
S = S.reductum();
}
//System.out.println(" R = " + R);
//System.out.println(" S = " + S);
}
} catch (Exception ex) {
System.out.println("R = " + R);
System.out.println("S = " + S);
System.out.println("f = " + f + ", " + e + ", " + htl[i]);
System.out.println("a = " + a + ", " + b + ", " + r + ", " + lbc[i]);
//throw ex;
return T;
}
return R.abs();
}
/**
* Normalform with recording.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,Ap), the normal form of Ap wrt. Pp.
*/
@SuppressWarnings("unchecked") // not jet working
public GenPolynomial<C>
normalform(List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
throw new RuntimeException("not jet implemented");
/*
int l = Pp.size();
GenPolynomial<C>[] P = new GenPolynomial[l];
synchronized (Pp) {
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want <C>
GenPolynomial<C>[] p = new GenPolynomial[ l ];
Map.Entry<ExpVector,C> m;
int j = 0;
int i;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> zero = Ap.ring.getZERO();
GenPolynomial<C> R = Ap.ring.getZERO();
GenPolynomial<C> fac = null;
// GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
//throw new RuntimeException("Syzygy no GB");
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C)lbc[i];
a = a.divide( c );
Q = p[i].multiply( a, e );
S = S.subtract( Q );
fac = row.get(i);
if ( fac == null ) {
fac = zero.sum( a, e );
} else {
fac = fac.sum( a, e );
}
row.set(i,fac);
}
}
return R;
*/
}
/**
* Irreducible set.
* @typeparam C coefficient type.
* @param Pp polynomial list.
* @return a list P of polynomials which are in normalform wrt. P.
*/
public List<GenPolynomial<C>> irreducibleSet(List<GenPolynomial<C>> Pp) {
ArrayList<GenPolynomial<C>> P = new ArrayList<GenPolynomial<C>>();
if ( Pp == null ) {
return null;
}
for ( GenPolynomial<C> a : Pp ) {
if ( !a.isZERO() ) {
P.add( a );
}
}
int l = P.size();
if ( l <= 1 ) return P;
int irr = 0;
ExpVector e;
ExpVector f;
C c;
C d;
GenPolynomial<C> a;
Iterator<GenPolynomial<C>> it;
logger.debug("irr = ");
while ( irr != l ) {
//it = P.listIterator();
a = P.get(0); //it.next();
P.remove(0);
e = a.leadingExpVector();
c = a.leadingBaseCoefficient();
a = normalform( P, a );
logger.debug(String.valueOf(irr));
if ( a.isZERO() ) { l--;
if ( l <= 1 ) { return P; }
} else {
f = a.leadingExpVector();
d = a.leadingBaseCoefficient();
if ( e.equals( f ) && c.equals(d) ) {
irr++;
} else {
irr = 0;
}
P.add( a );
}
}
//System.out.println();
return P;
}
}
|
diff --git a/core/src/java/com/dtolabs/rundeck/core/common/UpdateUtils.java b/core/src/java/com/dtolabs/rundeck/core/common/UpdateUtils.java
index c58ceda9a..ee9881163 100644
--- a/core/src/java/com/dtolabs/rundeck/core/common/UpdateUtils.java
+++ b/core/src/java/com/dtolabs/rundeck/core/common/UpdateUtils.java
@@ -1,178 +1,179 @@
/*
* Copyright 2010 DTO Labs, Inc. (http://dtolabs.com)
*
* 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.
*/
/*
* UpdateUtils.java
*
* User: Greg Schueler <a href="mailto:[email protected]">[email protected]</a>
* Created: Oct 14, 2010 12:15:28 PM
*
*/
package com.dtolabs.rundeck.core.common;
import com.dtolabs.rundeck.core.utils.FileUtils;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Get;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
/**
* UpdateUtils provides {@link #updateFileFromUrl(String, String)} to GET a file from remote URL and
* store it to a file. This utility will provide locks and synchronization to prevent two threads or jvms from
* overwriting the destination file at the same time, and will use last modification time from the source URL to skip
* URL acquisition based on file modification time.
*
* @author Greg Schueler <a href="mailto:[email protected]">[email protected]</a>
*/
public class UpdateUtils {
private static Logger logger = Logger.getLogger(UpdateUtils.class);
static final boolean USETIMESTAMP = true;
/**
* Get the source URL and store it to a destination file path
*
* @param sourceUrl
* @param destinationFilePath
*
* @throws UpdateException
*/
public static void updateFileFromUrl(final String sourceUrl, final String destinationFilePath) throws
UpdateException {
final URL url;
try {
url = new URL(sourceUrl);
} catch (MalformedURLException e) {
throw new UpdateException(e);
}
final File destinationFile = new File(destinationFilePath);
final long mtime = destinationFile.exists() ? destinationFile.lastModified() : 0;
get(url, destinationFile);
if (destinationFile.lastModified() > mtime) {
logger.info("updated file: " + destinationFile.getAbsolutePath());
} else {
logger.info("file already up to date: " + destinationFile.getAbsolutePath());
}
}
static void get(final URL srcUrl, final File destFile) throws UpdateException {
final Project p = new Project();
final File lockFile = new File(destFile.getAbsolutePath() + ".lock");
final File newDestFile = new File(destFile.getAbsolutePath() + ".new");
try {
final Task getTask = createTask(srcUrl, newDestFile, null, null);
getTask.setProject(p);
//synchronize writing to file within this jvm
synchronized (UpdateUtils.class) {
final FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
//acquire file lock to block external jvm (commandline) from writing to file
final FileLock lock = channel.lock();
try {
FileUtils.copyFileStreams(destFile, newDestFile);
if(!newDestFile.setLastModified(destFile.lastModified())) {
logger.warn("Unable to set modification time of temp file: " + newDestFile.getAbsolutePath());
}
getTask.execute();
final String osName = System.getProperty("os.name");
if (!newDestFile.renameTo(destFile)) {
if (osName.toLowerCase().indexOf("windows") > -1 && destFile.exists()) {
//first remove the destFile
if (!destFile.delete()) {
throw new UpdateException(
"Unable to remove dest file on windows: " + destFile);
}
if (!newDestFile.renameTo(destFile)) {
throw new UpdateException(
"Unable to move temp file to dest file on windows: " + newDestFile + ", "
+ destFile);
}
} else {
throw new UpdateException(
"Unable to move temp file to dest file: " + newDestFile + ", " + destFile);
}
}
} catch (BuildException e) {
- throw new UpdateException("Get task failed retrieving file from server", e);
+ logger.error("Error getting URL <" + srcUrl + ">: " + e.getMessage(), e);
+ throw new UpdateException(e);
} finally {
lock.release();
channel.close();
}
}
} catch (IOException e) {
throw new UpdateException("Unable to get and write file: " + e.getMessage(), e);
}
}
private static Task createTask(final URL fileUrl, final File destFile,
final String username, final String password) {
final Get getTask = new Get();
getTask.setDest(destFile);
if (null != username) {
getTask.setUsername(username);
}
if (null != password) {
getTask.setPassword(password);
}
getTask.setSrc(fileUrl);
/**
* If it is an empty file, then ignore timestamp check and get it
*/
if (destFile.length() == 0) {
getTask.setUseTimestamp(false);
} else {
getTask.setUseTimestamp(USETIMESTAMP);
}
return getTask;
}
/**
* An exception caused by the UpdateUtils methods.
*/
public static class UpdateException extends Exception {
public UpdateException() {
super();
}
public UpdateException(final String s) {
super(s);
}
public UpdateException(final String s, final Throwable throwable) {
super(s, throwable);
}
public UpdateException(final Throwable throwable) {
super(throwable);
}
}
}
| true | true | static void get(final URL srcUrl, final File destFile) throws UpdateException {
final Project p = new Project();
final File lockFile = new File(destFile.getAbsolutePath() + ".lock");
final File newDestFile = new File(destFile.getAbsolutePath() + ".new");
try {
final Task getTask = createTask(srcUrl, newDestFile, null, null);
getTask.setProject(p);
//synchronize writing to file within this jvm
synchronized (UpdateUtils.class) {
final FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
//acquire file lock to block external jvm (commandline) from writing to file
final FileLock lock = channel.lock();
try {
FileUtils.copyFileStreams(destFile, newDestFile);
if(!newDestFile.setLastModified(destFile.lastModified())) {
logger.warn("Unable to set modification time of temp file: " + newDestFile.getAbsolutePath());
}
getTask.execute();
final String osName = System.getProperty("os.name");
if (!newDestFile.renameTo(destFile)) {
if (osName.toLowerCase().indexOf("windows") > -1 && destFile.exists()) {
//first remove the destFile
if (!destFile.delete()) {
throw new UpdateException(
"Unable to remove dest file on windows: " + destFile);
}
if (!newDestFile.renameTo(destFile)) {
throw new UpdateException(
"Unable to move temp file to dest file on windows: " + newDestFile + ", "
+ destFile);
}
} else {
throw new UpdateException(
"Unable to move temp file to dest file: " + newDestFile + ", " + destFile);
}
}
} catch (BuildException e) {
throw new UpdateException("Get task failed retrieving file from server", e);
} finally {
lock.release();
channel.close();
}
}
} catch (IOException e) {
throw new UpdateException("Unable to get and write file: " + e.getMessage(), e);
}
}
| static void get(final URL srcUrl, final File destFile) throws UpdateException {
final Project p = new Project();
final File lockFile = new File(destFile.getAbsolutePath() + ".lock");
final File newDestFile = new File(destFile.getAbsolutePath() + ".new");
try {
final Task getTask = createTask(srcUrl, newDestFile, null, null);
getTask.setProject(p);
//synchronize writing to file within this jvm
synchronized (UpdateUtils.class) {
final FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
//acquire file lock to block external jvm (commandline) from writing to file
final FileLock lock = channel.lock();
try {
FileUtils.copyFileStreams(destFile, newDestFile);
if(!newDestFile.setLastModified(destFile.lastModified())) {
logger.warn("Unable to set modification time of temp file: " + newDestFile.getAbsolutePath());
}
getTask.execute();
final String osName = System.getProperty("os.name");
if (!newDestFile.renameTo(destFile)) {
if (osName.toLowerCase().indexOf("windows") > -1 && destFile.exists()) {
//first remove the destFile
if (!destFile.delete()) {
throw new UpdateException(
"Unable to remove dest file on windows: " + destFile);
}
if (!newDestFile.renameTo(destFile)) {
throw new UpdateException(
"Unable to move temp file to dest file on windows: " + newDestFile + ", "
+ destFile);
}
} else {
throw new UpdateException(
"Unable to move temp file to dest file: " + newDestFile + ", " + destFile);
}
}
} catch (BuildException e) {
logger.error("Error getting URL <" + srcUrl + ">: " + e.getMessage(), e);
throw new UpdateException(e);
} finally {
lock.release();
channel.close();
}
}
} catch (IOException e) {
throw new UpdateException("Unable to get and write file: " + e.getMessage(), e);
}
}
|
diff --git a/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java b/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java
index 5740348..949965a 100644
--- a/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java
+++ b/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java
@@ -1,54 +1,55 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.chainsaw.vfs;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the meta-data of the VFSLogFilePatternReceiver.
*
*/
public class VFSLogFilePatternReceiverBeanInfo extends SimpleBeanInfo {
/* (non-Javadoc)
* @see java.beans.BeanInfo#getPropertyDescriptors()
*/
public PropertyDescriptor[] getPropertyDescriptors() {
try {
return new PropertyDescriptor[] {
new PropertyDescriptor("fileURL", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"timestampFormat", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("logFormat", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("name", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("tailing", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("autoReconnect", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("waitMillis", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("appendNonMatches", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("customLevelDefinitions", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"filterExpression", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"promptForUserInfo", VFSLogFilePatternReceiver.class),
};
} catch (Exception e) {
}
return null;
}
}
| true | true | public PropertyDescriptor[] getPropertyDescriptors() {
try {
return new PropertyDescriptor[] {
new PropertyDescriptor("fileURL", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"timestampFormat", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("logFormat", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("name", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("tailing", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("autoReconnect", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("waitMillis", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("appendNonMatches", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"filterExpression", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"promptForUserInfo", VFSLogFilePatternReceiver.class),
};
} catch (Exception e) {
}
return null;
}
| public PropertyDescriptor[] getPropertyDescriptors() {
try {
return new PropertyDescriptor[] {
new PropertyDescriptor("fileURL", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"timestampFormat", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("logFormat", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("name", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("tailing", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("autoReconnect", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("waitMillis", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("appendNonMatches", VFSLogFilePatternReceiver.class),
new PropertyDescriptor("customLevelDefinitions", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"filterExpression", VFSLogFilePatternReceiver.class),
new PropertyDescriptor(
"promptForUserInfo", VFSLogFilePatternReceiver.class),
};
} catch (Exception e) {
}
return null;
}
|
diff --git a/src/org/joval/io/LocalFilesystem.java b/src/org/joval/io/LocalFilesystem.java
index 5b05d516..9984d58a 100755
--- a/src/org/joval/io/LocalFilesystem.java
+++ b/src/org/joval/io/LocalFilesystem.java
@@ -1,254 +1,254 @@
// Copyright (C) 2011 jOVAL.org. All rights reserved.
// This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt
package org.joval.io;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Vector;
import org.joval.intf.io.IFile;
import org.joval.intf.io.IFilesystem;
import org.joval.intf.io.IRandomAccess;
import org.joval.intf.util.ILoggable;
import org.joval.intf.util.IPathRedirector;
import org.joval.intf.util.IProperty;
import org.joval.intf.util.tree.INode;
import org.joval.intf.util.tree.ITree;
import org.joval.intf.util.tree.ITreeBuilder;
import org.joval.intf.system.IBaseSession;
import org.joval.intf.system.IEnvironment;
import org.joval.os.windows.io.WindowsFile;
import org.joval.util.tree.CachingTree;
import org.joval.util.tree.Tree;
import org.joval.util.JOVALMsg;
import org.joval.util.JOVALSystem;
import org.joval.util.StringTools;
/**
* A pure-Java implementation of the IFilesystem interface.
*
* @author David A. Solin
* @version %I% %G%
*/
public class LocalFilesystem extends CachingTree implements IFilesystem {
private static final boolean WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private int entries, maxEntries;
private boolean autoExpand = true, preloaded = false;
private IProperty props;
private IBaseSession session;
private IEnvironment env;
private IPathRedirector redirector;
public LocalFilesystem(IBaseSession session, IEnvironment env, IPathRedirector redirector) {
super();
this.session = session;
this.env = env;
this.redirector = redirector;
props = session.getProperties();
setLogger(session.getLogger());
}
public void setAutoExpand(boolean autoExpand) {
this.autoExpand = autoExpand;
}
public boolean preload() {
- if (props.getBooleanProperty(PROP_PRELOAD_LOCAL)) {
+ if (!props.getBooleanProperty(PROP_PRELOAD_LOCAL)) {
return false;
} else if (preloaded) {
return true;
}
entries = 0;
maxEntries = props.getIntProperty(PROP_PRELOAD_MAXENTRIES);
try {
Collection<String> skips = new Vector<String>();
String skipStr = props.getProperty(PROP_PRELOAD_SKIP);
if (skipStr != null) {
skips.addAll(StringTools.toList(StringTools.tokenize(skipStr, ":", true)));
}
if (WINDOWS) {
File[] roots = File.listRoots();
for (int i=0; i < roots.length; i++) {
String name = roots[i].getName();
if (skips.contains(name)) {
logger.info(JOVALMsg.STATUS_FS_PRELOAD_SKIP, name);
} else {
logger.debug(JOVALMsg.STATUS_FS_PRELOAD, name);
ITreeBuilder tree = cache.getTreeBuilder(name);
if (tree == null) {
tree = new Tree(name, getDelimiter());
cache.addTree(tree);
}
addRecursive(tree, roots[i]);
}
}
} else {
File root = new File(getDelimiter());
Collection<File> roots = new Vector<File>();
if (skips.size() > 0) {
for (String child : root.list()) {
if (skips.contains(child)) {
logger.info(JOVALMsg.STATUS_FS_PRELOAD_SKIP, child);
} else {
roots.add(new File(root, child));
}
}
} else {
roots.add(root);
}
ITreeBuilder tree = cache.getTreeBuilder("");
if (tree == null) {
tree = new Tree("", getDelimiter());
cache.addTree(tree);
}
for (File f : roots) {
logger.debug(JOVALMsg.STATUS_FS_PRELOAD, f.getName());
addRecursive(tree, f);
}
}
} catch (PreloadOverflowException e) {
logger.warn(JOVALMsg.ERROR_PRELOAD_OVERFLOW, maxEntries);
preloaded = true;
return true;
} catch (Exception e) {
logger.warn(JOVALMsg.ERROR_PRELOAD);
logger.warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
return false;
}
preloaded = true;
return true;
}
public String getDelimiter() {
return File.separator;
}
public INode lookup(String path) throws NoSuchElementException {
try {
IFile f = getFile(path);
if (f.exists()) {
return f;
} else {
throw new NoSuchElementException(path);
}
} catch (IOException e) {
logger.warn(JOVALMsg.ERROR_IO, toString(), e.getMessage());
logger.debug(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
return null;
}
// Implement IFilesystem
public boolean connect() {
return true;
}
public void disconnect() {
}
public IFile getFile(String path) throws IllegalArgumentException, IOException {
if (autoExpand) {
path = env.expand(path);
}
String realPath = path;
if (redirector != null) {
String alt = redirector.getRedirect(path);
if (alt != null) {
realPath = alt;
}
}
if (WINDOWS) {
if (realPath.length() > 2 && realPath.charAt(1) == ':') {
if (StringTools.isLetter(realPath.charAt(0))) {
return new WindowsFile(new FileProxy(this, new File(realPath), path));
}
}
throw new IllegalArgumentException(JOVALSystem.getMessage(JOVALMsg.ERROR_FS_LOCALPATH, realPath));
} else if (realPath.length() > 0 && realPath.charAt(0) == File.separatorChar) {
return new FileProxy(this, new File(realPath), path);
} else {
throw new IllegalArgumentException(JOVALSystem.getMessage(JOVALMsg.ERROR_FS_LOCALPATH, realPath));
}
}
public IFile getFile(String path, boolean vol) throws IllegalArgumentException, IOException {
return getFile(path);
}
public IRandomAccess getRandomAccess(IFile file, String mode) throws IllegalArgumentException, IOException {
return new RandomAccessFileProxy(new RandomAccessFile(file.getLocalName(), mode));
}
public IRandomAccess getRandomAccess(String path, String mode) throws IllegalArgumentException, IOException {
return new RandomAccessFileProxy(new RandomAccessFile(path, mode));
}
public InputStream getInputStream(String path) throws IllegalArgumentException, IOException {
return getFile(path).getInputStream();
}
public OutputStream getOutputStream(String path) throws IllegalArgumentException, IOException {
return getFile(path).getOutputStream(false);
}
public OutputStream getOutputStream(String path, boolean append) throws IllegalArgumentException, IOException {
return getFile(path).getOutputStream(append);
}
// Private
private class PreloadOverflowException extends IOException {
private PreloadOverflowException() {
super();
}
}
private void addRecursive(ITreeBuilder tree, File f) throws IOException {
if (entries++ < maxEntries) {
String path = f.getCanonicalPath();
if (!path.equals(f.getPath())) {
logger.warn(JOVALMsg.ERROR_PRELOAD_LINE, path); // skip links
} else if (f.isFile()) {
INode node = tree.getRoot();
try {
while ((path = trimToken(path, getDelimiter())) != null) {
node = node.getChild(getToken(path, getDelimiter()));
}
} catch (UnsupportedOperationException e) {
do {
node = tree.makeNode(node, getToken(path, getDelimiter()));
} while ((path = trimToken(path, getDelimiter())) != null);
} catch (NoSuchElementException e) {
do {
node = tree.makeNode(node, getToken(path, getDelimiter()));
} while ((path = trimToken(path, getDelimiter())) != null);
}
} else if (f.isDirectory()) {
File[] children = f.listFiles();
if (children == null) {
logger.warn(JOVALMsg.ERROR_PRELOAD_LINE, path);
} else {
for (File child : children) {
addRecursive(tree, child);
}
}
} else {
logger.warn(JOVALMsg.ERROR_PRELOAD_LINE, path);
}
} else {
throw new PreloadOverflowException();
}
}
}
| true | true | public boolean preload() {
if (props.getBooleanProperty(PROP_PRELOAD_LOCAL)) {
return false;
} else if (preloaded) {
return true;
}
entries = 0;
maxEntries = props.getIntProperty(PROP_PRELOAD_MAXENTRIES);
try {
Collection<String> skips = new Vector<String>();
String skipStr = props.getProperty(PROP_PRELOAD_SKIP);
if (skipStr != null) {
skips.addAll(StringTools.toList(StringTools.tokenize(skipStr, ":", true)));
}
if (WINDOWS) {
File[] roots = File.listRoots();
for (int i=0; i < roots.length; i++) {
String name = roots[i].getName();
if (skips.contains(name)) {
logger.info(JOVALMsg.STATUS_FS_PRELOAD_SKIP, name);
} else {
logger.debug(JOVALMsg.STATUS_FS_PRELOAD, name);
ITreeBuilder tree = cache.getTreeBuilder(name);
if (tree == null) {
tree = new Tree(name, getDelimiter());
cache.addTree(tree);
}
addRecursive(tree, roots[i]);
}
}
} else {
File root = new File(getDelimiter());
Collection<File> roots = new Vector<File>();
if (skips.size() > 0) {
for (String child : root.list()) {
if (skips.contains(child)) {
logger.info(JOVALMsg.STATUS_FS_PRELOAD_SKIP, child);
} else {
roots.add(new File(root, child));
}
}
} else {
roots.add(root);
}
ITreeBuilder tree = cache.getTreeBuilder("");
if (tree == null) {
tree = new Tree("", getDelimiter());
cache.addTree(tree);
}
for (File f : roots) {
logger.debug(JOVALMsg.STATUS_FS_PRELOAD, f.getName());
addRecursive(tree, f);
}
}
} catch (PreloadOverflowException e) {
logger.warn(JOVALMsg.ERROR_PRELOAD_OVERFLOW, maxEntries);
preloaded = true;
return true;
} catch (Exception e) {
logger.warn(JOVALMsg.ERROR_PRELOAD);
logger.warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
return false;
}
preloaded = true;
return true;
}
| public boolean preload() {
if (!props.getBooleanProperty(PROP_PRELOAD_LOCAL)) {
return false;
} else if (preloaded) {
return true;
}
entries = 0;
maxEntries = props.getIntProperty(PROP_PRELOAD_MAXENTRIES);
try {
Collection<String> skips = new Vector<String>();
String skipStr = props.getProperty(PROP_PRELOAD_SKIP);
if (skipStr != null) {
skips.addAll(StringTools.toList(StringTools.tokenize(skipStr, ":", true)));
}
if (WINDOWS) {
File[] roots = File.listRoots();
for (int i=0; i < roots.length; i++) {
String name = roots[i].getName();
if (skips.contains(name)) {
logger.info(JOVALMsg.STATUS_FS_PRELOAD_SKIP, name);
} else {
logger.debug(JOVALMsg.STATUS_FS_PRELOAD, name);
ITreeBuilder tree = cache.getTreeBuilder(name);
if (tree == null) {
tree = new Tree(name, getDelimiter());
cache.addTree(tree);
}
addRecursive(tree, roots[i]);
}
}
} else {
File root = new File(getDelimiter());
Collection<File> roots = new Vector<File>();
if (skips.size() > 0) {
for (String child : root.list()) {
if (skips.contains(child)) {
logger.info(JOVALMsg.STATUS_FS_PRELOAD_SKIP, child);
} else {
roots.add(new File(root, child));
}
}
} else {
roots.add(root);
}
ITreeBuilder tree = cache.getTreeBuilder("");
if (tree == null) {
tree = new Tree("", getDelimiter());
cache.addTree(tree);
}
for (File f : roots) {
logger.debug(JOVALMsg.STATUS_FS_PRELOAD, f.getName());
addRecursive(tree, f);
}
}
} catch (PreloadOverflowException e) {
logger.warn(JOVALMsg.ERROR_PRELOAD_OVERFLOW, maxEntries);
preloaded = true;
return true;
} catch (Exception e) {
logger.warn(JOVALMsg.ERROR_PRELOAD);
logger.warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
return false;
}
preloaded = true;
return true;
}
|
diff --git a/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPSpecialization.java b/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPSpecialization.java
index ba1c8080f..364dd3c37 100644
--- a/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPSpecialization.java
+++ b/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPSpecialization.java
@@ -1,151 +1,158 @@
/*******************************************************************************
* Copyright (c) 2007 QNX Software Systems 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:
* QNX - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.pdom.dom.cpp;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.IPDOMNode;
import org.eclipse.cdt.core.dom.IPDOMVisitor;
import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPSpecialization;
import org.eclipse.cdt.core.parser.util.ObjectMap;
import org.eclipse.cdt.internal.core.pdom.PDOM;
import org.eclipse.cdt.internal.core.pdom.db.PDOMNodeLinkedList;
import org.eclipse.cdt.internal.core.pdom.dom.IPDOMOverloader;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMNamedNode;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMNode;
import org.eclipse.core.runtime.CoreException;
/**
* @author Bryan Wilkinson
*
*/
abstract class PDOMCPPSpecialization extends PDOMCPPBinding implements
ICPPSpecialization, IPDOMOverloader {
private static final int ARGMAP_PARAMS = PDOMCPPBinding.RECORD_SIZE + 0;
private static final int ARGMAP_ARGS = PDOMCPPBinding.RECORD_SIZE + 4;
private static final int SIGNATURE_MEMENTO = PDOMCPPBinding.RECORD_SIZE + 8;
private static final int SPECIALIZED = PDOMCPPBinding.RECORD_SIZE + 12;
/**
* The size in bytes of a PDOMCPPSpecialization record in the database.
*/
protected static final int RECORD_SIZE = PDOMCPPBinding.RECORD_SIZE + 16;
public PDOMCPPSpecialization(PDOM pdom, PDOMNode parent, ICPPSpecialization spec, PDOMNamedNode specialized)
throws CoreException {
super(pdom, parent, spec.getName().toCharArray());
pdom.getDB().putInt(record + SPECIALIZED, specialized.getRecord());
PDOMNodeLinkedList paramList = new PDOMNodeLinkedList(pdom, record + ARGMAP_PARAMS, getLinkageImpl());
PDOMNodeLinkedList argList = new PDOMNodeLinkedList(pdom, record + ARGMAP_ARGS, getLinkageImpl());
ObjectMap argMap = ((ICPPSpecialization)spec).getArgumentMap();
if (argMap != null) {
for (int i = 0; i < argMap.size(); i++) {
- PDOMNode paramNode = getLinkageImpl().addType(this, (IType) argMap.keyAt(i));
- PDOMNode argNode = getLinkageImpl().addType(this, (IType) argMap.getAt(i));
- if (paramNode != null && argNode != null) {
- paramList.addMember(paramNode);
- argList.addMember(argNode);
+ Object param = argMap.keyAt(i);
+ Object arg = argMap.getAt(i);
+ /* TODO: allow template non-type parameters once they have been
+ * implemented in the PDOM
+ */
+ if (param instanceof IType && arg instanceof IType) {
+ PDOMNode paramNode = getLinkageImpl().addType(this, (IType) param);
+ PDOMNode argNode = getLinkageImpl().addType(this, (IType) arg);
+ if (paramNode != null && argNode != null) {
+ paramList.addMember(paramNode);
+ argList.addMember(argNode);
+ }
}
}
}
try {
Integer memento = PDOMCPPOverloaderUtil.getSignatureMemento(spec);
pdom.getDB().putInt(record + SIGNATURE_MEMENTO, memento != null ? memento.intValue() : 0);
} catch (DOMException e) {
}
}
public PDOMCPPSpecialization(PDOM pdom, int bindingRecord) {
super(pdom, bindingRecord);
}
public IBinding getSpecializedBinding() {
try {
int specializedRec = pdom.getDB().getInt(record + SPECIALIZED);
PDOMNode node = specializedRec != 0 ?
getLinkageImpl().getNode(specializedRec) : null;
if (node instanceof IBinding) {
return (IBinding) node;
}
} catch (CoreException e) {
CCorePlugin.log(e);
}
return null;
}
private static class NodeCollector implements IPDOMVisitor {
private List nodes = new ArrayList();
public boolean visit(IPDOMNode node) throws CoreException {
nodes.add(node);
return false;
}
public void leave(IPDOMNode node) throws CoreException {
}
public IPDOMNode[] getNodes() {
return (IPDOMNode[])nodes.toArray(new IPDOMNode[nodes.size()]);
}
}
public ObjectMap getArgumentMap() {
try {
PDOMNodeLinkedList paramList = new PDOMNodeLinkedList(pdom, record + ARGMAP_PARAMS, getLinkageImpl());
PDOMNodeLinkedList argList = new PDOMNodeLinkedList(pdom, record + ARGMAP_ARGS, getLinkageImpl());
NodeCollector paramVisitor = new NodeCollector();
paramList.accept(paramVisitor);
IPDOMNode[] paramNodes = paramVisitor.getNodes();
NodeCollector argVisitor = new NodeCollector();
argList.accept(argVisitor);
IPDOMNode[] argNodes = argVisitor.getNodes();
ObjectMap map = new ObjectMap(paramNodes.length);
for (int i = 0; i < paramNodes.length; i++) {
map.put(paramNodes[i], argNodes[i]);
}
return map;
} catch (CoreException e) {
CCorePlugin.log(e);
}
return null;
}
public int getSignatureMemento() throws CoreException {
return pdom.getDB().getInt(record + SIGNATURE_MEMENTO);
}
private static IType[] getArguments(ObjectMap argMap) {
IType[] args = new IType[argMap.size()];
for (int i = 0; i < argMap.size(); i++) {
args[i] = (IType) argMap.getAt(i);
}
return args;
}
public boolean matchesArguments(IType[] arguments) {
IType [] args = getArguments(getArgumentMap());
if( args.length == arguments.length ){
int i = 0;
for(; i < args.length; i++) {
if( !( args[i].isSameType( arguments[i] ) ) )
break;
}
return i == args.length;
}
return false;
}
}
| true | true | public PDOMCPPSpecialization(PDOM pdom, PDOMNode parent, ICPPSpecialization spec, PDOMNamedNode specialized)
throws CoreException {
super(pdom, parent, spec.getName().toCharArray());
pdom.getDB().putInt(record + SPECIALIZED, specialized.getRecord());
PDOMNodeLinkedList paramList = new PDOMNodeLinkedList(pdom, record + ARGMAP_PARAMS, getLinkageImpl());
PDOMNodeLinkedList argList = new PDOMNodeLinkedList(pdom, record + ARGMAP_ARGS, getLinkageImpl());
ObjectMap argMap = ((ICPPSpecialization)spec).getArgumentMap();
if (argMap != null) {
for (int i = 0; i < argMap.size(); i++) {
PDOMNode paramNode = getLinkageImpl().addType(this, (IType) argMap.keyAt(i));
PDOMNode argNode = getLinkageImpl().addType(this, (IType) argMap.getAt(i));
if (paramNode != null && argNode != null) {
paramList.addMember(paramNode);
argList.addMember(argNode);
}
}
}
try {
Integer memento = PDOMCPPOverloaderUtil.getSignatureMemento(spec);
pdom.getDB().putInt(record + SIGNATURE_MEMENTO, memento != null ? memento.intValue() : 0);
} catch (DOMException e) {
}
}
| public PDOMCPPSpecialization(PDOM pdom, PDOMNode parent, ICPPSpecialization spec, PDOMNamedNode specialized)
throws CoreException {
super(pdom, parent, spec.getName().toCharArray());
pdom.getDB().putInt(record + SPECIALIZED, specialized.getRecord());
PDOMNodeLinkedList paramList = new PDOMNodeLinkedList(pdom, record + ARGMAP_PARAMS, getLinkageImpl());
PDOMNodeLinkedList argList = new PDOMNodeLinkedList(pdom, record + ARGMAP_ARGS, getLinkageImpl());
ObjectMap argMap = ((ICPPSpecialization)spec).getArgumentMap();
if (argMap != null) {
for (int i = 0; i < argMap.size(); i++) {
Object param = argMap.keyAt(i);
Object arg = argMap.getAt(i);
/* TODO: allow template non-type parameters once they have been
* implemented in the PDOM
*/
if (param instanceof IType && arg instanceof IType) {
PDOMNode paramNode = getLinkageImpl().addType(this, (IType) param);
PDOMNode argNode = getLinkageImpl().addType(this, (IType) arg);
if (paramNode != null && argNode != null) {
paramList.addMember(paramNode);
argList.addMember(argNode);
}
}
}
}
try {
Integer memento = PDOMCPPOverloaderUtil.getSignatureMemento(spec);
pdom.getDB().putInt(record + SIGNATURE_MEMENTO, memento != null ? memento.intValue() : 0);
} catch (DOMException e) {
}
}
|
diff --git a/src/main/java/thesmith/eventhorizon/controller/BaseController.java b/src/main/java/thesmith/eventhorizon/controller/BaseController.java
index 3844f44..5ab5aff 100644
--- a/src/main/java/thesmith/eventhorizon/controller/BaseController.java
+++ b/src/main/java/thesmith/eventhorizon/controller/BaseController.java
@@ -1,212 +1,214 @@
package thesmith.eventhorizon.controller;
import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import thesmith.eventhorizon.model.Account;
import thesmith.eventhorizon.model.Snapshot;
import thesmith.eventhorizon.model.Status;
import thesmith.eventhorizon.model.User;
import thesmith.eventhorizon.service.AccountService;
import thesmith.eventhorizon.service.SnapshotService;
import thesmith.eventhorizon.service.StatusService;
import thesmith.eventhorizon.service.UserService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
public class BaseController {
public static final String VIEWER = "viewer";
public static final String COOKIE = "eventhorizon";
public static final String USERNAME_COOKIE = "eventhorizon-username";
public static final String HOST_POSTFIX = ".eventhorizon.me";
public static final String SECURE_HOST = "https://event-horizon.appspot.com";
public static final String REDIRECT = "redirect:";
protected final Log logger = LogFactory.getLog(this.getClass());
@Autowired
protected UserService userService;
@Autowired
protected AccountService accountService;
@Autowired
protected StatusService statusService;
@Autowired
protected SnapshotService snapshotService;
protected Queue queue = QueueFactory.getDefaultQueue();
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
}
protected Date createStatus(Date nextCreated, Status status, List<Account> accounts) {
Account account = getAccount(accounts, status);
if (null == nextCreated) {
Status next = statusService.next(account, status.getCreated());
if (null != next)
nextCreated = next.getCreated();
+ else
+ nextCreated = new Date();
}
Date previousCreated = status.getCreated();
Status previous = statusService.previous(account, status.getCreated());
if (null != previous)
previousCreated = new Date(previous.getCreated().getTime() + 1L);
statusService.create(status);
boolean found = false;
if (null != previousCreated) {
List<Snapshot> snapshots = snapshotService.list(status.getPersonId(), previousCreated, nextCreated);
for (Snapshot snapshot: snapshots) {
snapshotService.addStatus(snapshot, status);
if (snapshot.getCreated().equals(status.getCreated()))
found = true;
}
}
if (!found)
createSnapshot(status, accounts);
nextCreated = status.getCreated();
return nextCreated;
}
private Account getAccount(List<Account> accounts, Status status) {
for (Account account: accounts) {
if (account.getDomain().equals(status.getDomain()))
return account;
}
return null;
}
private void createSnapshot(Status status, List<Account> accounts) {
List<Key> statusIds = Lists.newArrayList();
List<String> domains = Lists.newArrayList();
for (Account acc: accounts) {
if (null != acc.getUserId()) {
if (acc.getDomain().equals(status.getDomain())) {
statusIds.add(status.getId());
domains.add(status.getDomain());
} else {
Status s = statusService.find(acc, status.getCreated());
if (null != s) {
statusIds.add(s.getId());
domains.add(s.getDomain());
}
}
}
}
Snapshot snapshot = new Snapshot();
snapshot.setPersonId(status.getPersonId());
snapshot.setCreated(status.getCreated());
snapshot.setStatusIds(statusIds);
snapshot.setDomains(domains);
snapshotService.create(snapshot);
}
protected User auth(HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
if (COOKIE.equalsIgnoreCase(cookie.getName())) {
if (logger.isDebugEnabled())
logger.debug("Authenticating cookie: " + cookie.getValue());
User user = userService.authn(cookie.getValue());
if (null != user) {
if (logger.isDebugEnabled())
logger.debug("Cookie authenticated as user: " + user.getUsername());
return user;
}
}
}
}
return null;
}
protected void setViewer(HttpServletRequest request, ModelMap model) {
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
if (BaseController.USERNAME_COOKIE.equalsIgnoreCase(cookie.getName())) {
model.addAttribute(BaseController.VIEWER, cookie.getValue());
model.addAttribute("userHost", userHost(cookie.getValue()));
}
}
}
}
protected boolean isProduction() {
return ("Production".equals(System.getProperty("com.google.appengine.runtime.environment", "")));
}
protected String secureHost() {
if (isProduction())
return SECURE_HOST;
return "";
}
protected void setUserCookie(HttpServletResponse response, String personId) {
Cookie username = new Cookie(USERNAME_COOKIE, personId);
username.setPath("/");
username.setMaxAge(60 * 60 * 24 * 30);
if (isProduction())
username.setDomain(HOST_POSTFIX);
response.addCookie(username);
}
protected String userHost(String personId) {
if (isProduction())
return "http://" + personId + HOST_POSTFIX;
return "/" + personId;
}
protected String authUrl(String personId, String ptrt) {
if (null == ptrt) {
if (isProduction())
return "http://" + personId + HOST_POSTFIX + AuthController.AUTH_URL +"?ptrt=";
return AuthController.AUTH_URL + "?ptrt=/" + personId;
} else {
if (isProduction())
return "http://" + personId + HOST_POSTFIX + AuthController.AUTH_URL + "?ptrt=" + ptrt;
return AuthController.AUTH_URL + "?ptrt=" + ptrt;
}
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public void setStatusService(StatusService statusService) {
this.statusService = statusService;
}
public void setSnapshotService(SnapshotService snapshotService) {
this.snapshotService = snapshotService;
}
public void setQueue(Queue queue) {
this.queue = queue;
}
}
| true | true | protected Date createStatus(Date nextCreated, Status status, List<Account> accounts) {
Account account = getAccount(accounts, status);
if (null == nextCreated) {
Status next = statusService.next(account, status.getCreated());
if (null != next)
nextCreated = next.getCreated();
}
Date previousCreated = status.getCreated();
Status previous = statusService.previous(account, status.getCreated());
if (null != previous)
previousCreated = new Date(previous.getCreated().getTime() + 1L);
statusService.create(status);
boolean found = false;
if (null != previousCreated) {
List<Snapshot> snapshots = snapshotService.list(status.getPersonId(), previousCreated, nextCreated);
for (Snapshot snapshot: snapshots) {
snapshotService.addStatus(snapshot, status);
if (snapshot.getCreated().equals(status.getCreated()))
found = true;
}
}
if (!found)
createSnapshot(status, accounts);
nextCreated = status.getCreated();
return nextCreated;
}
| protected Date createStatus(Date nextCreated, Status status, List<Account> accounts) {
Account account = getAccount(accounts, status);
if (null == nextCreated) {
Status next = statusService.next(account, status.getCreated());
if (null != next)
nextCreated = next.getCreated();
else
nextCreated = new Date();
}
Date previousCreated = status.getCreated();
Status previous = statusService.previous(account, status.getCreated());
if (null != previous)
previousCreated = new Date(previous.getCreated().getTime() + 1L);
statusService.create(status);
boolean found = false;
if (null != previousCreated) {
List<Snapshot> snapshots = snapshotService.list(status.getPersonId(), previousCreated, nextCreated);
for (Snapshot snapshot: snapshots) {
snapshotService.addStatus(snapshot, status);
if (snapshot.getCreated().equals(status.getCreated()))
found = true;
}
}
if (!found)
createSnapshot(status, accounts);
nextCreated = status.getCreated();
return nextCreated;
}
|
diff --git a/wallet/src/de/schildbach/wallet/service/AutosyncReceiver.java b/wallet/src/de/schildbach/wallet/service/AutosyncReceiver.java
index 5fe8181..2d1a71c 100644
--- a/wallet/src/de/schildbach/wallet/service/AutosyncReceiver.java
+++ b/wallet/src/de/schildbach/wallet/service/AutosyncReceiver.java
@@ -1,86 +1,86 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.schildbach.wallet.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.preference.PreferenceManager;
import android.util.Log;
import de.schildbach.wallet.Constants;
/**
* @author Andreas Schildbach
*/
public class AutosyncReceiver extends BroadcastReceiver
{
private static final String TAG = AutosyncReceiver.class.getSimpleName();
@Override
public void onReceive(final Context context, final Intent intent)
{
Log.i(TAG, "got broadcast intent: " + intent);
// other app got replaced
- if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED) && !intent.getDataString().equals(context.getPackageName()))
+ if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED) && !intent.getDataString().equals("package:" + context.getPackageName()))
return;
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final boolean prefsAutosync = prefs.getBoolean(Constants.PREFS_KEY_AUTOSYNC, true);
final long prefsLastUsed = prefs.getLong(Constants.PREFS_KEY_LAST_USED, 0);
// determine power connected state
final Intent batteryChanged = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
final int batteryStatus = batteryChanged.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isPowerConnected = batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING || batteryStatus == BatteryManager.BATTERY_STATUS_FULL;
final boolean running = prefsAutosync && isPowerConnected;
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Intent serviceIntent = new Intent(BlockchainService.ACTION_HOLD_WIFI_LOCK, null, context, BlockchainServiceImpl.class);
final PendingIntent alarmIntent = PendingIntent.getService(context, 0, serviceIntent, 0);
if (running)
{
context.startService(serviceIntent);
final long now = System.currentTimeMillis();
final long lastUsedAgo = now - prefsLastUsed;
final long alarmInterval;
if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS)
alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS)
alarmInterval = AlarmManager.INTERVAL_HOUR;
else
alarmInterval = AlarmManager.INTERVAL_HALF_DAY;
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, alarmInterval, alarmIntent);
}
else
{
alarmManager.cancel(alarmIntent);
}
}
}
| true | true | public void onReceive(final Context context, final Intent intent)
{
Log.i(TAG, "got broadcast intent: " + intent);
// other app got replaced
if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED) && !intent.getDataString().equals(context.getPackageName()))
return;
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final boolean prefsAutosync = prefs.getBoolean(Constants.PREFS_KEY_AUTOSYNC, true);
final long prefsLastUsed = prefs.getLong(Constants.PREFS_KEY_LAST_USED, 0);
// determine power connected state
final Intent batteryChanged = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
final int batteryStatus = batteryChanged.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isPowerConnected = batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING || batteryStatus == BatteryManager.BATTERY_STATUS_FULL;
final boolean running = prefsAutosync && isPowerConnected;
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Intent serviceIntent = new Intent(BlockchainService.ACTION_HOLD_WIFI_LOCK, null, context, BlockchainServiceImpl.class);
final PendingIntent alarmIntent = PendingIntent.getService(context, 0, serviceIntent, 0);
if (running)
{
context.startService(serviceIntent);
final long now = System.currentTimeMillis();
final long lastUsedAgo = now - prefsLastUsed;
final long alarmInterval;
if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS)
alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS)
alarmInterval = AlarmManager.INTERVAL_HOUR;
else
alarmInterval = AlarmManager.INTERVAL_HALF_DAY;
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, alarmInterval, alarmIntent);
}
else
{
alarmManager.cancel(alarmIntent);
}
}
| public void onReceive(final Context context, final Intent intent)
{
Log.i(TAG, "got broadcast intent: " + intent);
// other app got replaced
if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED) && !intent.getDataString().equals("package:" + context.getPackageName()))
return;
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final boolean prefsAutosync = prefs.getBoolean(Constants.PREFS_KEY_AUTOSYNC, true);
final long prefsLastUsed = prefs.getLong(Constants.PREFS_KEY_LAST_USED, 0);
// determine power connected state
final Intent batteryChanged = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
final int batteryStatus = batteryChanged.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isPowerConnected = batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING || batteryStatus == BatteryManager.BATTERY_STATUS_FULL;
final boolean running = prefsAutosync && isPowerConnected;
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Intent serviceIntent = new Intent(BlockchainService.ACTION_HOLD_WIFI_LOCK, null, context, BlockchainServiceImpl.class);
final PendingIntent alarmIntent = PendingIntent.getService(context, 0, serviceIntent, 0);
if (running)
{
context.startService(serviceIntent);
final long now = System.currentTimeMillis();
final long lastUsedAgo = now - prefsLastUsed;
final long alarmInterval;
if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS)
alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS)
alarmInterval = AlarmManager.INTERVAL_HOUR;
else
alarmInterval = AlarmManager.INTERVAL_HALF_DAY;
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, alarmInterval, alarmIntent);
}
else
{
alarmManager.cancel(alarmIntent);
}
}
|
diff --git a/bundles/org.savara.bpmn2/src/main/java/org/savara/bpmn2/internal/generation/process/components/ParallelActivity.java b/bundles/org.savara.bpmn2/src/main/java/org/savara/bpmn2/internal/generation/process/components/ParallelActivity.java
index 96bce28..86ea5be 100644
--- a/bundles/org.savara.bpmn2/src/main/java/org/savara/bpmn2/internal/generation/process/components/ParallelActivity.java
+++ b/bundles/org.savara.bpmn2/src/main/java/org/savara/bpmn2/internal/generation/process/components/ParallelActivity.java
@@ -1,290 +1,290 @@
/*
* Copyright 2005-7 Pi4 Technologies Ltd
*
* 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.
*
*
* Change History:
* Jan 25, 2007 : Initial version created by gary
*/
package org.savara.bpmn2.internal.generation.process.components;
import org.savara.bpmn2.internal.generation.process.BPMN2GenerationException;
import org.scribble.protocol.model.Parallel;
/**
* This class represents a parallel grouping of states within a
* UML state machine.
*
*/
public class ParallelActivity extends AbstractBPMNActivity {
/**
* This constructor initializes the parallel state.
*
* @param parallel The parallel
* @param parent The parent BPMN state
* @param model The BPMN model
*/
public ParallelActivity(Parallel parallel, BPMNActivity parent,
org.savara.bpmn2.internal.generation.process.BPMN2ModelFactory model,
org.savara.bpmn2.internal.generation.process.BPMN2NotationFactory notation)
throws BPMN2GenerationException {
super(parent, model, notation);
initialize(parallel);
}
/**
* This method performs the initialization of the
* parallel state.
*
* @param elem The parallel
* @throws BPMN2GenerationException Failed to initialize
*/
protected void initialize(Parallel elem) throws BPMN2GenerationException {
// Get region
/*
Activity region=getTopLevelActivity();
// Create parallel state
ActivityNode parallelState = region.createNode(null,
UMLPackage.eINSTANCE.getForkNode());
parallelState.getInPartitions().add(getActivityPartition());
*/
Object parallelState=getModelFactory().createANDGateway(getContainer());
m_forkState = new JunctionActivity(parallelState, this,
getModelFactory(), getNotationFactory());
// Create join state
/*
ActivityNode joinState = region.createNode(null,
UMLPackage.eINSTANCE.getJoinNode());
joinState.getInPartitions().add(getActivityPartition());
*/
Object joinState=getModelFactory().createANDGateway(getContainer());
m_joinState = new JunctionActivity(joinState, this,
getModelFactory(), getNotationFactory());
}
/**
* This method indicates that the UML state for the
* child nodes is complete.
*
*/
public void childrenComplete() {
if (m_completed == false) {
int width=m_forkState.getWidth()+m_joinState.getWidth()+
(2 * HORIZONTAL_GAP);
int height=0;
// Move the junction state to the end of the list
if (getChildStates().remove(m_joinState)) {
getChildStates().add(m_joinState);
}
// Join the child state vertex with transitions
int maxwidth=0;
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity umls=(BPMNActivity)getChildStates().get(i);
height += (umls.getHeight()+VERTICAL_GAP);
if (umls.getWidth() > maxwidth) {
maxwidth = umls.getWidth();
}
umls.transitionFrom(m_forkState, null);
// Check if state is a junction
Object endNode=umls.getEndNode();
/* Do not remove endpoint junctions from
* parallel elements, as this can cause issues
* with layout
if (getModelFactory().isJoin(endNode) || // instanceof org.eclipse.uml2.uml.MergeNode ||
getModelFactory().isTerminal(endNode)) { // instanceof org.eclipse.uml2.uml.FlowFinalNode) {
// Move the incoming transitions from the junction
// to the next state
java.util.List list=getModelFactory().getInboundControlLinks(endNode);
for (int j=list.size()-1; j >= 0; j--) {
Object transition=list.get(j);
getModelFactory().setTarget(transition,
m_joinState.getStartNode());
}
// Remove the junction
getModelFactory().delete(endNode);
} else {
*/
m_joinState.transitionFrom(umls, null);
//}
}
width += maxwidth;
if (height >= HORIZONTAL_GAP) {
height -= HORIZONTAL_GAP;
}
if (height < m_forkState.getHeight()) {
height = m_forkState.getHeight();
}
if (height < m_joinState.getHeight()) {
height = m_joinState.getHeight();
}
setWidth(width);
setHeight(height);
adjustWidth(width);
m_completed = true;
}
}
/**
* This method returns the start node for the activites
* represented by this UML activity implementation.
*
* @return The starting node
*/
public Object getStartNode() {
return(m_forkState.getStartNode());
}
/**
* This method returns the end node for the activities
* represented by this UML activity implementation.
*
* @return The ending node
*/
public Object getEndNode() {
return(m_joinState.getEndNode());
}
/**
* This method returns the start state.
*
* @return The start state
*/
public BPMNActivity getStartState() {
return(m_forkState);
}
/**
* This method returns the end state.
*
* @return The end state
*/
public BPMNActivity getEndState() {
return(m_joinState);
}
public void adjustWidth(int width) {
int extrawidth=m_forkState.getWidth()+m_joinState.getWidth()+
(2 * HORIZONTAL_GAP);
setWidth(width);
// Adjust child widths
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity umls=(BPMNActivity)getChildStates().get(i);
umls.adjustWidth(width-extrawidth);
}
}
public void calculatePosition(int x, int y) {
int cury=y;
int midx=x+(getWidth()/2);
int midy=y+(getHeight()/2);
setX(x);
setY(y);
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
act.calculatePosition(midx-(act.getWidth()/2), cury);
//midy-(act.getHeight()/2));
cury += (act.getHeight()+VERTICAL_GAP);
}
m_forkState.calculatePosition(x, midy-(m_forkState.getHeight()/2));
m_joinState.calculatePosition(x+getWidth()-
m_joinState.getWidth(), midy-(m_joinState.getHeight()/2));
}
public void draw(Object parent) {
// Construct notation
for (int i=0; i < getChildStates().size(); i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
act.draw(parent);
}
// Construct sequence links
for (int i=1; i < getChildStates().size(); i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
if (shouldConnect(act)) {
getStartState().transitionTo(act, null, parent);
}
- if (act != getStartState()) {
+ if (act != m_joinState) {
act.getEndState().transitionTo(m_joinState, null, parent);
}
}
}
protected boolean shouldConnect(BPMNActivity act) {
boolean ret=act != m_joinState;
if (ret && act instanceof JoinActivity) {
ret = false;
}
if (ret && act instanceof SequenceActivity &&
((SequenceActivity)act).getChildStates().size() > 0 &&
((SequenceActivity)act).getChildStates().get(0) instanceof JoinActivity) {
ret = false;
}
return(ret);
}
/*
public void transitionTo(BPMNActivity toNode, String expression, Object parent) {
for (Object act : getChildStates()) {
Object link=getModelFactory().createControlLink(getContainer(),
getEndNode(), toNode.getStartNode(), expression);
getNotationFactory().createSequenceLink(getModelFactory(), link, parent);
}
}
*/
private boolean m_completed=false;
private BPMNActivity m_forkState=null;
private BPMNActivity m_joinState=null;
}
| true | true | public void childrenComplete() {
if (m_completed == false) {
int width=m_forkState.getWidth()+m_joinState.getWidth()+
(2 * HORIZONTAL_GAP);
int height=0;
// Move the junction state to the end of the list
if (getChildStates().remove(m_joinState)) {
getChildStates().add(m_joinState);
}
// Join the child state vertex with transitions
int maxwidth=0;
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity umls=(BPMNActivity)getChildStates().get(i);
height += (umls.getHeight()+VERTICAL_GAP);
if (umls.getWidth() > maxwidth) {
maxwidth = umls.getWidth();
}
umls.transitionFrom(m_forkState, null);
// Check if state is a junction
Object endNode=umls.getEndNode();
/* Do not remove endpoint junctions from
* parallel elements, as this can cause issues
* with layout
if (getModelFactory().isJoin(endNode) || // instanceof org.eclipse.uml2.uml.MergeNode ||
getModelFactory().isTerminal(endNode)) { // instanceof org.eclipse.uml2.uml.FlowFinalNode) {
// Move the incoming transitions from the junction
// to the next state
java.util.List list=getModelFactory().getInboundControlLinks(endNode);
for (int j=list.size()-1; j >= 0; j--) {
Object transition=list.get(j);
getModelFactory().setTarget(transition,
m_joinState.getStartNode());
}
// Remove the junction
getModelFactory().delete(endNode);
} else {
*/
m_joinState.transitionFrom(umls, null);
//}
}
width += maxwidth;
if (height >= HORIZONTAL_GAP) {
height -= HORIZONTAL_GAP;
}
if (height < m_forkState.getHeight()) {
height = m_forkState.getHeight();
}
if (height < m_joinState.getHeight()) {
height = m_joinState.getHeight();
}
setWidth(width);
setHeight(height);
adjustWidth(width);
m_completed = true;
}
}
/**
* This method returns the start node for the activites
* represented by this UML activity implementation.
*
* @return The starting node
*/
public Object getStartNode() {
return(m_forkState.getStartNode());
}
/**
* This method returns the end node for the activities
* represented by this UML activity implementation.
*
* @return The ending node
*/
public Object getEndNode() {
return(m_joinState.getEndNode());
}
/**
* This method returns the start state.
*
* @return The start state
*/
public BPMNActivity getStartState() {
return(m_forkState);
}
/**
* This method returns the end state.
*
* @return The end state
*/
public BPMNActivity getEndState() {
return(m_joinState);
}
public void adjustWidth(int width) {
int extrawidth=m_forkState.getWidth()+m_joinState.getWidth()+
(2 * HORIZONTAL_GAP);
setWidth(width);
// Adjust child widths
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity umls=(BPMNActivity)getChildStates().get(i);
umls.adjustWidth(width-extrawidth);
}
}
public void calculatePosition(int x, int y) {
int cury=y;
int midx=x+(getWidth()/2);
int midy=y+(getHeight()/2);
setX(x);
setY(y);
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
act.calculatePosition(midx-(act.getWidth()/2), cury);
//midy-(act.getHeight()/2));
cury += (act.getHeight()+VERTICAL_GAP);
}
m_forkState.calculatePosition(x, midy-(m_forkState.getHeight()/2));
m_joinState.calculatePosition(x+getWidth()-
m_joinState.getWidth(), midy-(m_joinState.getHeight()/2));
}
public void draw(Object parent) {
// Construct notation
for (int i=0; i < getChildStates().size(); i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
act.draw(parent);
}
// Construct sequence links
for (int i=1; i < getChildStates().size(); i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
if (shouldConnect(act)) {
getStartState().transitionTo(act, null, parent);
}
if (act != getStartState()) {
act.getEndState().transitionTo(m_joinState, null, parent);
}
}
}
protected boolean shouldConnect(BPMNActivity act) {
boolean ret=act != m_joinState;
if (ret && act instanceof JoinActivity) {
ret = false;
}
if (ret && act instanceof SequenceActivity &&
((SequenceActivity)act).getChildStates().size() > 0 &&
((SequenceActivity)act).getChildStates().get(0) instanceof JoinActivity) {
ret = false;
}
return(ret);
}
/*
public void transitionTo(BPMNActivity toNode, String expression, Object parent) {
for (Object act : getChildStates()) {
Object link=getModelFactory().createControlLink(getContainer(),
getEndNode(), toNode.getStartNode(), expression);
getNotationFactory().createSequenceLink(getModelFactory(), link, parent);
}
}
*/
private boolean m_completed=false;
private BPMNActivity m_forkState=null;
private BPMNActivity m_joinState=null;
}
| public void childrenComplete() {
if (m_completed == false) {
int width=m_forkState.getWidth()+m_joinState.getWidth()+
(2 * HORIZONTAL_GAP);
int height=0;
// Move the junction state to the end of the list
if (getChildStates().remove(m_joinState)) {
getChildStates().add(m_joinState);
}
// Join the child state vertex with transitions
int maxwidth=0;
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity umls=(BPMNActivity)getChildStates().get(i);
height += (umls.getHeight()+VERTICAL_GAP);
if (umls.getWidth() > maxwidth) {
maxwidth = umls.getWidth();
}
umls.transitionFrom(m_forkState, null);
// Check if state is a junction
Object endNode=umls.getEndNode();
/* Do not remove endpoint junctions from
* parallel elements, as this can cause issues
* with layout
if (getModelFactory().isJoin(endNode) || // instanceof org.eclipse.uml2.uml.MergeNode ||
getModelFactory().isTerminal(endNode)) { // instanceof org.eclipse.uml2.uml.FlowFinalNode) {
// Move the incoming transitions from the junction
// to the next state
java.util.List list=getModelFactory().getInboundControlLinks(endNode);
for (int j=list.size()-1; j >= 0; j--) {
Object transition=list.get(j);
getModelFactory().setTarget(transition,
m_joinState.getStartNode());
}
// Remove the junction
getModelFactory().delete(endNode);
} else {
*/
m_joinState.transitionFrom(umls, null);
//}
}
width += maxwidth;
if (height >= HORIZONTAL_GAP) {
height -= HORIZONTAL_GAP;
}
if (height < m_forkState.getHeight()) {
height = m_forkState.getHeight();
}
if (height < m_joinState.getHeight()) {
height = m_joinState.getHeight();
}
setWidth(width);
setHeight(height);
adjustWidth(width);
m_completed = true;
}
}
/**
* This method returns the start node for the activites
* represented by this UML activity implementation.
*
* @return The starting node
*/
public Object getStartNode() {
return(m_forkState.getStartNode());
}
/**
* This method returns the end node for the activities
* represented by this UML activity implementation.
*
* @return The ending node
*/
public Object getEndNode() {
return(m_joinState.getEndNode());
}
/**
* This method returns the start state.
*
* @return The start state
*/
public BPMNActivity getStartState() {
return(m_forkState);
}
/**
* This method returns the end state.
*
* @return The end state
*/
public BPMNActivity getEndState() {
return(m_joinState);
}
public void adjustWidth(int width) {
int extrawidth=m_forkState.getWidth()+m_joinState.getWidth()+
(2 * HORIZONTAL_GAP);
setWidth(width);
// Adjust child widths
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity umls=(BPMNActivity)getChildStates().get(i);
umls.adjustWidth(width-extrawidth);
}
}
public void calculatePosition(int x, int y) {
int cury=y;
int midx=x+(getWidth()/2);
int midy=y+(getHeight()/2);
setX(x);
setY(y);
for (int i=1; i < getChildStates().size()-1; i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
act.calculatePosition(midx-(act.getWidth()/2), cury);
//midy-(act.getHeight()/2));
cury += (act.getHeight()+VERTICAL_GAP);
}
m_forkState.calculatePosition(x, midy-(m_forkState.getHeight()/2));
m_joinState.calculatePosition(x+getWidth()-
m_joinState.getWidth(), midy-(m_joinState.getHeight()/2));
}
public void draw(Object parent) {
// Construct notation
for (int i=0; i < getChildStates().size(); i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
act.draw(parent);
}
// Construct sequence links
for (int i=1; i < getChildStates().size(); i++) {
BPMNActivity act=(BPMNActivity)getChildStates().get(i);
if (shouldConnect(act)) {
getStartState().transitionTo(act, null, parent);
}
if (act != m_joinState) {
act.getEndState().transitionTo(m_joinState, null, parent);
}
}
}
protected boolean shouldConnect(BPMNActivity act) {
boolean ret=act != m_joinState;
if (ret && act instanceof JoinActivity) {
ret = false;
}
if (ret && act instanceof SequenceActivity &&
((SequenceActivity)act).getChildStates().size() > 0 &&
((SequenceActivity)act).getChildStates().get(0) instanceof JoinActivity) {
ret = false;
}
return(ret);
}
/*
public void transitionTo(BPMNActivity toNode, String expression, Object parent) {
for (Object act : getChildStates()) {
Object link=getModelFactory().createControlLink(getContainer(),
getEndNode(), toNode.getStartNode(), expression);
getNotationFactory().createSequenceLink(getModelFactory(), link, parent);
}
}
*/
private boolean m_completed=false;
private BPMNActivity m_forkState=null;
private BPMNActivity m_joinState=null;
}
|
diff --git a/src/org/apache/xerces/dom/DeferredDocumentImpl.java b/src/org/apache/xerces/dom/DeferredDocumentImpl.java
index d82d519a9..27f235490 100644
--- a/src/org/apache/xerces/dom/DeferredDocumentImpl.java
+++ b/src/org/apache/xerces/dom/DeferredDocumentImpl.java
@@ -1,1572 +1,1572 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import java.util.Vector;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.utils.StringPool;
import org.w3c.dom.*;
/**
* The Document interface represents the entire HTML or XML document.
* Conceptually, it is the root of the document tree, and provides the
* primary access to the document's data.
* <P>
* Since elements, text nodes, comments, processing instructions,
* etc. cannot exist outside the context of a Document, the Document
* interface also contains the factory methods needed to create these
* objects. The Node objects created have a ownerDocument attribute
* which associates them with the Document within whose context they
* were created.
*
* @version
* @since PR-DOM-Level-1-19980818.
*/
public class DeferredDocumentImpl
extends DocumentImpl
implements DeferredNode {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = 5186323580749626857L;
// debugging
/** To include code for printing the ref count tables. */
private static final boolean DEBUG_PRINT_REF_COUNTS = false;
/** To include code for printing the internal tables. */
private static final boolean DEBUG_PRINT_TABLES = false;
/** To debug identifiers set to true and recompile. */
private static final boolean DEBUG_IDS = false;
// protected
/** Chunk shift. */
protected static final int CHUNK_SHIFT = 11; // 2^11 = 2k
/** Chunk size. */
protected static final int CHUNK_SIZE = (1 << CHUNK_SHIFT);
/** Chunk mask. */
protected static final int CHUNK_MASK = CHUNK_SIZE - 1;
/** Initial chunk size. */
protected static final int INITIAL_CHUNK_COUNT = (1 << (16 - CHUNK_SHIFT)); // 2^16 = 64k
//
// Data
//
// lazy-eval information
/** Node count. */
protected transient int fNodeCount = 0;
/** Node types. */
protected transient int fNodeType[][];
/** Node names. */
protected transient int fNodeName[][];
/** Node values. */
protected transient int fNodeValue[][];
/** Node parents. */
protected transient int fNodeParent[][];
/** Node first children. */
protected transient int fNodeFirstChild[][];
/** Node next siblings. */
protected transient int fNodeNextSib[][];
/** Identifier count. */
protected transient int fIdCount;
/** Identifier name indexes. */
protected transient int fIdName[];
/** Identifier element indexes. */
protected transient int fIdElement[];
/** String pool cache. */
protected transient StringPool fStringPool;
/** DOM2: For namespace support in the deferred case.
*/
// Implementation Note: The deferred element and attribute must know how to
// interpret the int representing the qname.
protected boolean fNamespacesEnabled = false;
//
// Constructors
//
/**
* NON-DOM: Actually creating a Document is outside the DOM's spec,
* since it has to operate in terms of a particular implementation.
*/
public DeferredDocumentImpl(StringPool stringPool) {
this(stringPool, false);
} // <init>(ParserState)
/**
* NON-DOM: Actually creating a Document is outside the DOM's spec,
* since it has to operate in terms of a particular implementation.
*/
public DeferredDocumentImpl(StringPool stringPool, boolean namespacesEnabled) {
this(stringPool, namespacesEnabled, false);
} // <init>(ParserState,boolean)
/** Experimental constructor. */
public DeferredDocumentImpl(StringPool stringPool,
boolean namespaces, boolean grammarAccess) {
super(grammarAccess);
fStringPool = stringPool;
syncData = true;
syncChildren = true;
fNamespacesEnabled = namespaces;
} // <init>(StringPool,boolean,boolean)
//
// Public methods
//
/** Returns the cached parser.getNamespaces() value.*/
boolean getNamespacesEnabled() {
return fNamespacesEnabled;
}
// internal factory methods
/** Creates a document node in the table. */
public int createDocument() {
int nodeIndex = createNode(Node.DOCUMENT_NODE);
return nodeIndex;
}
/** Creates a doctype. */
public int createDocumentType(int rootElementNameIndex, int publicId, int systemId) {
// create node
int nodeIndex = createNode(Node.DOCUMENT_TYPE_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
// added for DOM2: createDoctype factory method includes
// name, publicID, systemID
// create extra data node
int extraDataIndex = createNode((short)0); // node type unimportant
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
// save name, public id, system id
setChunkIndex(fNodeName, rootElementNameIndex, chunk, index);
setChunkIndex(fNodeValue, extraDataIndex, chunk, index);
setChunkIndex(fNodeName, publicId, echunk, eindex);
setChunkIndex(fNodeValue, systemId, echunk, eindex);
// return node index
return nodeIndex;
} // createDocumentType(int,int,int):int
public void setInternalSubset(int doctypeIndex, int subsetIndex) {
int chunk = doctypeIndex >> CHUNK_SHIFT;
int index = doctypeIndex & CHUNK_MASK;
int extraDataIndex = fNodeValue[chunk][index];
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
fNodeFirstChild[echunk][eindex] = subsetIndex;
}
/** Creates a notation in the table. */
public int createNotation(int notationName, int publicId, int systemId) throws Exception {
// create node
int nodeIndex = createNode(Node.NOTATION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
// create extra data node
int extraDataIndex = createNode((short)0); // node type unimportant
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
// save name, public id, system id, and notation name
setChunkIndex(fNodeName, notationName, chunk, index);
setChunkIndex(fNodeValue, extraDataIndex, chunk, index);
setChunkIndex(fNodeName, publicId, echunk, eindex);
setChunkIndex(fNodeValue, systemId, echunk, eindex);
// return node index
return nodeIndex;
} // createNotation(int,int,int):int
/** Creates an entity in the table. */
public int createEntity(int entityName, int publicId, int systemId, int notationName) throws Exception {
// create node
int nodeIndex = createNode(Node.ENTITY_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
// create extra data node
int extraDataIndex = createNode((short)0); // node type unimportant
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
// save name, public id, system id, and notation name
setChunkIndex(fNodeName, entityName, chunk, index);
setChunkIndex(fNodeValue, extraDataIndex, chunk, index);
setChunkIndex(fNodeName, publicId, echunk, eindex);
setChunkIndex(fNodeValue, systemId, echunk, eindex);
setChunkIndex(fNodeFirstChild, notationName, echunk, eindex);
// return node index
return nodeIndex;
} // createEntity(int,int,int,int):int
/** Creates an entity reference node in the table. */
public int createEntityReference(int nameIndex) throws Exception {
// create node
int nodeIndex = createNode(Node.ENTITY_REFERENCE_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkIndex(fNodeName, nameIndex, chunk, index);
// return node index
return nodeIndex;
} // createEntityReference(int):int
/** Creates an element node in the table. */
public int createElement(int elementNameIndex, XMLAttrList attrList, int attrListIndex) {
// create node
int elementNodeIndex = createNode(Node.ELEMENT_NODE);
int elementChunk = elementNodeIndex >> CHUNK_SHIFT;
int elementIndex = elementNodeIndex & CHUNK_MASK;
setChunkIndex(fNodeName, elementNameIndex, elementChunk, elementIndex);
// create attributes
if (attrListIndex != -1) {
int first = attrList.getFirstAttr(attrListIndex);
int lastAttrNodeIndex = -1;
int lastAttrChunk = -1;
int lastAttrIndex = -1;
for (int index = first;
index != -1;
index = attrList.getNextAttr(index)) {
// create attribute
int attrNodeIndex = createAttribute(attrList.getAttrName(index),
attrList.getAttValue(index),
attrList.isSpecified(index));
int attrChunk = attrNodeIndex >> CHUNK_SHIFT;
int attrIndex = attrNodeIndex & CHUNK_MASK;
setChunkIndex(fNodeParent, elementNodeIndex, attrChunk, attrIndex);
// add links
if (index == first) {
setChunkIndex(fNodeValue, attrNodeIndex, elementChunk, elementIndex);
}
else {
setChunkIndex(fNodeNextSib, attrNodeIndex, lastAttrChunk, lastAttrIndex);
}
// save last chunk and index
lastAttrNodeIndex = attrNodeIndex;
lastAttrChunk = attrChunk;
lastAttrIndex = attrIndex;
}
}
// return node index
return elementNodeIndex;
} // createElement(int,XMLAttrList,int):int
/** Creates an attributes in the table. */
public int createAttribute(int attrNameIndex, int attrValueIndex,
boolean specified) {
// create node
int nodeIndex = createNode(NodeImpl.ATTRIBUTE_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkIndex(fNodeName, attrNameIndex, chunk, index);
setChunkIndex(fNodeValue, specified ? 1 : 0, chunk, index);
// append value as text node
int textNodeIndex = createTextNode(attrValueIndex, false);
appendChild(nodeIndex, textNodeIndex);
// return node index
return nodeIndex;
} // createAttribute(int,int,boolean):int
/** Creates an element definition in the table. */
public int createElementDefinition(int elementNameIndex) {
// create node
int nodeIndex = createNode(NodeImpl.ELEMENT_DEFINITION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkIndex(fNodeName, elementNameIndex, chunk, index);
// return node index
return nodeIndex;
} // createElementDefinition(int):int
/** Creates a text node in the table. */
public int createTextNode(int dataIndex, boolean ignorableWhitespace) {
// create node
int nodeIndex = createNode(Node.TEXT_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkIndex(fNodeValue, dataIndex, chunk, index);
setChunkIndex(fNodeFirstChild, ignorableWhitespace ? 1 : 0, chunk, index);
// return node index
return nodeIndex;
} // createTextNode(int,boolean):int
/** Creates a CDATA section node in the table. */
public int createCDATASection(int dataIndex, boolean ignorableWhitespace) {
// create node
int nodeIndex = createNode(Node.CDATA_SECTION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkIndex(fNodeValue, dataIndex, chunk, index);
setChunkIndex(fNodeFirstChild, ignorableWhitespace ? 1 : 0, chunk, index);
// return node index
return nodeIndex;
} // createCDATASection(int,boolean):int
/** Creates a processing instruction node in the table. */
public int createProcessingInstruction(int targetIndex, int dataIndex) {
// create node
int nodeIndex = createNode(Node.PROCESSING_INSTRUCTION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkIndex(fNodeName, targetIndex, chunk, index);
setChunkIndex(fNodeValue, dataIndex, chunk, index);
// return node index
return nodeIndex;
} // createProcessingInstruction(int,int):int
/** Creates a comment node in the table. */
public int createComment(int dataIndex) {
// create node
int nodeIndex = createNode(Node.COMMENT_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkIndex(fNodeValue, dataIndex, chunk, index);
// return node index
return nodeIndex;
} // createComment(int):int
/** Appends a child to the specified parent in the table. */
public void appendChild(int parentIndex, int childIndex) {
// append parent index
int pchunk = parentIndex >> CHUNK_SHIFT;
int pindex = parentIndex & CHUNK_MASK;
int cchunk = childIndex >> CHUNK_SHIFT;
int cindex = childIndex & CHUNK_MASK;
setChunkIndex(fNodeParent, parentIndex, cchunk, cindex);
// look for last child
int prev = -1;
int index = getChunkIndex(fNodeFirstChild, pchunk, pindex);
while (index != -1) {
prev = index;
int nextIndex = getChunkIndex(fNodeNextSib, index >> CHUNK_SHIFT, index & CHUNK_MASK);
if (nextIndex == -1) {
break;
}
index = nextIndex;
}
// first child
if (prev == -1) {
setChunkIndex(fNodeFirstChild, childIndex, pchunk, pindex);
}
// last child
else {
int chnk = prev >> CHUNK_SHIFT;
int indx = prev & CHUNK_MASK;
setChunkIndex(fNodeNextSib, childIndex, chnk, indx);
}
} // appendChild(int,int)
/** Adds an attribute node to the specified element. */
public int setAttributeNode(int elemIndex, int attrIndex) {
int echunk = elemIndex >> CHUNK_SHIFT;
int eindex = elemIndex & CHUNK_MASK;
int achunk = attrIndex >> CHUNK_SHIFT;
int aindex = attrIndex & CHUNK_MASK;
// see if this attribute is already here
String attrName = fStringPool.toString(getChunkIndex(fNodeName, achunk, aindex));
int oldAttrIndex = getChunkIndex(fNodeValue, echunk, eindex);
int prevIndex = -1;
int oachunk = -1;
int oaindex = -1;
while (oldAttrIndex != -1) {
oachunk = oldAttrIndex >> CHUNK_SHIFT;
oaindex = oldAttrIndex & CHUNK_MASK;
String oldAttrName = fStringPool.toString(getChunkIndex(fNodeName, oachunk, oaindex));
if (oldAttrName.equals(attrName)) {
break;
}
prevIndex = oldAttrIndex;
oldAttrIndex = getChunkIndex(fNodeNextSib, oachunk, oaindex);
}
// remove old attribute
if (oldAttrIndex != -1) {
// patch links
int nextIndex = getChunkIndex(fNodeNextSib, oachunk, oaindex);
if (prevIndex == -1) {
setChunkIndex(fNodeValue, nextIndex, echunk, eindex);
}
else {
int pchunk = prevIndex >> CHUNK_SHIFT;
int pindex = prevIndex & CHUNK_MASK;
setChunkIndex(fNodeNextSib, nextIndex, pchunk, pindex);
}
// remove connections to siblings
clearChunkIndex(fNodeType, oachunk, oaindex);
clearChunkIndex(fNodeName, oachunk, oaindex);
clearChunkIndex(fNodeValue, oachunk, oaindex);
clearChunkIndex(fNodeParent, oachunk, oaindex);
clearChunkIndex(fNodeNextSib, oachunk, oaindex);
int attrTextIndex = clearChunkIndex(fNodeFirstChild, oachunk, oaindex);
int atchunk = attrTextIndex >> CHUNK_SHIFT;
int atindex = attrTextIndex & CHUNK_MASK;
clearChunkIndex(fNodeType, atchunk, atindex);
clearChunkIndex(fNodeValue, atchunk, atindex);
clearChunkIndex(fNodeParent, atchunk, atindex);
clearChunkIndex(fNodeFirstChild, atchunk, atindex);
}
// add new attribute
int nextIndex = getChunkIndex(fNodeValue, echunk, eindex);
setChunkIndex(fNodeValue, attrIndex, echunk, eindex);
// return
return oldAttrIndex;
} // setAttributeNode(int,int):int
/** Inserts a child before the specified node in the table. */
public int insertBefore(int parentIndex, int newChildIndex, int refChildIndex) {
if (refChildIndex == -1) {
appendChild(parentIndex, newChildIndex);
return newChildIndex;
}
int pchunk = parentIndex >> CHUNK_SHIFT;
int pindex = parentIndex & CHUNK_MASK;
int nchunk = newChildIndex >> CHUNK_SHIFT;
int nindex = newChildIndex & CHUNK_MASK;
int rchunk = refChildIndex >> CHUNK_SHIFT;
int rindex = refChildIndex & CHUNK_MASK;
// 1) if ref.parent.first = ref then
// begin
// ref.parent.first := new;
// end;
int firstIndex = getChunkIndex(fNodeFirstChild, pchunk, pindex);
if (firstIndex == refChildIndex) {
setChunkIndex(fNodeFirstChild, newChildIndex, pchunk, pindex);
}
// 2) if ref.prev != null then
// begin
// ref.prev.next := new;
// end;
int prevIndex = -1;
for (int index = getChunkIndex(fNodeFirstChild, pchunk, pindex);
index != -1;
index = getChunkIndex(fNodeNextSib, index >> CHUNK_SHIFT, index & CHUNK_MASK)) {
if (index == refChildIndex) {
break;
}
prevIndex = index;
}
if (prevIndex != -1) {
int chunk = prevIndex >> CHUNK_SHIFT;
int index = prevIndex & CHUNK_MASK;
setChunkIndex(fNodeNextSib, newChildIndex, chunk, index);
}
// 3) new.next := ref;
setChunkIndex(fNodeNextSib, refChildIndex, nchunk, nindex);
return newChildIndex;
} // insertBefore(int,int,int):int
/** Sets the first child of the parentIndex to childIndex. */
public void setAsFirstChild(int parentIndex, int childIndex) {
int pchunk = parentIndex >> CHUNK_SHIFT;
int pindex = parentIndex & CHUNK_MASK;
int chunk = childIndex >> CHUNK_SHIFT;
int index = childIndex & CHUNK_MASK;
setChunkIndex(fNodeFirstChild, childIndex, pchunk, pindex);
int next = childIndex;
while (next != -1) {
childIndex = next;
next = getChunkIndex(fNodeNextSib, chunk, index);
chunk = next >> CHUNK_SHIFT;
index = next & CHUNK_MASK;
}
} // setAsFirstChild(int,int)
// methods used when objects are "fluffed-up"
/** Returns the parent node of the given node. */
public int getParentNode(int nodeIndex) {
// REVISIT: should this be "public"? -Ac
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return getChunkIndex(fNodeParent, chunk, index);
} // getParentNode(int):int
/** Returns the first child of the given node. */
public int getFirstChild(int nodeIndex) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return clearChunkIndex(fNodeFirstChild, chunk, index);
} // getFirstChild(int):int
/** Returns the next sibling of the given node.
* This is post-normalization of Text Nodes.
*/
public int getNextSibling(int nodeIndex) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
nodeIndex = clearChunkIndex(fNodeNextSib, chunk, index);
while (nodeIndex != -1 && getChunkIndex(fNodeType, chunk, index) == Node.TEXT_NODE) {
nodeIndex = getChunkIndex(fNodeNextSib, chunk, index);
chunk = nodeIndex >> CHUNK_SHIFT;
index = nodeIndex & CHUNK_MASK;
}
return nodeIndex;
} // getNextSibling(int):int
/**
* Returns the <i>real</i> next sibling of the given node,
* directly from the data structures. Used by TextImpl#getNodeValue()
* to normalize values.
*/
public int getRealNextSibling(int nodeIndex) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return clearChunkIndex(fNodeNextSib, chunk, index);
} // getReadNextSibling(int):int
/**
* Returns the index of the element definition in the table
* with the specified name index, or -1 if no such definition
* exists.
*/
public int lookupElementDefinition(int elementNameIndex) {
if (fNodeCount > 1) {
// find doctype
int docTypeIndex = -1;
int nchunk = 0;
int nindex = 0;
for (int index = getChunkIndex(fNodeFirstChild, nchunk, nindex);
index != -1;
index = getChunkIndex(fNodeNextSib, nchunk, nindex)) {
nchunk = index >> CHUNK_SHIFT;
nindex = index & CHUNK_MASK;
if (getChunkIndex(fNodeType, nchunk, nindex) == Node.DOCUMENT_TYPE_NODE) {
docTypeIndex = index;
break;
}
}
// find element definition
if (docTypeIndex == -1) {
return -1;
}
nchunk = docTypeIndex >> CHUNK_SHIFT;
nindex = docTypeIndex & CHUNK_MASK;
for (int index = getChunkIndex(fNodeFirstChild, nchunk, nindex);
index != -1;
index = getChunkIndex(fNodeNextSib, nchunk, nindex)) {
nchunk = index >> CHUNK_SHIFT;
nindex = index & CHUNK_MASK;
if (getChunkIndex(fNodeName, nchunk, nindex) == elementNameIndex) {
return index;
}
}
}
return -1;
} // lookupElementDefinition(int):int
/** Instantiates the requested node object. */
public DeferredNode getNodeObject(int nodeIndex) {
// is there anything to do?
if (nodeIndex == -1) {
return null;
}
// get node type
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
int type = clearChunkIndex(fNodeType, chunk, index);
clearChunkIndex(fNodeParent, chunk, index);
// create new node
DeferredNode node = null;
switch (type) {
//
// Standard DOM node types
//
case Node.ATTRIBUTE_NODE: {
node = new DeferredAttrImpl(this, nodeIndex);
break;
}
case Node.CDATA_SECTION_NODE: {
node = new DeferredCDATASectionImpl(this, nodeIndex);
break;
}
case Node.COMMENT_NODE: {
node = new DeferredCommentImpl(this, nodeIndex);
break;
}
// NOTE: Document fragments can never be "fast".
//
// The parser will never ask to create a document
// fragment during the parse. Document fragments
// are used by the application *after* the parse.
//
// case Node.DOCUMENT_FRAGMENT_NODE: { break; }
case Node.DOCUMENT_NODE: {
// this node is never "fast"
node = this;
break;
}
case Node.DOCUMENT_TYPE_NODE: {
node = new DeferredDocumentTypeImpl(this, nodeIndex);
// save the doctype node
docType = (DocumentTypeImpl)node;
break;
}
case Node.ELEMENT_NODE: {
if (DEBUG_IDS) {
System.out.println("getNodeObject(ELEMENT_NODE): "+nodeIndex);
}
// create node
node = new DeferredElementImpl(this, nodeIndex);
// save the document element node
if (docElement == null) {
docElement = (ElementImpl)node;
}
// check to see if this element needs to be
// registered for its ID attributes
if (fIdElement != null) {
int idIndex = DeferredDocumentImpl.binarySearch(fIdElement, 0, fIdCount, nodeIndex);
while (idIndex != -1) {
if (DEBUG_IDS) {
System.out.println(" id index: "+idIndex);
System.out.println(" fIdName["+idIndex+
"]: "+fIdName[idIndex]);
}
// register ID
int nameIndex = fIdName[idIndex];
if (nameIndex != -1) {
String name = fStringPool.toString(nameIndex);
if (DEBUG_IDS) {
System.out.println(" name: "+name);
System.out.print("getNodeObject()#");
}
putIdentifier0(name, (Element)node);
fIdName[idIndex] = -1;
}
// continue if there are more IDs for
// this element
- if (idIndex < fIdCount &&
+ if (idIndex + 1 < fIdCount &&
fIdElement[idIndex + 1] == nodeIndex) {
idIndex++;
}
else {
idIndex = -1;
}
}
}
break;
}
case Node.ENTITY_NODE: {
node = new DeferredEntityImpl(this, nodeIndex);
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = new DeferredEntityReferenceImpl(this, nodeIndex);
break;
}
case Node.NOTATION_NODE: {
node = new DeferredNotationImpl(this, nodeIndex);
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = new DeferredProcessingInstructionImpl(this, nodeIndex);
break;
}
case Node.TEXT_NODE: {
node = new DeferredTextImpl(this, nodeIndex);
break;
}
//
// non-standard DOM node types
//
case NodeImpl.ELEMENT_DEFINITION_NODE: {
node = new DeferredElementDefinitionImpl(this, nodeIndex);
break;
}
default: {
throw new IllegalArgumentException("type: "+type);
}
} // switch node type
// store and return
if (node != null) {
return node;
}
// error
throw new IllegalArgumentException();
} // createNodeObject(int):Node
/** Returns the name of the given node. */
public String getNodeNameString(int nodeIndex) {
if (nodeIndex == -1) {
return null;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
int nameIndex = clearChunkIndex(fNodeName, chunk, index);
if (nameIndex == -1) {
return null;
}
return fStringPool.toString(nameIndex);
} // getNodeNameString(int):String
/** Returns the value of the given node. */
public String getNodeValueString(int nodeIndex) {
if (nodeIndex == -1) {
return null;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
int valueIndex = clearChunkIndex(fNodeValue, chunk, index);
if (valueIndex == -1) {
return null;
}
return fStringPool.toString(valueIndex);
} // getNodeValueString(int):String
/** Returns the real int name of the given node. */
public int getNodeName(int nodeIndex) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return clearChunkIndex(fNodeName, chunk, index);
} // getNodeName(int):int
/**
* Returns the real int value of the given node.
* Used by AttrImpl to store specified value (1 == true).
*/
public int getNodeValue(int nodeIndex) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return clearChunkIndex(fNodeValue, chunk, index);
} // getNodeValue(int):int
/** Returns the type of the given node. */
public short getNodeType(int nodeIndex) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return (short)clearChunkIndex(fNodeType, chunk, index);
} // getNodeType(int):int
// identifier maintenance
/** Registers an identifier name with a specified element node. */
public void putIdentifier(int nameIndex, int elementNodeIndex) {
if (DEBUG_IDS) {
System.out.println("putIdentifier("+nameIndex+", "+elementNodeIndex+')'+
" // "+
fStringPool.toString(nameIndex)+
", "+
fStringPool.toString(getChunkIndex(fNodeName, elementNodeIndex >> CHUNK_SHIFT, elementNodeIndex & CHUNK_MASK)));
}
// initialize arrays
if (fIdName == null) {
fIdName = new int[64];
fIdElement = new int[64];
}
// resize arrays
if (fIdCount == fIdName.length) {
int idName[] = new int[fIdCount * 2];
System.arraycopy(fIdName, 0, idName, 0, fIdCount);
fIdName = idName;
int idElement[] = new int[idName.length];
System.arraycopy(fIdElement, 0, idElement, 0, fIdCount);
fIdElement = idElement;
}
// store identifier
fIdName[fIdCount] = nameIndex;
fIdElement[fIdCount] = elementNodeIndex;
fIdCount++;
} // putIdentifier(int,int)
//
// DEBUG
//
/** Prints out the tables. */
public void print() {
if (DEBUG_PRINT_REF_COUNTS) {
System.out.print("num\t");
System.out.print("type\t");
System.out.print("name\t");
System.out.print("val\t");
System.out.print("par\t");
System.out.print("fch\t");
System.out.print("nsib");
System.out.println();
for (int i = 0; i < fNodeType.length; i++) {
if (fNodeType[i] != null) {
// separator
System.out.print("--------");
System.out.print("--------");
System.out.print("--------");
System.out.print("--------");
System.out.print("--------");
System.out.print("--------");
System.out.print("--------");
System.out.println();
// set count
System.out.print(i);
System.out.print('\t');
System.out.print(fNodeType[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeName[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeValue[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeParent[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeFirstChild[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeNextSib[i][CHUNK_SIZE]);
System.out.println();
// clear count
System.out.print(i);
System.out.print('\t');
System.out.print(fNodeType[i][CHUNK_SIZE + 1]);
System.out.print('\t');
System.out.print(fNodeName[i][CHUNK_SIZE + 1]);
System.out.print('\t');
System.out.print(fNodeValue[i][CHUNK_SIZE + 1]);
System.out.print('\t');
System.out.print(fNodeParent[i][CHUNK_SIZE + 1]);
System.out.print('\t');
System.out.print(fNodeFirstChild[i][CHUNK_SIZE + 1]);
System.out.print('\t');
System.out.print(fNodeNextSib[i][CHUNK_SIZE + 1]);
System.out.println();
}
}
}
if (DEBUG_PRINT_TABLES) {
// This assumes that the document is small
System.out.println("# start table");
for (int i = 0; i < fNodeCount; i++) {
int chunk = i >> CHUNK_SHIFT;
int index = i & CHUNK_MASK;
if (i % 10 == 0) {
System.out.print("num\t");
System.out.print("type\t");
System.out.print("name\t");
System.out.print("val\t");
System.out.print("par\t");
System.out.print("fch\t");
System.out.print("nsib");
System.out.println();
}
System.out.print(i);
System.out.print('\t');
System.out.print(getChunkIndex(fNodeType, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeName, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeValue, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeParent, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeFirstChild, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeNextSib, chunk, index));
/***
System.out.print(fNodeType[0][i]);
System.out.print('\t');
System.out.print(fNodeName[0][i]);
System.out.print('\t');
System.out.print(fNodeValue[0][i]);
System.out.print('\t');
System.out.print(fNodeParent[0][i]);
System.out.print('\t');
System.out.print(fNodeFirstChild[0][i]);
System.out.print('\t');
System.out.print(fNodeLastChild[0][i]);
System.out.print('\t');
System.out.print(fNodePrevSib[0][i]);
System.out.print('\t');
System.out.print(fNodeNextSib[0][i]);
/***/
System.out.println();
}
System.out.println("# end table");
}
} // print()
//
// DeferredNode methods
//
/** Returns the node index. */
public int getNodeIndex() {
return 0;
}
//
// Protected methods
//
/** access to string pool. */
protected StringPool getStringPool() {
return fStringPool;
}
/** Synchronizes the node's data. */
protected void synchronizeData() {
// no need to sync in the future
syncData = false;
// fluff up enough nodes to fill identifiers hash
if (fIdElement != null) {
// REVISIT: There has to be a more efficient way of
// doing this. But keep in mind that the
// tree can have been altered and re-ordered
// before all of the element nodes with ID
// attributes have been registered. For now
// this is reasonable and safe. -Ac
IntVector path = new IntVector();
for (int i = 0; i < fIdCount; i++) {
// ignore if it's already been registered
int elementNodeIndex = fIdElement[i];
int idNameIndex = fIdName[i];
if (idNameIndex == -1) {
continue;
}
// find path from this element to the root
path.removeAllElements();
int index = elementNodeIndex;
do {
path.addElement(index);
int pchunk = index >> CHUNK_SHIFT;
int pindex = index & CHUNK_MASK;
index = getChunkIndex(fNodeParent, pchunk, pindex);
} while (index != -1);
// Traverse path (backwards), fluffing the elements
// along the way. When this loop finishes, "place"
// will contain the reference to the element node
// we're interested in. -Ac
Node place = this;
for (int j = path.size() - 2; j >= 0; j--) {
index = path.elementAt(j);
Node child = place.getFirstChild();
while (child != null) {
if (child instanceof DeferredNode) {
int nodeIndex = ((DeferredNode)child).getNodeIndex();
if (nodeIndex == index) {
place = child;
break;
}
}
child = child.getNextSibling();
}
}
// register the element
Element element = (Element)place;
String name = fStringPool.toString(idNameIndex);
putIdentifier0(name, element);
fIdName[i] = -1;
// see if there are more IDs on this element
while (fIdElement[i + 1] == elementNodeIndex) {
name = fStringPool.toString(fIdName[++i]);
putIdentifier0(name, element);
}
}
} // if identifiers
} // synchronizeData()
/**
* Synchronizes the node's children with the internal structure.
* Fluffing the children at once solves a lot of work to keep
* the two structures in sync. The problem gets worse when
* editing the tree -- this makes it a lot easier.
*/
protected void synchronizeChildren() {
// no need to sync in the future
syncChildren = false;
getNodeType(0);
// create children and link them as siblings
NodeImpl last = null;
for (int index = getFirstChild(0);
index != -1;
index = getNextSibling(index)) {
NodeImpl node = (NodeImpl)getNodeObject(index);
if (last == null) {
firstChild = node;
}
else {
last.nextSibling = node;
}
node.parentNode = this;
node.previousSibling = last;
last = node;
// save doctype and document type
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE) {
docElement = (ElementImpl)node;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType = (DocumentTypeImpl)node;
}
}
if (last != null) {
lastChild = last;
}
} // synchronizeChildren()
// utility methods
/** Ensures that the internal tables are large enough. */
protected boolean ensureCapacity(int chunk, int index) {
// create buffers
if (fNodeType == null) {
fNodeType = new int[INITIAL_CHUNK_COUNT][];
fNodeName = new int[INITIAL_CHUNK_COUNT][];
fNodeValue = new int[INITIAL_CHUNK_COUNT][];
fNodeParent = new int[INITIAL_CHUNK_COUNT][];
fNodeFirstChild = new int[INITIAL_CHUNK_COUNT][];
fNodeNextSib = new int[INITIAL_CHUNK_COUNT][];
}
// return true if table is already big enough
try {
return fNodeType[chunk][index] != 0;
}
// resize the tables
catch (ArrayIndexOutOfBoundsException ex) {
int newsize = chunk * 2;
int[][] newArray = new int[newsize][];
System.arraycopy(fNodeType, 0, newArray, 0, chunk);
fNodeType = newArray;
newArray = new int[newsize][];
System.arraycopy(fNodeName, 0, newArray, 0, chunk);
fNodeName = newArray;
newArray = new int[newsize][];
System.arraycopy(fNodeValue, 0, newArray, 0, chunk);
fNodeValue = newArray;
newArray = new int[newsize][];
System.arraycopy(fNodeParent, 0, newArray, 0, chunk);
fNodeParent = newArray;
newArray = new int[newsize][];
System.arraycopy(fNodeFirstChild, 0, newArray, 0, chunk);
fNodeFirstChild = newArray;
newArray = new int[newsize][];
System.arraycopy(fNodeNextSib, 0, newArray, 0, chunk);
fNodeNextSib = newArray;
}
catch (NullPointerException ex) {
// ignore
}
// create chunks
createChunk(fNodeType, chunk);
createChunk(fNodeName, chunk);
createChunk(fNodeValue, chunk);
createChunk(fNodeParent, chunk);
createChunk(fNodeFirstChild, chunk);
createChunk(fNodeNextSib, chunk);
// success
return true;
} // ensureCapacity(int,int):boolean
/** Creates a node of the specified type. */
protected int createNode(short nodeType) {
// ensure tables are large enough
int chunk = fNodeCount >> CHUNK_SHIFT;
int index = fNodeCount & CHUNK_MASK;
ensureCapacity(chunk, index);
// initialize node
setChunkIndex(fNodeType, nodeType, chunk, index);
// return node index number
return fNodeCount++;
} // createNode(short):int
/**
* Performs a binary search for a target value in an array of
* values. The array of values must be in ascending sorted order
* before calling this method and all array values must be
* non-negative.
*
* @param values The array of values to search.
* @param start The starting offset of the search.
* @param end The ending offset of the search.
* @param target The target value.
*
* @return This function will return the <i>first</i> occurrence
* of the target value, or -1 if the target value cannot
* be found.
*/
protected static int binarySearch(final int values[],
int start, int end, int target) {
if (DEBUG_IDS) {
System.out.println("binarySearch(), target: "+target);
}
// look for target value
while (start <= end) {
// is this the one we're looking for?
int middle = (start + end) / 2;
int value = values[middle];
if (DEBUG_IDS) {
System.out.print(" value: "+value+", target: "+target+" // ");
print(values, start, end, middle, target);
}
if (value == target) {
while (middle > 0 && values[middle - 1] == target) {
middle--;
}
if (DEBUG_IDS) {
System.out.println("FOUND AT "+middle);
}
return middle;
}
// is this point higher or lower?
if (value > target) {
end = middle - 1;
}
else {
start = middle + 1;
}
} // while
// not found
if (DEBUG_IDS) {
System.out.println("NOT FOUND!");
}
return -1;
} // binarySearch(int[],int,int,int):int
//
// Private methods
//
/** Creates the specified chunk in the given array of chunks. */
private final void createChunk(int data[][], int chunk) {
data[chunk] = new int[CHUNK_SIZE + 2];
for (int i = 0; i < CHUNK_SIZE; i++) {
data[chunk][i] = -1;
}
}
/**
* Sets the specified value in the given of data at the chunk and index.
*
* @return Returns the old value.
*/
private final int setChunkIndex(int data[][], int value, int chunk, int index) {
if (value == -1) {
return clearChunkIndex(data, chunk, index);
}
int ovalue = data[chunk][index];
if (ovalue == -1) {
data[chunk][CHUNK_SIZE]++;
}
data[chunk][index] = value;
return ovalue;
}
/**
* Returns the specified value in the given data at the chunk and index.
*/
private final int getChunkIndex(int data[][], int chunk, int index) {
return data[chunk] != null ? data[chunk][index] : -1;
}
/**
* Clears the specified value in the given data at the chunk and index.
* Note that this method will clear the given chunk if the reference
* count becomes zero.
*
* @return Returns the old value.
*/
private final int clearChunkIndex(int data[][], int chunk, int index) {
int value = data[chunk] != null ? data[chunk][index] : -1;
if (value != -1) {
data[chunk][CHUNK_SIZE + 1]++;
data[chunk][index] = -1;
if (data[chunk][CHUNK_SIZE] == data[chunk][CHUNK_SIZE + 1]) {
data[chunk] = null;
}
}
return value;
}
/**
* This version of putIdentifier is needed to avoid fluffing
* all of the paths to ID attributes when a node object is
* created that contains an ID attribute.
*/
private final void putIdentifier0(String idName, Element element) {
if (DEBUG_IDS) {
System.out.println("putIdentifier0("+
idName+", "+
element+')');
}
// create hashtable
if (identifiers == null) {
identifiers = new java.util.Hashtable();
}
// save ID and its associated element
identifiers.put(idName, element);
} // putIdentifier0(String,Element)
/** Prints the ID array. */
private static void print(int values[], int start, int end,
int middle, int target) {
if (DEBUG_IDS) {
System.out.print(start);
System.out.print(" [");
for (int i = start; i < end; i++) {
if (middle == i) {
System.out.print("!");
}
System.out.print(values[i]);
if (values[i] == target) {
System.out.print("*");
}
if (i < end - 1) {
System.out.print(" ");
}
}
System.out.println("] "+end);
}
} // print(int[],int,int,int,int)
//
// Classes
//
/**
* A simple integer vector.
*/
static class IntVector {
//
// Data
//
/** Data. */
private int data[];
/** Size. */
private int size;
//
// Public methods
//
/** Returns the length of this vector. */
public int size() {
return size;
}
/** Returns the element at the specified index. */
public int elementAt(int index) {
return data[index];
}
/** Appends an element to the end of the vector. */
public void addElement(int element) {
ensureCapacity(size + 1);
data[size++] = element;
}
/** Clears the vector. */
public void removeAllElements() {
size = 0;
}
//
// Private methods
//
/** Makes sure that there is enough storage. */
private void ensureCapacity(int newsize) {
if (data == null) {
data = new int[newsize + 15];
}
else if (newsize > data.length) {
int newdata[] = new int[newsize + 15];
System.arraycopy(data, 0, newdata, 0, data.length);
data = newdata;
}
} // ensureCapacity(int)
} // class IntVector
} // class DeferredDocumentImpl
| true | true | public DeferredNode getNodeObject(int nodeIndex) {
// is there anything to do?
if (nodeIndex == -1) {
return null;
}
// get node type
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
int type = clearChunkIndex(fNodeType, chunk, index);
clearChunkIndex(fNodeParent, chunk, index);
// create new node
DeferredNode node = null;
switch (type) {
//
// Standard DOM node types
//
case Node.ATTRIBUTE_NODE: {
node = new DeferredAttrImpl(this, nodeIndex);
break;
}
case Node.CDATA_SECTION_NODE: {
node = new DeferredCDATASectionImpl(this, nodeIndex);
break;
}
case Node.COMMENT_NODE: {
node = new DeferredCommentImpl(this, nodeIndex);
break;
}
// NOTE: Document fragments can never be "fast".
//
// The parser will never ask to create a document
// fragment during the parse. Document fragments
// are used by the application *after* the parse.
//
// case Node.DOCUMENT_FRAGMENT_NODE: { break; }
case Node.DOCUMENT_NODE: {
// this node is never "fast"
node = this;
break;
}
case Node.DOCUMENT_TYPE_NODE: {
node = new DeferredDocumentTypeImpl(this, nodeIndex);
// save the doctype node
docType = (DocumentTypeImpl)node;
break;
}
case Node.ELEMENT_NODE: {
if (DEBUG_IDS) {
System.out.println("getNodeObject(ELEMENT_NODE): "+nodeIndex);
}
// create node
node = new DeferredElementImpl(this, nodeIndex);
// save the document element node
if (docElement == null) {
docElement = (ElementImpl)node;
}
// check to see if this element needs to be
// registered for its ID attributes
if (fIdElement != null) {
int idIndex = DeferredDocumentImpl.binarySearch(fIdElement, 0, fIdCount, nodeIndex);
while (idIndex != -1) {
if (DEBUG_IDS) {
System.out.println(" id index: "+idIndex);
System.out.println(" fIdName["+idIndex+
"]: "+fIdName[idIndex]);
}
// register ID
int nameIndex = fIdName[idIndex];
if (nameIndex != -1) {
String name = fStringPool.toString(nameIndex);
if (DEBUG_IDS) {
System.out.println(" name: "+name);
System.out.print("getNodeObject()#");
}
putIdentifier0(name, (Element)node);
fIdName[idIndex] = -1;
}
// continue if there are more IDs for
// this element
if (idIndex < fIdCount &&
fIdElement[idIndex + 1] == nodeIndex) {
idIndex++;
}
else {
idIndex = -1;
}
}
}
break;
}
case Node.ENTITY_NODE: {
node = new DeferredEntityImpl(this, nodeIndex);
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = new DeferredEntityReferenceImpl(this, nodeIndex);
break;
}
case Node.NOTATION_NODE: {
node = new DeferredNotationImpl(this, nodeIndex);
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = new DeferredProcessingInstructionImpl(this, nodeIndex);
break;
}
case Node.TEXT_NODE: {
node = new DeferredTextImpl(this, nodeIndex);
break;
}
//
// non-standard DOM node types
//
case NodeImpl.ELEMENT_DEFINITION_NODE: {
node = new DeferredElementDefinitionImpl(this, nodeIndex);
break;
}
default: {
throw new IllegalArgumentException("type: "+type);
}
} // switch node type
// store and return
if (node != null) {
return node;
}
// error
throw new IllegalArgumentException();
} // createNodeObject(int):Node
| public DeferredNode getNodeObject(int nodeIndex) {
// is there anything to do?
if (nodeIndex == -1) {
return null;
}
// get node type
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
int type = clearChunkIndex(fNodeType, chunk, index);
clearChunkIndex(fNodeParent, chunk, index);
// create new node
DeferredNode node = null;
switch (type) {
//
// Standard DOM node types
//
case Node.ATTRIBUTE_NODE: {
node = new DeferredAttrImpl(this, nodeIndex);
break;
}
case Node.CDATA_SECTION_NODE: {
node = new DeferredCDATASectionImpl(this, nodeIndex);
break;
}
case Node.COMMENT_NODE: {
node = new DeferredCommentImpl(this, nodeIndex);
break;
}
// NOTE: Document fragments can never be "fast".
//
// The parser will never ask to create a document
// fragment during the parse. Document fragments
// are used by the application *after* the parse.
//
// case Node.DOCUMENT_FRAGMENT_NODE: { break; }
case Node.DOCUMENT_NODE: {
// this node is never "fast"
node = this;
break;
}
case Node.DOCUMENT_TYPE_NODE: {
node = new DeferredDocumentTypeImpl(this, nodeIndex);
// save the doctype node
docType = (DocumentTypeImpl)node;
break;
}
case Node.ELEMENT_NODE: {
if (DEBUG_IDS) {
System.out.println("getNodeObject(ELEMENT_NODE): "+nodeIndex);
}
// create node
node = new DeferredElementImpl(this, nodeIndex);
// save the document element node
if (docElement == null) {
docElement = (ElementImpl)node;
}
// check to see if this element needs to be
// registered for its ID attributes
if (fIdElement != null) {
int idIndex = DeferredDocumentImpl.binarySearch(fIdElement, 0, fIdCount, nodeIndex);
while (idIndex != -1) {
if (DEBUG_IDS) {
System.out.println(" id index: "+idIndex);
System.out.println(" fIdName["+idIndex+
"]: "+fIdName[idIndex]);
}
// register ID
int nameIndex = fIdName[idIndex];
if (nameIndex != -1) {
String name = fStringPool.toString(nameIndex);
if (DEBUG_IDS) {
System.out.println(" name: "+name);
System.out.print("getNodeObject()#");
}
putIdentifier0(name, (Element)node);
fIdName[idIndex] = -1;
}
// continue if there are more IDs for
// this element
if (idIndex + 1 < fIdCount &&
fIdElement[idIndex + 1] == nodeIndex) {
idIndex++;
}
else {
idIndex = -1;
}
}
}
break;
}
case Node.ENTITY_NODE: {
node = new DeferredEntityImpl(this, nodeIndex);
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = new DeferredEntityReferenceImpl(this, nodeIndex);
break;
}
case Node.NOTATION_NODE: {
node = new DeferredNotationImpl(this, nodeIndex);
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = new DeferredProcessingInstructionImpl(this, nodeIndex);
break;
}
case Node.TEXT_NODE: {
node = new DeferredTextImpl(this, nodeIndex);
break;
}
//
// non-standard DOM node types
//
case NodeImpl.ELEMENT_DEFINITION_NODE: {
node = new DeferredElementDefinitionImpl(this, nodeIndex);
break;
}
default: {
throw new IllegalArgumentException("type: "+type);
}
} // switch node type
// store and return
if (node != null) {
return node;
}
// error
throw new IllegalArgumentException();
} // createNodeObject(int):Node
|
diff --git a/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java b/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java
index 01569eff..3922b825 100644
--- a/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java
+++ b/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java
@@ -1,252 +1,251 @@
package org.mule.galaxy.web.client.property;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Widget;
import java.io.Serializable;
import java.util.Collection;
import org.mule.galaxy.web.client.AbstractComposite;
import org.mule.galaxy.web.client.ErrorPanel;
import org.mule.galaxy.web.client.Galaxy;
import org.mule.galaxy.web.client.util.ConfirmDialog;
import org.mule.galaxy.web.client.util.ConfirmDialogAdapter;
import org.mule.galaxy.web.client.util.InlineFlowPanel;
import org.mule.galaxy.web.client.util.LightBox;
import org.mule.galaxy.web.rpc.AbstractCallback;
import org.mule.galaxy.web.rpc.WProperty;
/**
* Encapsulates the rendering and editing of a property value.
*/
public class EditPropertyPanel extends AbstractComposite {
private Button save;
protected Button cancel;
private AbstractPropertyRenderer renderer;
protected InlineFlowPanel panel;
protected ErrorPanel errorPanel;
protected String itemId;
protected WProperty property;
protected Galaxy galaxy;
protected ClickListener saveListener;
protected ClickListener deleteListener;
protected ClickListener cancelListener;
public EditPropertyPanel(AbstractPropertyRenderer renderer) {
super();
this.panel = new InlineFlowPanel();
initWidget(panel);
this.renderer = renderer;
}
public void initialize() {
initializeRenderer();
}
public InlineFlowPanel createViewPanel() {
Image editImg = new Image("images/page_edit.gif");
editImg.setStyleName("icon-baseline");
editImg.setTitle("Edit");
editImg.addClickListener(new ClickListener() {
public void onClick(Widget widget) {
showEdit();
}
});
Image deleteImg = new Image("images/delete_config.gif");
deleteImg.setStyleName("icon-baseline");
deleteImg.setTitle("Delete");
deleteImg.addClickListener(new ClickListener() {
public void onClick(Widget widget) {
delete();
}
});
InlineFlowPanel viewPanel = new InlineFlowPanel();
viewPanel.add(renderer.createViewWidget());
if (!property.isLocked()) {
// interesting... spacer label has to be a new object ref, otherwise not honored...
viewPanel.add(new Label(" "));
viewPanel.add(editImg);
viewPanel.add(new Label(" "));
viewPanel.add(deleteImg);
}
return viewPanel;
}
protected FlowPanel createEditPanel() {
FlowPanel editPanel = new FlowPanel();
editPanel.setStyleName("add-property-inline");
Widget editForm = renderer.createEditForm();
- editForm.setStyleName("add-property-inline");
editPanel.add(editForm);
FlowPanel buttonPanel = new FlowPanel();
cancel = new Button("Cancel");
cancel.addClickListener(new ClickListener() {
public void onClick(Widget arg0) {
cancel();
}
});
if (cancelListener != null) {
cancel.addClickListener(cancelListener);
}
save = new Button("Save");
save.addClickListener(new ClickListener() {
public void onClick(Widget arg0) {
cancel.setEnabled(false);
save.setEnabled(false);
save();
}
});
buttonPanel.add(save);
buttonPanel.add(cancel);
editPanel.add(buttonPanel);
return editPanel;
}
protected void cancel() {
initializeRenderer();
showView();
}
public void showView() {
panel.clear();
panel.add(createViewPanel());
}
protected void delete() {
final ConfirmDialog dialog = new ConfirmDialog(new ConfirmDialogAdapter() {
public void onConfirm() {
doDelete();
}
}, "Are you sure you want to delete this property?");
new LightBox(dialog).show();
}
protected void doDelete() {
galaxy.getRegistryService().deleteProperty(itemId, property.getName(), new AbstractCallback(errorPanel) {
public void onSuccess(Object arg0) {
deleteListener.onClick(null);
}
});
}
public void showEdit() {
panel.clear();
FlowPanel editPanel = createEditPanel();
panel.add(editPanel);
}
protected void save() {
final Serializable value = (Serializable) renderer.getValueToSave();
AbstractCallback saveCallback = getSaveCallback(value);
setEnabled(false);
renderer.save(itemId, property.getName(), value, saveCallback);
}
protected AbstractCallback getSaveCallback(final Serializable value) {
AbstractCallback saveCallback = new AbstractCallback(errorPanel) {
public void onFailure(Throwable caught) {
onSaveFailure(caught, this);
}
public void onSuccess(Object response) {
onSave(value, response);
}
};
return saveCallback;
}
protected void onSave(final Serializable value, Object response) {
setEnabled(true);
property.setValue(value);
initializeRenderer();
showView();
if (saveListener != null) {
saveListener.onClick(save);
}
}
private void initializeRenderer() {
renderer.initialize(galaxy, errorPanel, property.getValue(), false);
}
protected void onSaveFailure(Throwable caught, AbstractCallback saveCallback) {
saveCallback.onFailureDirect(caught);
}
public WProperty getProperty() {
return property;
}
public void setProperty(WProperty property) {
this.property = property;
}
public void setGalaxy(Galaxy galaxy) {
this.galaxy = galaxy;
}
public void setErrorPanel(ErrorPanel errorPanel) {
this.errorPanel = errorPanel;
}
public void setItemId(String entryid) {
this.itemId = entryid;
}
public void setEnabled(boolean b) {
if (cancel != null) {
cancel.setEnabled(b);
}
if (save != null) {
save.setEnabled(b);
}
}
public void setSaveListener(ClickListener saveListener) {
this.saveListener = saveListener;
}
public void setDeleteListener(ClickListener deleteListener) {
this.deleteListener = deleteListener;
}
public void setCancelListener(ClickListener cancelListener) {
this.cancelListener = cancelListener;
}
}
| true | true | protected FlowPanel createEditPanel() {
FlowPanel editPanel = new FlowPanel();
editPanel.setStyleName("add-property-inline");
Widget editForm = renderer.createEditForm();
editForm.setStyleName("add-property-inline");
editPanel.add(editForm);
FlowPanel buttonPanel = new FlowPanel();
cancel = new Button("Cancel");
cancel.addClickListener(new ClickListener() {
public void onClick(Widget arg0) {
cancel();
}
});
if (cancelListener != null) {
cancel.addClickListener(cancelListener);
}
save = new Button("Save");
save.addClickListener(new ClickListener() {
public void onClick(Widget arg0) {
cancel.setEnabled(false);
save.setEnabled(false);
save();
}
});
buttonPanel.add(save);
buttonPanel.add(cancel);
editPanel.add(buttonPanel);
return editPanel;
}
| protected FlowPanel createEditPanel() {
FlowPanel editPanel = new FlowPanel();
editPanel.setStyleName("add-property-inline");
Widget editForm = renderer.createEditForm();
editPanel.add(editForm);
FlowPanel buttonPanel = new FlowPanel();
cancel = new Button("Cancel");
cancel.addClickListener(new ClickListener() {
public void onClick(Widget arg0) {
cancel();
}
});
if (cancelListener != null) {
cancel.addClickListener(cancelListener);
}
save = new Button("Save");
save.addClickListener(new ClickListener() {
public void onClick(Widget arg0) {
cancel.setEnabled(false);
save.setEnabled(false);
save();
}
});
buttonPanel.add(save);
buttonPanel.add(cancel);
editPanel.add(buttonPanel);
return editPanel;
}
|
diff --git a/topcat/src/main/uk/ac/starlink/topcat/JELUtils.java b/topcat/src/main/uk/ac/starlink/topcat/JELUtils.java
index e85492273..5c826f230 100644
--- a/topcat/src/main/uk/ac/starlink/topcat/JELUtils.java
+++ b/topcat/src/main/uk/ac/starlink/topcat/JELUtils.java
@@ -1,148 +1,148 @@
package uk.ac.starlink.topcat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import gnu.jel.Library;
import gnu.jel.DVMap;
import java.util.Date;
import java.util.Hashtable;
import uk.ac.starlink.topcat.func.Activation;
import uk.ac.starlink.topcat.func.Angles;
import uk.ac.starlink.topcat.func.Miscellaneous;
/**
* This class provides some utility methods for use with the JEL
* expression compiler.
*
* @author Mark Taylor (Starlink)
*/
public class JELUtils {
private static List staticClasses;
public static final String AUX_CLASSES_PROPERTY = "gnu.jel.static.classes";
private static Logger logger = Logger.getLogger( "uk.ac.starlink.topcat" );
/**
* Returns a JEL Library suitable for expression evaluation.
*
* @param rowReader object which can read rows from the table to
* be used for expression evaluation
* @return a library
*/
public static Library getLibrary( JELRowReader rowReader ) {
Class[] staticLib =
(Class[]) getStaticClasses().toArray( new Class[ 0 ] );
Class[] dynamicLib = new Class[] { JELRowReader.class };
Class[] dotClasses = new Class[] { String.class, Date.class };
DVMap resolver = rowReader;
Hashtable cnmap = null;
return new Library( staticLib, dynamicLib, dotClasses,
resolver, cnmap );
}
/**
* Returns a JEL library suitable for code activation.
* This includes access to methods which do stuff (e.g. write to
* System.out, pop up viewers) rather than just ones which
* calculate things.
*
* @param rowReader object which can read rows from the table to
* be used for expression execution
* @return a library
*/
static Library getActivationLibrary( JELRowReader rowReader ) {
List statix = new ArrayList( getStaticClasses() );
statix.add( Activation.class );
Class[] staticLib = (Class[]) statix.toArray( new Class[ 0 ] );
Class[] dynamicLib = new Class[] { JELRowReader.class };
Class[] dotClasses = new Class[] { String.class, Date.class };
DVMap resolver = rowReader;
Hashtable cnmap = null;
return new Library( staticLib, dynamicLib, dotClasses,
resolver, cnmap );
}
/**
* Returns the list of classes whose static methods will be mapped
* into the JEL evaluation namespace. This may be modified.
*
* @return list of classes with static methods
*/
public static List getStaticClasses() {
if ( staticClasses == null ) {
/* Basic classes always present. */
List classList = new ArrayList( Arrays.asList( new Class[] {
Math.class, Integer.class, Float.class, Double.class,
Angles.class, Miscellaneous.class,
} ) );
try {
/* Add classes specified by a system property. */
String auxClasses = System.getProperty( AUX_CLASSES_PROPERTY );
if ( auxClasses != null && auxClasses.trim().length() > 0 ) {
String[] cs = auxClasses.split( ":" );
for ( int i = 0; i < cs.length; i++ ) {
String className = cs[ i ].trim();
try {
classList.add( Class.forName( className,
true,
Thread.currentThread().getContextClassLoader()));
}
catch ( ClassNotFoundException e ) {
logger.warning( "Class not found: " + className );
}
}
}
}
catch ( SecurityException e ) {
logger.info( "Security manager prevents loading "
+ "auxiliary JEL classes" );
}
/* Combine to produce the final list. */
staticClasses = classList;
}
- return Collections.unmodifiableList( staticClasses );
+ return staticClasses;
}
/**
* Turns a primitive class into the corresponding wrapper class.
*
* @param prim primitive class
* @return the corresponding non-primitive wrapper class
*/
public static Class wrapPrimitiveClass( Class prim ) {
if ( prim == boolean.class ) {
return Boolean.class;
}
else if ( prim == char.class ) {
return Character.class;
}
else if ( prim == byte.class ) {
return Byte.class;
}
else if ( prim == short.class ) {
return Short.class;
}
else if ( prim == int.class ) {
return Integer.class;
}
else if ( prim == long.class ) {
return Long.class;
}
else if ( prim == float.class ) {
return Float.class;
}
else if ( prim == double.class ) {
return Double.class;
}
else {
throw new IllegalArgumentException( prim + " is not primitive" );
}
}
}
| true | true | public static List getStaticClasses() {
if ( staticClasses == null ) {
/* Basic classes always present. */
List classList = new ArrayList( Arrays.asList( new Class[] {
Math.class, Integer.class, Float.class, Double.class,
Angles.class, Miscellaneous.class,
} ) );
try {
/* Add classes specified by a system property. */
String auxClasses = System.getProperty( AUX_CLASSES_PROPERTY );
if ( auxClasses != null && auxClasses.trim().length() > 0 ) {
String[] cs = auxClasses.split( ":" );
for ( int i = 0; i < cs.length; i++ ) {
String className = cs[ i ].trim();
try {
classList.add( Class.forName( className,
true,
Thread.currentThread().getContextClassLoader()));
}
catch ( ClassNotFoundException e ) {
logger.warning( "Class not found: " + className );
}
}
}
}
catch ( SecurityException e ) {
logger.info( "Security manager prevents loading "
+ "auxiliary JEL classes" );
}
/* Combine to produce the final list. */
staticClasses = classList;
}
return Collections.unmodifiableList( staticClasses );
}
| public static List getStaticClasses() {
if ( staticClasses == null ) {
/* Basic classes always present. */
List classList = new ArrayList( Arrays.asList( new Class[] {
Math.class, Integer.class, Float.class, Double.class,
Angles.class, Miscellaneous.class,
} ) );
try {
/* Add classes specified by a system property. */
String auxClasses = System.getProperty( AUX_CLASSES_PROPERTY );
if ( auxClasses != null && auxClasses.trim().length() > 0 ) {
String[] cs = auxClasses.split( ":" );
for ( int i = 0; i < cs.length; i++ ) {
String className = cs[ i ].trim();
try {
classList.add( Class.forName( className,
true,
Thread.currentThread().getContextClassLoader()));
}
catch ( ClassNotFoundException e ) {
logger.warning( "Class not found: " + className );
}
}
}
}
catch ( SecurityException e ) {
logger.info( "Security manager prevents loading "
+ "auxiliary JEL classes" );
}
/* Combine to produce the final list. */
staticClasses = classList;
}
return staticClasses;
}
|
diff --git a/src/main/java/fr/ybo/ybotv/android/adapter/CeSoirViewFlowAdapter.java b/src/main/java/fr/ybo/ybotv/android/adapter/CeSoirViewFlowAdapter.java
index b984996..d5ccbd0 100644
--- a/src/main/java/fr/ybo/ybotv/android/adapter/CeSoirViewFlowAdapter.java
+++ b/src/main/java/fr/ybo/ybotv/android/adapter/CeSoirViewFlowAdapter.java
@@ -1,129 +1,129 @@
package fr.ybo.ybotv.android.adapter;
import android.app.Activity;
import android.content.res.Configuration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import fr.ybo.ybotv.android.R;
import fr.ybo.ybotv.android.YboTvApplication;
import fr.ybo.ybotv.android.activity.ListProgrammeManager;
import fr.ybo.ybotv.android.modele.ChannelWithProgramme;
import org.taptwo.android.widget.TitleProvider;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class CeSoirViewFlowAdapter extends BaseAdapter implements TitleProvider {
private LayoutInflater inflater;
private Activity context;
private int[] titles = {R.string.primeTime, R.string.partie2, R.string.finSoiree};
private Calendar currentDate;
public CeSoirViewFlowAdapter(Activity context, Calendar currentDate) {
this.inflater = LayoutInflater.from(context);
this.context = context;
this.currentDate = currentDate;
}
public void changeCurrentDate(Calendar calendar) {
currentDate = calendar;
notifyDataSetChanged();
}
@Override
public int getCount() {
return titles.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
private static class MyGetProgramme implements ListProgrammeManager.GetProgramme {
private int position;
private YboTvApplication application;
private Calendar currentDate;
private MyGetProgramme(int position, YboTvApplication application, Calendar currentDate) {
this.position = position;
this.application = application;
this.currentDate = currentDate;
}
@Override
public List<ChannelWithProgramme> getProgrammes() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String dateToSelect;
switch (position) {
case 1:
// Deuxième partie
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "230000";
break;
case 2:
// Fin de soirée
Calendar calendarTwomorrow = (Calendar) currentDate.clone();
calendarTwomorrow.add(Calendar.DAY_OF_MONTH, 1);
Date twomorrow = calendarTwomorrow.getTime();
- if (calendarTwomorrow.get(Calendar.HOUR_OF_DAY) > 2) {
+ if (calendarTwomorrow.get(Calendar.HOUR_OF_DAY) <= 2) {
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "010000";
} else {
dateToSelect = simpleDateFormat.format(twomorrow) + "010000";
}
break;
default:
// PrimeTime
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "210000";
break;
}
return ChannelWithProgramme.getProgrammesForDate(application, dateToSelect);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_ss_pub, null);
}
GridView gridView = (GridView) convertView.findViewById(R.id.grid);
if (((YboTvApplication)context.getApplication()).isTablet()) {
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
gridView.setNumColumns(3);
} else {
gridView.setNumColumns(2);
}
}
new ListProgrammeManager(gridView, context, new MyGetProgramme(position, (YboTvApplication) context.getApplication(), currentDate)).constructAdapter();
return convertView;
}
/* (non-Javadoc)
* @see org.taptwo.android.widget.TitleProvider#getTitle(int)
*/
@Override
public String getTitle(int position) {
return context.getString(titles[position]);
}
}
| true | true | public List<ChannelWithProgramme> getProgrammes() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String dateToSelect;
switch (position) {
case 1:
// Deuxième partie
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "230000";
break;
case 2:
// Fin de soirée
Calendar calendarTwomorrow = (Calendar) currentDate.clone();
calendarTwomorrow.add(Calendar.DAY_OF_MONTH, 1);
Date twomorrow = calendarTwomorrow.getTime();
if (calendarTwomorrow.get(Calendar.HOUR_OF_DAY) > 2) {
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "010000";
} else {
dateToSelect = simpleDateFormat.format(twomorrow) + "010000";
}
break;
default:
// PrimeTime
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "210000";
break;
}
return ChannelWithProgramme.getProgrammesForDate(application, dateToSelect);
}
| public List<ChannelWithProgramme> getProgrammes() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String dateToSelect;
switch (position) {
case 1:
// Deuxième partie
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "230000";
break;
case 2:
// Fin de soirée
Calendar calendarTwomorrow = (Calendar) currentDate.clone();
calendarTwomorrow.add(Calendar.DAY_OF_MONTH, 1);
Date twomorrow = calendarTwomorrow.getTime();
if (calendarTwomorrow.get(Calendar.HOUR_OF_DAY) <= 2) {
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "010000";
} else {
dateToSelect = simpleDateFormat.format(twomorrow) + "010000";
}
break;
default:
// PrimeTime
dateToSelect = simpleDateFormat.format(currentDate.getTime()) + "210000";
break;
}
return ChannelWithProgramme.getProgrammesForDate(application, dateToSelect);
}
|
diff --git a/server/src/test/java/com/ece/superkids/testing/StateSavedTests.java b/server/src/test/java/com/ece/superkids/testing/StateSavedTests.java
index 043bb59..90bf14a 100644
--- a/server/src/test/java/com/ece/superkids/testing/StateSavedTests.java
+++ b/server/src/test/java/com/ece/superkids/testing/StateSavedTests.java
@@ -1,76 +1,79 @@
package com.ece.superkids.testing;
import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import com.ece.superkids.questions.entities.*;
import com.ece.superkids.questions.enums.*;
import com.ece.superkids.users.FileUserManager;
import com.ece.superkids.users.entities.History;
import com.ece.superkids.users.entities.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The <code>StateSavedTests</code> has tests to check states can be saved successfully and can be reparsed.
*
* @author Marc Adam
*/
public class StateSavedTests {
private FileUserManager fileUserManager = new FileUserManager();
private User testUser;
private Question question;
/**
* Create a user and a question.
*/
@Before
public void setup() {
testUser = new User("TestUser");
question = new Question();
+ fileUserManager.addUser(testUser);
question.setAnswer("QuestionAnswer");
question.setCategory(QuestionCategory.ANIMALS);
question.setLevel(QuestionLevel.LEVEL_1);
question.setExplaination("This is a test question, do not answer this.");
question.setType(QuestionType.TEXT);
ArrayList choices = new ArrayList();
choices.add("Answer 1");
choices.add("Answer 2");
choices.add("Answer 3");
choices.add("Answer 4");
question.setChoices(choices);
+ testUser.setCurrentQuestion(question);
+ testUser.saveUser();
}
/**
* Check if the current question is saved.
*/
@Test
public void setCurrentQuestionTest() {
testUser.setCurrentQuestion(question);
testUser.saveUser();
}
/**
* Check if the state of the user after closing the application is the same as the state of the user before closing the application.
*/
@Test
public void getStateAfterClosingApplicationTest() {
User actualUser = fileUserManager.getUser("TestUser");
Question actualQuestion = actualUser.getState().getCurrentQuestion();
assertEquals(question.getQuestion(), actualQuestion.getQuestion());
assertEquals(question.getExplaination(), actualQuestion.getExplaination());
fileUserManager.deleteUser("TestUser");
}
}
| false | true | public void setup() {
testUser = new User("TestUser");
question = new Question();
question.setAnswer("QuestionAnswer");
question.setCategory(QuestionCategory.ANIMALS);
question.setLevel(QuestionLevel.LEVEL_1);
question.setExplaination("This is a test question, do not answer this.");
question.setType(QuestionType.TEXT);
ArrayList choices = new ArrayList();
choices.add("Answer 1");
choices.add("Answer 2");
choices.add("Answer 3");
choices.add("Answer 4");
question.setChoices(choices);
}
| public void setup() {
testUser = new User("TestUser");
question = new Question();
fileUserManager.addUser(testUser);
question.setAnswer("QuestionAnswer");
question.setCategory(QuestionCategory.ANIMALS);
question.setLevel(QuestionLevel.LEVEL_1);
question.setExplaination("This is a test question, do not answer this.");
question.setType(QuestionType.TEXT);
ArrayList choices = new ArrayList();
choices.add("Answer 1");
choices.add("Answer 2");
choices.add("Answer 3");
choices.add("Answer 4");
question.setChoices(choices);
testUser.setCurrentQuestion(question);
testUser.saveUser();
}
|
diff --git a/app/src/processing/mode/java/JavaBuild.java b/app/src/processing/mode/java/JavaBuild.java
index f42d0930d..e6db686ba 100644
--- a/app/src/processing/mode/java/JavaBuild.java
+++ b/app/src/processing/mode/java/JavaBuild.java
@@ -1,1793 +1,1793 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
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; 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 processing.mode.java;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import processing.app.*;
import processing.core.*;
import processing.mode.java.preproc.*;
// Would you believe there's a java.lang.Compiler class? I wouldn't.
public class JavaBuild {
public static final String PACKAGE_REGEX =
"(?:^|\\s|;)package\\s+(\\S+)\\;";
protected Sketch sketch;
protected Mode mode;
// what happens in the build, stays in the build.
// (which is to say that everything below this line, stays within this class)
protected File srcFolder;
protected File binFolder;
private boolean foundMain = false;
private String classPath;
protected String sketchClassName;
/**
* This will include the code folder, any library folders, etc. that might
* contain native libraries that need to be picked up with java.library.path.
* This is *not* the "Processing" libraries path, this is the Java libraries
* path, as in java.library.path=BlahBlah, which identifies search paths for
* DLLs or JNILIBs. (It's Java's LD_LIBRARY_PATH, for you UNIX fans.)
* This is set by the preprocessor as it figures out where everything is.
*/
private String javaLibraryPath;
/** List of library folders, as figured out during preprocessing. */
private ArrayList<Library> importedLibraries;
public JavaBuild(Sketch sketch) {
this.sketch = sketch;
this.mode = sketch.getMode();
}
/**
* Cleanup temporary files used during a build/run.
*/
// protected void cleanup() {
// // if the java runtime is holding onto any files in the build dir, we
// // won't be able to delete them, so we need to force a gc here
// System.gc();
//
// // note that we can't remove the builddir itself, otherwise
// // the next time we start up, internal runs using Runner won't
// // work because the build dir won't exist at startup, so the classloader
// // will ignore the fact that that dir is in the CLASSPATH in run.sh
// Base.removeDescendants(tempBuildFolder);
// }
/**
* Preprocess, Compile, and Run the current code.
* <P>
* There are three main parts to this process:
* <PRE>
* (0. if not java, then use another 'engine'.. i.e. python)
*
* 1. do the p5 language preprocessing
* this creates a working .java file in a specific location
* better yet, just takes a chunk of java code and returns a
* new/better string editor can take care of saving this to a
* file location
*
* 2. compile the code from that location
* catching errors along the way
* placing it in a ready classpath, or .. ?
*
* 3. run the code
* needs to communicate location for window
* and maybe setup presentation space as well
* run externally if a code folder exists,
* or if more than one file is in the project
*
* X. afterwards, some of these steps need a cleanup function
* </PRE>
*/
//protected String compile() throws RunnerException {
/**
* Run the build inside a temporary build folder. Used for run/present.
* @return null if compilation failed, main class name if not
* @throws RunnerException
*/
public String build(boolean sizeWarning) throws SketchException {
return build(sketch.makeTempFolder(), sketch.makeTempFolder(), sizeWarning);
}
/**
* Preprocess and compile all the code for this sketch.
*
* In an advanced program, the returned class name could be different,
* which is why the className is set based on the return value.
* A compilation error will burp up a RunnerException.
*
* @return null if compilation failed, main class name if not
*/
public String build(File srcFolder, File binFolder, boolean sizeWarning) throws SketchException {
this.srcFolder = srcFolder;
this.binFolder = binFolder;
// Base.openFolder(srcFolder);
// Base.openFolder(binFolder);
// run the preprocessor
String classNameFound = preprocess(srcFolder, sizeWarning);
// compile the program. errors will happen as a RunnerException
// that will bubble up to whomever called build().
// Compiler compiler = new Compiler(this);
// String bootClasses = System.getProperty("sun.boot.class.path");
// if (compiler.compile(this, srcFolder, binFolder, primaryClassName, getClassPath(), bootClasses)) {
if (Compiler.compile(this)) {
sketchClassName = classNameFound;
return classNameFound;
}
return null;
}
public String getSketchClassName() {
return sketchClassName;
}
/**
* Build all the code for this sketch.
*
* In an advanced program, the returned class name could be different,
* which is why the className is set based on the return value.
* A compilation error will burp up a RunnerException.
*
* Setting purty to 'true' will cause exception line numbers to be incorrect.
* Unless you know the code compiles, you should first run the preprocessor
* with purty set to false to make sure there are no errors, then once
* successful, re-export with purty set to true.
*
* @param buildPath Location to copy all the .java files
* @return null if compilation failed, main class name if not
*/
// public String preprocess() throws SketchException {
// return preprocess(sketch.makeTempFolder());
// }
public String preprocess(File srcFolder, boolean sizeWarning) throws SketchException {
return preprocess(srcFolder, null, new PdePreprocessor(sketch.getName()), sizeWarning);
}
/**
* @param srcFolder location where the .java source files will be placed
* @param packageName null, or the package name that should be used as default
* @param preprocessor the preprocessor object ready to do the work
* @return main PApplet class name found during preprocess, or null if error
* @throws SketchException
*/
public String preprocess(File srcFolder,
String packageName,
PdePreprocessor preprocessor,
boolean sizeWarning) throws SketchException {
// make sure the user isn't playing "hide the sketch folder"
sketch.ensureExistence();
// System.out.println("srcFolder is " + srcFolder);
classPath = binFolder.getAbsolutePath();
// figure out the contents of the code folder to see if there
// are files that need to be added to the imports
String[] codeFolderPackages = null;
if (sketch.hasCodeFolder()) {
File codeFolder = sketch.getCodeFolder();
javaLibraryPath = codeFolder.getAbsolutePath();
// get a list of .jar files in the "code" folder
// (class files in subfolders should also be picked up)
String codeFolderClassPath =
Base.contentsToClassPath(codeFolder);
// append the jar files in the code folder to the class path
classPath += File.pathSeparator + codeFolderClassPath;
// get list of packages found in those jars
codeFolderPackages =
Base.packageListFromClassPath(codeFolderClassPath);
} else {
javaLibraryPath = "";
}
// 1. concatenate all .pde files to the 'main' pde
// store line number for starting point of each code bit
StringBuffer bigCode = new StringBuffer();
int bigCount = 0;
for (SketchCode sc : sketch.getCode()) {
if (sc.isExtension("pde")) {
sc.setPreprocOffset(bigCount);
bigCode.append(sc.getProgram());
bigCode.append('\n');
bigCount += sc.getLineCount();
}
}
// // initSketchSize() sets the internal sketchWidth/Height/Renderer vars
// // in the preprocessor. Those are used in preproc.write() so that they
// // can be turned into sketchXxxx() methods.
// // This also returns the size info as an array so that we can figure out
// // if this fella is OpenGL, and if so, to add the import. It's messy and
// // gross and someday we'll just always include OpenGL.
// String[] sizeInfo =
// preprocessor.initSketchSize(sketch.getMainProgram(), sizeWarning);
// //PdePreprocessor.parseSketchSize(sketch.getMainProgram(), false);
// if (sizeInfo != null) {
// String sketchRenderer = sizeInfo[3];
// if (sketchRenderer != null) {
// if (sketchRenderer.equals("P2D") ||
// sketchRenderer.equals("P3D") ||
// sketchRenderer.equals("OPENGL")) {
// bigCode.insert(0, "import processing.opengl.*; ");
// }
// }
// }
PreprocessorResult result;
try {
File outputFolder = (packageName == null) ?
srcFolder : new File(srcFolder, packageName.replace('.', '/'));
outputFolder.mkdirs();
// Base.openFolder(outputFolder);
final File java = new File(outputFolder, sketch.getName() + ".java");
final PrintWriter stream = new PrintWriter(new FileWriter(java));
try {
result = preprocessor.write(stream, bigCode.toString(), codeFolderPackages);
} finally {
stream.close();
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
String msg = "Build folder disappeared or could not be written";
throw new SketchException(msg);
} catch (antlr.RecognitionException re) {
// re also returns a column that we're not bothering with for now
// first assume that it's the main file
// int errorFile = 0;
int errorLine = re.getLine() - 1;
// then search through for anyone else whose preprocName is null,
// since they've also been combined into the main pde.
int errorFile = findErrorFile(errorLine);
// System.out.println("error line is " + errorLine + ", file is " + errorFile);
errorLine -= sketch.getCode(errorFile).getPreprocOffset();
// System.out.println(" preproc offset for that file: " + sketch.getCode(errorFile).getPreprocOffset());
// System.out.println("i found this guy snooping around..");
// System.out.println("whatcha want me to do with 'im boss?");
// System.out.println(errorLine + " " + errorFile + " " + code[errorFile].getPreprocOffset());
String msg = re.getMessage();
//System.out.println(java.getAbsolutePath());
// System.out.println(bigCode);
if (msg.contains("expecting RCURLY")) {
//if (msg.equals("expecting RCURLY, found 'null'")) {
// This can be a problem since the error is sometimes listed as a line
// that's actually past the number of lines. For instance, it might
// report "line 15" of a 14 line program. Added code to highlightLine()
// inside Editor to deal with this situation (since that code is also
// useful for other similar situations).
throw new SketchException("Found one too many { characters " +
"without a } to match it.",
errorFile, errorLine, re.getColumn(), false);
}
if (msg.contains("expecting LCURLY")) {
System.err.println(msg);
String suffix = ".";
String[] m = PApplet.match(msg, "found ('.*')");
if (m != null) {
suffix = ", not " + m[1] + ".";
}
throw new SketchException("Was expecting a { character" + suffix,
errorFile, errorLine, re.getColumn(), false);
}
if (msg.indexOf("expecting RBRACK") != -1) {
System.err.println(msg);
throw new SketchException("Syntax error, " +
"maybe a missing ] character?",
errorFile, errorLine, re.getColumn(), false);
}
if (msg.indexOf("expecting SEMI") != -1) {
System.err.println(msg);
throw new SketchException("Syntax error, " +
"maybe a missing semicolon?",
errorFile, errorLine, re.getColumn(), false);
}
if (msg.indexOf("expecting RPAREN") != -1) {
System.err.println(msg);
throw new SketchException("Syntax error, " +
"maybe a missing right parenthesis?",
errorFile, errorLine, re.getColumn(), false);
}
if (msg.indexOf("preproc.web_colors") != -1) {
throw new SketchException("A web color (such as #ffcc00) " +
"must be six digits.",
errorFile, errorLine, re.getColumn(), false);
}
//System.out.println("msg is " + msg);
throw new SketchException(msg, errorFile,
errorLine, re.getColumn(), false);
} catch (antlr.TokenStreamRecognitionException tsre) {
// while this seems to store line and column internally,
// there doesn't seem to be a method to grab it..
// so instead it's done using a regexp
// System.err.println("and then she tells me " + tsre.toString());
// TODO not tested since removing ORO matcher.. ^ could be a problem
String mess = "^line (\\d+):(\\d+):\\s";
String[] matches = PApplet.match(tsre.toString(), mess);
if (matches != null) {
int errorLine = Integer.parseInt(matches[1]) - 1;
int errorColumn = Integer.parseInt(matches[2]);
int errorFile = 0;
for (int i = 1; i < sketch.getCodeCount(); i++) {
SketchCode sc = sketch.getCode(i);
if (sc.isExtension("pde") &&
(sc.getPreprocOffset() < errorLine)) {
errorFile = i;
}
}
errorLine -= sketch.getCode(errorFile).getPreprocOffset();
throw new SketchException(tsre.getMessage(),
errorFile, errorLine, errorColumn);
} else {
// this is bad, defaults to the main class.. hrm.
String msg = tsre.toString();
throw new SketchException(msg, 0, -1, -1);
}
} catch (SketchException pe) {
// RunnerExceptions are caught here and re-thrown, so that they don't
// get lost in the more general "Exception" handler below.
throw pe;
} catch (Exception ex) {
// TODO better method for handling this?
System.err.println("Uncaught exception type:" + ex.getClass());
ex.printStackTrace();
throw new SketchException(ex.toString());
}
// grab the imports from the code just preproc'd
importedLibraries = new ArrayList<Library>();
Library core = mode.getCoreLibrary();
if (core != null) {
importedLibraries.add(core);
classPath += core.getClassPath();
}
// System.out.println("extra imports: " + result.extraImports);
for (String item : result.extraImports) {
// remove things up to the last dot
int dot = item.lastIndexOf('.');
// http://dev.processing.org/bugs/show_bug.cgi?id=1145
String entry = (dot == -1) ? item : item.substring(0, dot);
// System.out.println("library searching for " + entry);
Library library = mode.getLibrary(entry);
// System.out.println(" found " + library);
if (library != null) {
if (!importedLibraries.contains(library)) {
importedLibraries.add(library);
classPath += library.getClassPath();
javaLibraryPath += File.pathSeparator + library.getNativePath();
}
} else {
boolean found = false;
// If someone insists on unnecessarily repeating the code folder
// import, don't show an error for it.
if (codeFolderPackages != null) {
String itemPkg = item.substring(0, item.lastIndexOf('.'));
for (String pkg : codeFolderPackages) {
if (pkg.equals(itemPkg)) {
found = true;
break;
}
}
}
if (ignorableImport(item)) {
found = true;
}
if (!found) {
System.err.println("No library found for " + entry);
}
}
}
// PApplet.println(PApplet.split(libraryPath, File.pathSeparatorChar));
// Finally, add the regular Java CLASSPATH. This contains everything
// imported by the PDE itself (core.jar, pde.jar, quaqua.jar) which may
// in fact be more of a problem.
String javaClassPath = System.getProperty("java.class.path");
// Remove quotes if any.. A messy (and frequent) Windows problem
if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) {
javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1);
}
classPath += File.pathSeparator + javaClassPath;
// But make sure that there isn't anything in there that's missing,
// otherwise ECJ will complain and die. For instance, Java 1.7 (or maybe
// it's appbundler?) adds Java/Classes to the path, which kills us.
//String[] classPieces = PApplet.split(classPath, File.pathSeparator);
// Nah, nevermind... we'll just create the @!#$! folder until they fix it.
// 3. then loop over the code[] and save each .java file
for (SketchCode sc : sketch.getCode()) {
if (sc.isExtension("java")) {
// In most cases, no pre-processing services necessary for Java files.
// Just write the the contents of 'program' to a .java file
// into the build directory. However, if a default package is being
// used (as in Android), and no package is specified in the source,
// then we need to move this code to the same package as the sketch.
// Otherwise, the class may not be found, or at a minimum, the default
// access across the packages will mean that things behave incorrectly.
// For instance, desktop code that uses a .java file with no packages,
// will be fine with the default access, but since Android's PApplet
// requires a package, code from that (default) package (such as the
// PApplet itself) won't have access to methods/variables from the
// package-less .java file (unless they're all marked public).
String filename = sc.getFileName();
try {
String javaCode = sc.getProgram();
String[] packageMatch = PApplet.match(javaCode, PACKAGE_REGEX);
// if no package, and a default package is being used
// (i.e. on Android) we'll have to add one
if (packageMatch == null && packageName == null) {
sc.copyTo(new File(srcFolder, filename));
} else {
if (packageMatch == null) {
// use the default package name, since mixing with package-less code will break
packageMatch = new String[] { packageName };
// add the package name to the source before writing it
javaCode = "package " + packageName + ";" + javaCode;
}
File packageFolder = new File(srcFolder, packageMatch[0].replace('.', '/'));
packageFolder.mkdirs();
Base.saveFile(javaCode, new File(packageFolder, filename));
}
} catch (IOException e) {
e.printStackTrace();
String msg = "Problem moving " + filename + " to the build folder";
throw new SketchException(msg);
}
} else if (sc.isExtension("pde")) {
// The compiler and runner will need this to have a proper offset
sc.addPreprocOffset(result.headerOffset);
}
}
foundMain = preprocessor.hasMethod("main");
return result.className;
}
/**
* Returns true if this package isn't part of a library (it's a system import
* or something like that). Don't bother complaining about java.* or javax.*
* because it's probably in boot.class.path. But we're not checking against
* that path since it's enormous. Unfortunately we do still have to check
* for libraries that begin with a prefix like javax, since that includes
* the OpenGL library, even though we're just returning true here, hrm...
*/
protected boolean ignorableImport(String pkg) {
if (pkg.startsWith("java.")) return true;
if (pkg.startsWith("javax.")) return true;
if (pkg.startsWith("processing.core.")) return true;
if (pkg.startsWith("processing.data.")) return true;
if (pkg.startsWith("processing.event.")) return true;
if (pkg.startsWith("processing.opengl.")) return true;
// // ignore core, data, and opengl packages
// String[] coreImports = preprocessor.getCoreImports();
// for (int i = 0; i < coreImports.length; i++) {
// String imp = coreImports[i];
// if (imp.endsWith(".*")) {
// imp = imp.substring(0, imp.length() - 2);
// }
// if (pkg.startsWith(imp)) {
// return true;
// }
// }
return false;
}
protected int findErrorFile(int errorLine) {
for (int i = sketch.getCodeCount() - 1; i > 0; i--) {
SketchCode sc = sketch.getCode(i);
if (sc.isExtension("pde") && (sc.getPreprocOffset() <= errorLine)) {
// keep looping until the errorLine is past the offset
return i;
}
}
return 0; // i give up
}
/**
* Path to the folder that will contain processed .java source files. Not
* the location for .pde files, since that can be obtained from the sketch.
*/
public File getSrcFolder() {
return srcFolder;
}
public File getBinFolder() {
return binFolder;
}
/**
* Absolute path to the sketch folder. Used to set the working directry of
* the sketch when running, i.e. so that saveFrame() goes to the right
* location when running from the PDE, instead of the same folder as the
* Processing.exe or the root of the user's home dir.
*/
public String getSketchPath() {
return sketch.getFolder().getAbsolutePath();
}
/** Class path determined during build. */
public String getClassPath() {
return classPath;
}
/** Return the java.library.path for this sketch (for all the native DLLs etc). */
public String getJavaLibraryPath() {
return javaLibraryPath;
}
/**
* Whether the preprocessor found a main() method. If main() is found, then
* it will be used to launch the sketch instead of PApplet.main().
*/
public boolean getFoundMain() {
return foundMain;
}
/**
* Get the list of imported libraries. Used by external tools like Android mode.
* @return list of library folders connected to this sketch.
*/
public ArrayList<Library> getImportedLibraries() {
return importedLibraries;
}
/**
* Map an error from a set of processed .java files back to its location
* in the actual sketch.
* @param message The error message.
* @param filename The .java file where the exception was found.
* @param line Line number of the .java file for the exception (1-indexed)
* @return A RunnerException to be sent to the editor, or null if it wasn't
* possible to place the exception to the sketch code.
*/
// public RunnerException placeExceptionAlt(String message,
// String filename, int line) {
// String appletJavaFile = appletClassName + ".java";
// SketchCode errorCode = null;
// if (filename.equals(appletJavaFile)) {
// for (SketchCode code : getCode()) {
// if (code.isExtension("pde")) {
// if (line >= code.getPreprocOffset()) {
// errorCode = code;
// }
// }
// }
// } else {
// for (SketchCode code : getCode()) {
// if (code.isExtension("java")) {
// if (filename.equals(code.getFileName())) {
// errorCode = code;
// }
// }
// }
// }
// int codeIndex = getCodeIndex(errorCode);
//
// if (codeIndex != -1) {
// //System.out.println("got line num " + lineNumber);
// // in case this was a tab that got embedded into the main .java
// line -= getCode(codeIndex).getPreprocOffset();
//
// // lineNumber is 1-indexed, but editor wants zero-indexed
// line--;
//
// // getMessage() will be what's shown in the editor
// RunnerException exception =
// new RunnerException(message, codeIndex, line, -1);
// exception.hideStackTrace();
// return exception;
// }
// return null;
// }
/**
* Map an error from a set of processed .java files back to its location
* in the actual sketch.
* @param message The error message.
* @param filename The .java file where the exception was found.
* @param line Line number of the .java file for the exception (0-indexed!)
* @return A RunnerException to be sent to the editor, or null if it wasn't
* possible to place the exception to the sketch code.
*/
public SketchException placeException(String message,
String dotJavaFilename,
int dotJavaLine) {
int codeIndex = 0; //-1;
int codeLine = -1;
// System.out.println("placing " + dotJavaFilename + " " + dotJavaLine);
// System.out.println("code count is " + getCodeCount());
// first check to see if it's a .java file
for (int i = 0; i < sketch.getCodeCount(); i++) {
SketchCode code = sketch.getCode(i);
if (code.isExtension("java")) {
if (dotJavaFilename.equals(code.getFileName())) {
codeIndex = i;
codeLine = dotJavaLine;
return new SketchException(message, codeIndex, codeLine);
}
}
}
// If not the preprocessed file at this point, then need to get out
if (!dotJavaFilename.equals(sketch.getName() + ".java")) {
return null;
}
// if it's not a .java file, codeIndex will still be 0
// this section searches through the list of .pde files
codeIndex = 0;
for (int i = 0; i < sketch.getCodeCount(); i++) {
SketchCode code = sketch.getCode(i);
if (code.isExtension("pde")) {
// System.out.println("preproc offset is " + code.getPreprocOffset());
// System.out.println("looking for line " + dotJavaLine);
if (code.getPreprocOffset() <= dotJavaLine) {
codeIndex = i;
// System.out.println("i'm thinkin file " + i);
codeLine = dotJavaLine - code.getPreprocOffset();
}
}
}
// could not find a proper line number, so deal with this differently.
// but if it was in fact the .java file we're looking for, though,
// send the error message through.
// this is necessary because 'import' statements will be at a line
// that has a lower number than the preproc offset, for instance.
// if (codeLine == -1 && !dotJavaFilename.equals(name + ".java")) {
// return null;
// }
// return new SketchException(message, codeIndex, codeLine);
return new SketchException(message, codeIndex, codeLine, -1, false); // changed for 0194 for compile errors, but...
}
/*
protected boolean exportApplet() throws SketchException, IOException {
return exportApplet(new File(sketch.getFolder(), "applet"));
}
*/
/**
* Handle export to applet.
*/
/*
public boolean exportApplet(File appletFolder) throws SketchException, IOException {
mode.prepareExportFolder(appletFolder);
srcFolder = sketch.makeTempFolder();
binFolder = sketch.makeTempFolder();
String foundName = build(srcFolder, binFolder, true);
// (already reported) error during export, exit this function
if (foundName == null) return false;
// If name != exportSketchName, then that's weirdness
// BUG unfortunately, that can also be a bug in the preproc :(
if (!sketch.getName().equals(foundName)) {
Base.showWarning("Error during export",
"Sketch name is " + sketch.getName() + " but the\n" +
"name found in the code was " + foundName + ".", null);
return false;
}
String[] sizeInfo =
PdePreprocessor.parseSketchSize(sketch.getMainProgram(), false);
int sketchWidth = PApplet.DEFAULT_WIDTH;
int sketchHeight = PApplet.DEFAULT_HEIGHT;
boolean openglApplet = false;
boolean foundSize = false;
if (sizeInfo != null) {
try {
if (sizeInfo[1] != null && sizeInfo[2] != null) {
sketchWidth = Integer.parseInt(sizeInfo[1]);
sketchHeight = Integer.parseInt(sizeInfo[2]);
foundSize = true;
}
} catch (Exception e) {
e.printStackTrace();
// parsing errors, whatever; ignored
}
String sketchRenderer = sizeInfo[3];
if (sketchRenderer != null) {
if (sketchRenderer.equals("P2D") ||
sketchRenderer.equals("P3D") ||
sketchRenderer.equals("OPENGL")) {
openglApplet = true;
}
}
}
if (!foundSize) {
final String message =
"The size of this applet could not automatically be\n" +
"determined from your code. You'll have to edit the\n" +
"HTML file to set the size of the applet.\n" +
"Use only numeric values (not variables) for the size()\n" +
"command. See the size() reference for an explanation.";
Base.showWarning("Could not find applet size", message, null);
}
// // If the renderer is set to the built-in OpenGL library,
// // then it's definitely an OpenGL applet.
// if (sketchRenderer.equals("P3D") || sketchRenderer.equals("OPENGL")) {
// openglApplet = true;
// }
// int wide = PApplet.DEFAULT_WIDTH;
// int high = PApplet.DEFAULT_HEIGHT;
// String renderer = "";
//
// String scrubbed = PdePreprocessor.scrubComments(sketch.getCode(0).getProgram());
// String[] matches = PApplet.match(scrubbed, PdePreprocessor.SIZE_REGEX);
//
// if (matches != null) {
// try {
// wide = Integer.parseInt(matches[1]);
// high = Integer.parseInt(matches[2]);
//
// // Adding back the trim() for 0136 to handle Bug #769
// if (matches.length == 4) renderer = matches[3].trim();
// // Actually, matches.length should always be 4...
//
// } catch (NumberFormatException e) {
// // found a reference to size, but it didn't
// // seem to contain numbers
// final String message =
// "The size of this applet could not automatically be\n" +
// "determined from your code. You'll have to edit the\n" +
// "HTML file to set the size of the applet.\n" +
// "Use only numeric values (not variables) for the size()\n" +
// "command. See the size() reference for an explanation.";
//
// Base.showWarning("Could not find applet size", message, null);
// }
// } // else no size() command found
// Grab the Javadoc-style description from the main code.
String description = "";
// If there are multiple closings, need to catch the first,
// which is what the (.*?) will do for us.
// http://code.google.com/p/processing/issues/detail?id=877
String[] javadoc = PApplet.match(sketch.getCode(0).getProgram(), "/\\*{2,}(.*?)\\*+/");
if (javadoc != null) {
StringBuffer dbuffer = new StringBuffer();
String found = javadoc[1];
String[] pieces = PApplet.split(found, '\n');
for (String line : pieces) {
// if this line starts with * characters, remove 'em
String[] m = PApplet.match(line, "^\\s*\\*+(.*)");
dbuffer.append(m != null ? m[1] : line);
// insert the new line into the html to help w/ line breaks
dbuffer.append('\n');
}
description = dbuffer.toString();
}
// Add links to all the code
StringBuffer sources = new StringBuffer();
//for (int i = 0; i < codeCount; i++) {
for (SketchCode code : sketch.getCode()) {
sources.append("<a href=\"" + code.getFileName() + "\">" +
code.getPrettyName() + "</a> ");
}
// Copy the source files to the target, since we like
// to encourage people to share their code
// for (int i = 0; i < codeCount; i++) {
for (SketchCode code : sketch.getCode()) {
try {
File exportedSource = new File(appletFolder, code.getFileName());
//Base.copyFile(code[i].getFile(), exportedSource);
code.copyTo(exportedSource);
} catch (IOException e) {
e.printStackTrace(); // ho hum, just move on...
}
}
// move the .java file from the preproc there too
String preprocFilename = sketch.getName() + ".java";
File preprocFile = new File(srcFolder, preprocFilename);
if (preprocFile.exists()) {
preprocFile.renameTo(new File(appletFolder, preprocFilename));
} else {
System.err.println("Could not copy source file: " + preprocFile.getAbsolutePath());
}
// Use separate .jar files whenever a library or code folder is in use.
boolean separateJar =
Preferences.getBoolean("export.applet.separate_jar_files") ||
sketch.hasCodeFolder() ||
javaLibraryPath.length() != 0;
File skeletonFolder = mode.getContentFile("applet");
// Copy the loading gif to the applet
String LOADING_IMAGE = "loading.gif";
// Check if the user already has their own loader image
File loadingImage = new File(sketch.getFolder(), LOADING_IMAGE);
if (!loadingImage.exists()) {
// File skeletonFolder = new File(Base.getContentFile("lib"), "export");
loadingImage = new File(skeletonFolder, LOADING_IMAGE);
}
Base.copyFile(loadingImage, new File(appletFolder, LOADING_IMAGE));
// not a good idea after all
// File deployFile = new File(skeletonFolder, "deployJava.js");
// Base.copyFile(deployFile, new File(appletFolder, "deployJava.js"));
// Create new .jar file
FileOutputStream zipOutputFile =
new FileOutputStream(new File(appletFolder, sketch.getName() + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// ZipEntry entry;
StringBuffer archives = new StringBuffer();
archives.append(sketch.getName() + ".jar");
// Add the manifest file
addManifest(zos);
// File openglLibraryFolder =
// new File(editor.getMode().getLibrariesFolder(), "opengl/library");
// String openglLibraryPath = openglLibraryFolder.getAbsolutePath();
// boolean openglApplet = false;
HashMap<String,Object> zipFileContents = new HashMap<String,Object>();
// add contents of 'library' folders
for (Library library : importedLibraries) {
// if (library.getPath().equals(openglLibraryPath)) {
if (library.getName().equals("OpenGL")) {
openglApplet = true;
}
for (File exportFile : library.getAppletExports()) {
String exportName = exportFile.getName();
if (!exportFile.exists()) {
System.err.println("File " + exportFile.getAbsolutePath() + " does not exist");
} else if (exportFile.isDirectory()) {
System.out.println("Ignoring sub-folder \"" + exportFile.getAbsolutePath() + "\"");
} else if (exportName.toLowerCase().endsWith(".zip") ||
exportName.toLowerCase().endsWith(".jar")) {
if (separateJar) {
Base.copyFile(exportFile, new File(appletFolder, exportName));
archives.append("," + exportName);
} else {
String path = exportFile.getAbsolutePath();
packClassPathIntoZipFile(path, zos, zipFileContents);
}
} else { // just copy the file over.. prolly a .dll or something
Base.copyFile(exportFile, new File(appletFolder, exportName));
}
}
}
// Copy core.jar, or add its contents to the output .jar file
File bagelJar = Base.isMacOS() ?
Base.getContentFile("core.jar") :
Base.getContentFile("lib/core.jar");
if (separateJar) {
Base.copyFile(bagelJar, new File(appletFolder, "core.jar"));
archives.append(",core.jar");
} else {
String bagelJarPath = bagelJar.getAbsolutePath();
packClassPathIntoZipFile(bagelJarPath, zos, zipFileContents);
}
if (sketch.hasCodeFolder()) {
File[] codeJarFiles = sketch.getCodeFolder().listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.charAt(0) == '.') return false;
if (name.toLowerCase().endsWith(".jar")) return true;
if (name.toLowerCase().endsWith(".zip")) return true;
return false;
}
});
for (File exportFile : codeJarFiles) {
String name = exportFile.getName();
Base.copyFile(exportFile, new File(appletFolder, name));
archives.append("," + name);
}
}
// Add the data folder to the output .jar file
addDataFolder(zos);
// add the project's .class files to the jar
// just grabs everything from the build directory
// since there may be some inner classes
// (add any .class files from the applet dir, then delete them)
// TODO this needs to be recursive (for packages)
addClasses(zos, binFolder);
// close up the jar file
zos.flush();
zos.close();
//
// convert the applet template
// @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@
// and now @@description@@
File htmlOutputFile = new File(appletFolder, "index.html");
// UTF-8 fixes http://dev.processing.org/bugs/show_bug.cgi?id=474
PrintWriter htmlWriter = PApplet.createWriter(htmlOutputFile);
InputStream is = null;
// if there is an applet.html file in the sketch folder, use that
File customHtml = new File(sketch.getFolder(), "applet.html");
if (customHtml.exists()) {
is = new FileInputStream(customHtml);
}
// for (File libraryFolder : importedLibraries) {
// System.out.println(libraryFolder + " " + libraryFolder.getAbsolutePath());
// }
if (is == null) {
if (openglApplet) {
is = mode.getContentStream("applet/template-opengl.html");
} else {
is = mode.getContentStream("applet/template.html");
}
}
BufferedReader reader = PApplet.createReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (line.indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(line);
int index = 0;
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
sketch.getName());
}
while ((index = sb.indexOf("@@source@@")) != -1) {
sb.replace(index, index + "@@source@@".length(),
sources.toString());
}
while ((index = sb.indexOf("@@archive@@")) != -1) {
sb.replace(index, index + "@@archive@@".length(),
archives.toString());
}
while ((index = sb.indexOf("@@width@@")) != -1) {
sb.replace(index, index + "@@width@@".length(),
String.valueOf(sketchWidth));
}
while ((index = sb.indexOf("@@height@@")) != -1) {
sb.replace(index, index + "@@height@@".length(),
String.valueOf(sketchHeight));
}
while ((index = sb.indexOf("@@description@@")) != -1) {
sb.replace(index, index + "@@description@@".length(),
description);
}
line = sb.toString();
}
htmlWriter.println(line);
}
reader.close();
htmlWriter.flush();
htmlWriter.close();
return true;
}
*/
/**
* Export to application via GUI.
*/
protected boolean exportApplication() throws IOException, SketchException {
// Do the build once, so that we know what libraries are in use (and what
// the situation is with their native libs), and also for efficiency of
// not redoing the compilation for each platform. In particular, though,
// importedLibraries won't be set until the preprocessing has finished,
// so we have to do that before the stuff below.
String foundName = build(true);
// (already reported) error during export, exit this function
if (foundName == null) return false;
// if name != exportSketchName, then that's weirdness
// BUG unfortunately, that can also be a bug in the preproc :(
if (!sketch.getName().equals(foundName)) {
Base.showWarning("Error during export",
"Sketch name is " + sketch.getName() + " but the sketch\n" +
"name in the code was " + foundName, null);
return false;
}
/*
File folder = null;
for (String platformName : PConstants.platformNames) {
int platform = Base.getPlatformIndex(platformName);
if (Preferences.getBoolean("export.application.platform." + platformName)) {
if (Library.hasMultipleArch(platform, importedLibraries)) {
// export the 32-bit version
folder = new File(sketch.getFolder(), "application." + platformName + "32");
if (!exportApplication(folder, platform, 32)) {
return false;
}
// export the 64-bit version
folder = new File(sketch.getFolder(), "application." + platformName + "64");
if (!exportApplication(folder, platform, 64)) {
return false;
}
} else { // just make a single one for this platform
folder = new File(sketch.getFolder(), "application." + platformName);
if (!exportApplication(folder, platform, 0)) {
return false;
}
}
}
}
*/
File folder = null;
String platformName = Base.getPlatformName();
boolean embedJava = Preferences.getBoolean("export.application.embed_java");
if (Library.hasMultipleArch(PApplet.platform, importedLibraries)) {
if (Base.getNativeBits() == 32) {
// export the 32-bit version
folder = new File(sketch.getFolder(), "application." + platformName + "32");
if (!exportApplication(folder, PApplet.platform, 32, embedJava)) {
return false;
}
} else if (Base.getNativeBits() == 64) {
// export the 64-bit version
folder = new File(sketch.getFolder(), "application." + platformName + "64");
if (!exportApplication(folder, PApplet.platform, 64, embedJava)) {
return false;
}
}
} else { // just make a single one for this platform
folder = new File(sketch.getFolder(), "application." + platformName);
if (!exportApplication(folder, PApplet.platform, 0, embedJava)) {
return false;
}
}
return true; // all good
}
/**
* Export to application without GUI. Also called by the Commander.
*/
protected boolean exportApplication(File destFolder,
int exportPlatform,
int exportBits,
boolean embedJava) throws IOException, SketchException {
// TODO this should probably be a dialog box instead of a warning
// on the terminal. And the message should be written better than this.
// http://code.google.com/p/processing/issues/detail?id=884
for (Library library : importedLibraries) {
if (!library.supportsArch(exportPlatform, exportBits)) {
String pn = PConstants.platformNames[exportPlatform];
Base.showWarning("Quibbles 'n Bits",
"The application." + pn + exportBits +
" folder will not be created\n" +
"because no " + exportBits + "-bit version of " +
library.getName() + " is available for " + pn, null);
return true; // don't cancel all exports for this, just move along
}
}
/// prep the output directory
mode.prepareExportFolder(destFolder);
/// figure out where the jar files will be placed
File jarFolder = new File(destFolder, "lib");
/// where all the skeleton info lives
/// on macosx, need to copy .app skeleton since that's
/// also where the jar files will be placed
File dotAppFolder = null;
// String jdkFolderName = null;
String jvmRuntime = "";
if (exportPlatform == PConstants.MACOSX) {
dotAppFolder = new File(destFolder, sketch.getName() + ".app");
File contentsOrig = new File(Base.getJavaHome(), "../../../../..");
if (embedJava) {
File jdkFolder = new File(Base.getJavaHome(), "../../..");
String jdkFolderName = jdkFolder.getCanonicalFile().getName();
jvmRuntime = "<key>JVMRuntime</key>\n <string>" + jdkFolderName + "</string>";
}
// File dotAppSkeleton = mode.getContentFile("application/template.app");
// Base.copyDir(dotAppSkeleton, dotAppFolder);
File contentsFolder = new File(dotAppFolder, "Contents");
contentsFolder.mkdirs();
// Info.plist will be written later
// set the jar folder to a different location than windows/linux
//jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
jarFolder = new File(contentsFolder, "Java");
File macosFolder = new File(contentsFolder, "MacOS");
macosFolder.mkdirs();
Base.copyFile(new File(contentsOrig, "MacOS/Processing"),
new File(contentsFolder, "MacOS/" + sketch.getName()));
File pkgInfo = new File(contentsFolder, "PkgInfo");
PrintWriter writer = PApplet.createWriter(pkgInfo);
writer.println("APPL????");
writer.flush();
writer.close();
// Use faster(?) native copy here (also to do sym links)
if (embedJava) {
Base.copyDirNative(new File(contentsOrig, "PlugIns"),
new File(contentsFolder, "PlugIns"));
}
File resourcesFolder = new File(contentsFolder, "Resources");
Base.copyDir(new File(contentsOrig, "Resources/en.lproj"),
new File(resourcesFolder, "en.lproj"));
Base.copyFile(mode.getContentFile("application/sketch.icns"),
new File(resourcesFolder, "sketch.icns"));
/*
String stubName = "Contents/MacOS/JavaApplicationStub";
// need to set the stub to executable
// will work on osx or *nix, but just dies on windows, oh well..
if (Base.isWindows()) {
File warningFile = new File(destFolder, "readme.txt");
PrintWriter pw = PApplet.createWriter(warningFile);
pw.println("This application was created on Windows, which does not");
pw.println("properly support setting files as \"executable\",");
pw.println("a necessity for applications on Mac OS X.");
pw.println();
pw.println("To fix this, use the Terminal on Mac OS X, and from this");
pw.println("directory, type the following:");
pw.println();
pw.println("chmod +x " + dotAppFolder.getName() + "/" + stubName);
pw.flush();
pw.close();
} else {
File stubFile = new File(dotAppFolder, stubName);
String stubPath = stubFile.getAbsolutePath();
Runtime.getRuntime().exec(new String[] { "chmod", "+x", stubPath });
}
*/
} else if (exportPlatform == PConstants.LINUX) {
if (embedJava) {
Base.copyDirNative(Base.getJavaHome(), new File(destFolder, "java"));
}
} else if (exportPlatform == PConstants.WINDOWS) {
if (embedJava) {
Base.copyDir(Base.getJavaHome(), new File(destFolder, "java"));
}
}
/// make the jar folder (all platforms)
if (!jarFolder.exists()) jarFolder.mkdirs();
/// on windows, copy the exe file
if (exportPlatform == PConstants.WINDOWS) {
if (exportBits == 64) {
// We don't yet have a 64-bit launcher, so this is a workaround for now.
File batFile = new File(destFolder, sketch.getName() + ".bat");
PrintWriter writer = PApplet.createWriter(batFile);
writer.println("@echo off");
writer.println("java -Djava.ext.dirs=lib -Djava.library.path=lib " + sketch.getName());
writer.flush();
writer.close();
} else {
Base.copyFile(mode.getContentFile("application/template.exe"),
new File(destFolder, sketch.getName() + ".exe"));
}
}
/// start copying all jar files
Vector<String> jarListVector = new Vector<String>();
/// create the main .jar file
// HashMap<String,Object> zipFileContents = new HashMap<String,Object>();
FileOutputStream zipOutputFile =
new FileOutputStream(new File(jarFolder, sketch.getName() + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// ZipEntry entry;
// add the manifest file so that the .jar can be double clickable
addManifest(zos);
// add the project's .class files to the jar
// (just grabs everything from the build directory,
// since there may be some inner classes)
// TODO this needs to be recursive (for packages)
// File classFiles[] = tempClassesFolder.listFiles(new FilenameFilter() {
// public boolean accept(File dir, String name) {
// return name.endsWith(".class");
// }
// });
// for (File file : classFiles) {
// entry = new ZipEntry(file.getName());
// zos.putNextEntry(entry);
// zos.write(Base.loadBytesRaw(file));
// zos.closeEntry();
// }
addClasses(zos, binFolder);
// add the data folder to the main jar file
// addDataFolder(zos);
// For 2.0a2, make the data folder a separate directory, rather than
// packaging potentially large files into the JAR. On OS X, we have to hide
// the folder inside the .app package, while Linux and Windows will have a
// 'data' folder next to 'lib'.
if (sketch.hasDataFolder()) {
if (exportPlatform == PConstants.MACOSX) {
Base.copyDir(sketch.getDataFolder(), new File(jarFolder, "data"));
} else {
Base.copyDir(sketch.getDataFolder(), new File(destFolder, "data"));
}
}
// add the contents of the code folder to the jar
if (sketch.hasCodeFolder()) {
String includes = Base.contentsToClassPath(sketch.getCodeFolder());
// Use tokens to get rid of extra blanks, which causes huge exports
String[] codeList = PApplet.splitTokens(includes, File.pathSeparator);
// String cp = "";
for (int i = 0; i < codeList.length; i++) {
if (codeList[i].toLowerCase().endsWith(".jar") ||
codeList[i].toLowerCase().endsWith(".zip")) {
File exportFile = new File(codeList[i]);
String exportFilename = exportFile.getName();
Base.copyFile(exportFile, new File(jarFolder, exportFilename));
jarListVector.add(exportFilename);
} else {
// cp += codeList[i] + File.pathSeparator;
}
}
// packClassPathIntoZipFile(cp, zos, zipFileContents); // this was double adding the code folder prior to 2.0a2
}
zos.flush();
zos.close();
jarListVector.add(sketch.getName() + ".jar");
// /// add core.jar to the jar destination folder
//
// File bagelJar = Base.isMacOS() ?
// Base.getContentFile("core.jar") :
// Base.getContentFile("lib/core.jar");
// Base.copyFile(bagelJar, new File(jarFolder, "core.jar"));
// jarListVector.add("core.jar");
/// add contents of 'library' folders to the export
for (Library library : importedLibraries) {
// add each item from the library folder / export list to the output
for (File exportFile : library.getApplicationExports(exportPlatform, exportBits)) {
// System.out.println("export: " + exportFile);
String exportName = exportFile.getName();
if (!exportFile.exists()) {
System.err.println(exportFile.getName() +
" is mentioned in export.txt, but it's " +
"a big fat lie and does not exist.");
} else if (exportFile.isDirectory()) {
//System.err.println("Ignoring sub-folder \"" + exportList[i] + "\"");
// if (exportPlatform == PConstants.MACOSX) {
// // For OS X, copy subfolders to Contents/Resources/Java
Base.copyDir(exportFile, new File(jarFolder, exportName));
// } else {
// // For other platforms, just copy the folder to the same directory
// // as the application.
// Base.copyDir(exportFile, new File(destFolder, exportName));
// }
} else if (exportName.toLowerCase().endsWith(".zip") ||
exportName.toLowerCase().endsWith(".jar")) {
Base.copyFile(exportFile, new File(jarFolder, exportName));
jarListVector.add(exportName);
// old style, prior to 2.0a2
// } else if ((exportPlatform == PConstants.MACOSX) &&
// (exportFile.getName().toLowerCase().endsWith(".jnilib"))) {
// // jnilib files can be placed in Contents/Resources/Java
// Base.copyFile(exportFile, new File(jarFolder, exportName));
//
// } else {
// // copy the file to the main directory.. prolly a .dll or something
// Base.copyFile(exportFile, new File(destFolder, exportName));
// }
// first 2.0a2 attempt, until below...
// } else if (exportPlatform == PConstants.MACOSX) {
// Base.copyFile(exportFile, new File(jarFolder, exportName));
//
// } else {
// Base.copyFile(exportFile, new File(destFolder, exportName));
} else {
// Starting with 2.0a2 put extra export files (DLLs, plugins folder,
// anything else for libraries) inside lib or Contents/Resources/Java
Base.copyFile(exportFile, new File(jarFolder, exportName));
}
}
}
/// create platform-specific CLASSPATH based on included jars
String jarList[] = new String[jarListVector.size()];
jarListVector.copyInto(jarList);
StringBuffer exportClassPath = new StringBuffer();
if (exportPlatform == PConstants.MACOSX) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$JAVAROOT/" + jarList[i]);
}
} else if (exportPlatform == PConstants.WINDOWS) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(",");
exportClassPath.append(jarList[i]);
}
} else {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$APPDIR/lib/" + jarList[i]);
}
}
/// figure out run options for the VM
// this is too vague. if anyone is using it, we can bring it back
// String runOptions = Preferences.get("run.options");
List<String> runOptions = new ArrayList<String>();
if (Preferences.getBoolean("run.options.memory")) {
runOptions.add("-Xms" + Preferences.get("run.options.memory.initial") + "m");
runOptions.add("-Xmx" + Preferences.get("run.options.memory.maximum") + "m");
}
StringBuilder jvmOptionsList = new StringBuilder();
for (String opt : runOptions) {
jvmOptionsList.append(" <string>");
jvmOptionsList.append(opt);
jvmOptionsList.append("</string>");
jvmOptionsList.append('\n');
}
// if (exportPlatform == PConstants.MACOSX) {
// // If no bits specified (libs are all universal, or no native libs)
// // then exportBits will be 0, and can be controlled via "Get Info".
// // Otherwise, need to specify the bits as a VM option.
// if (exportBits == 32) {
// runOptions += " -d32";
// } else if (exportBits == 64) {
// runOptions += " -d64";
// }
// }
/// macosx: write out Info.plist (template for classpath, etc)
if (exportPlatform == PConstants.MACOSX) {
//String PLIST_TEMPLATE = "template.plist";
String PLIST_TEMPLATE = "Info.plist.tmpl";
File plistTemplate = new File(sketch.getFolder(), PLIST_TEMPLATE);
if (!plistTemplate.exists()) {
//plistTemplate = mode.getContentFile("application/template.plist");
plistTemplate = mode.getContentFile("application/Info.plist.tmpl");
}
File plistFile = new File(dotAppFolder, "Contents/Info.plist");
PrintWriter pw = PApplet.createWriter(plistFile);
String lines[] = PApplet.loadStrings(plistTemplate);
for (int i = 0; i < lines.length; i++) {
if (lines[i].indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(lines[i]);
int index = 0;
while ((index = sb.indexOf("@@jvm_runtime@@")) != -1) {
sb.replace(index, index + "@@jvm_runtime@@".length(),
jvmRuntime);
}
while ((index = sb.indexOf("@@jvm_options_list@@")) != -1) {
sb.replace(index, index + "@@jvm_options_list@@".length(),
jvmOptionsList.toString());
}
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
sketch.getName());
}
// while ((index = sb.indexOf("@@classpath@@")) != -1) {
// sb.replace(index, index + "@@classpath@@".length(),
// exportClassPath.toString());
// }
while ((index = sb.indexOf("@@lsuipresentationmode@@")) != -1) {
sb.replace(index, index + "@@lsuipresentationmode@@".length(),
Preferences.getBoolean("export.application.fullscreen") ? "4" : "0");
}
// while ((index = sb.indexOf("@@lsarchitecturepriority@@")) != -1) {
// // More about this mess: http://support.apple.com/kb/TS2827
// // First default to exportBits == 0 case
// String arch = "<string>x86_64</string>\n <string>i386</string>";
// if (exportBits == 32) {
// arch = "<string>i386</string>";
// } else if (exportBits == 64) {
// arch = "<string>x86_64</string>";
// }
// sb.replace(index, index + "@@lsarchitecturepriority@@".length(), arch);
// }
lines[i] = sb.toString();
}
// explicit newlines to avoid Windows CRLF
pw.print(lines[i] + "\n");
}
pw.flush();
pw.close();
} else if (exportPlatform == PConstants.WINDOWS) {
File argsFile = new File(destFolder + "/lib/args.txt");
PrintWriter pw = PApplet.createWriter(argsFile);
// Since this is only on Windows, make sure we use Windows CRLF
- pw.print(runOptions + "\r\n");
+ pw.print(PApplet.join(runOptions.toArray(new String[0]), " ") + "\r\n");
pw.print(sketch.getName() + "\r\n");
pw.print(exportClassPath);
pw.flush();
pw.close();
} else {
File shellScript = new File(destFolder, sketch.getName());
PrintWriter pw = PApplet.createWriter(shellScript);
// Do the newlines explicitly so that Windows CRLF
// isn't used when exporting for Unix.
pw.print("#!/bin/sh\n\n");
//ps.print("APPDIR=`dirname $0`\n");
pw.print("APPDIR=$(dirname \"$0\")\n"); // more posix compliant
// another fix for bug #234, LD_LIBRARY_PATH ignored on some platforms
//ps.print("LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$APPDIR\n");
pw.print("java " + Preferences.get("run.options") +
" -Djava.library.path=\"$APPDIR:$APPDIR/lib\"" +
" -cp \"" + exportClassPath + "\"" +
" " + sketch.getName() + " \"$@\"\n");
pw.flush();
pw.close();
String shellPath = shellScript.getAbsolutePath();
// will work on osx or *nix, but just dies on windows, oh well..
if (!Base.isWindows()) {
Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
}
}
/// copy the source files to the target
/// (we like to encourage people to share their code)
File sourceFolder = new File(destFolder, "source");
sourceFolder.mkdirs();
for (SketchCode code : sketch.getCode()) {
try {
code.copyTo(new File(sourceFolder, code.getFileName()));
} catch (IOException e) {
e.printStackTrace();
}
}
// move the .java file from the preproc there too
String preprocFilename = sketch.getName() + ".java";
File preprocFile = new File(srcFolder, preprocFilename);
if (preprocFile.exists()) {
Base.copyFile(preprocFile, new File(sourceFolder, preprocFilename));
} else {
System.err.println("Could not copy source file: " + preprocFile.getAbsolutePath());
}
/// remove the .class files from the export folder.
// for (File file : classFiles) {
// if (!file.delete()) {
// Base.showWarning("Could not delete",
// file.getName() + " could not \n" +
// "be deleted from the applet folder. \n" +
// "You'll need to remove it by hand.", null);
// }
// }
// these will now be removed automatically via the temp folder deleteOnExit()
/// goodbye
return true;
}
protected void addManifest(ZipOutputStream zos) throws IOException {
ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
zos.putNextEntry(entry);
String contents =
"Manifest-Version: 1.0\n" +
"Created-By: Processing " + Base.getVersionName() + "\n" +
"Main-Class: " + sketch.getName() + "\n"; // TODO not package friendly
zos.write(contents.getBytes());
zos.closeEntry();
}
protected void addClasses(ZipOutputStream zos, File dir) throws IOException {
String path = dir.getAbsolutePath();
if (!path.endsWith("/") && !path.endsWith("\\")) {
path += '/';
}
// System.out.println("path is " + path);
addClasses(zos, dir, path);
}
protected void addClasses(ZipOutputStream zos, File dir, String rootPath) throws IOException {
File files[] = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.charAt(0) != '.');
}
});
for (File sub : files) {
String relativePath = sub.getAbsolutePath().substring(rootPath.length());
// System.out.println("relative path is " + relativePath);
if (sub.isDirectory()) {
addClasses(zos, sub, rootPath);
} else if (sub.getName().endsWith(".class")) {
// System.out.println(" adding item " + relativePath);
ZipEntry entry = new ZipEntry(relativePath);
zos.putNextEntry(entry);
//zos.write(Base.loadBytesRaw(sub));
PApplet.saveStream(zos, new FileInputStream(sub));
zos.closeEntry();
}
}
}
protected void addDataFolder(ZipOutputStream zos) throws IOException {
if (sketch.hasDataFolder()) {
String[] dataFiles = Base.listFiles(sketch.getDataFolder(), false);
int offset = sketch.getFolder().getAbsolutePath().length() + 1;
for (String path : dataFiles) {
if (Base.isWindows()) {
path = path.replace('\\', '/');
}
//File dataFile = new File(dataFiles[i]);
File dataFile = new File(path);
if (!dataFile.isDirectory()) {
// don't export hidden files
// skipping dot prefix removes all: . .. .DS_Store
if (dataFile.getName().charAt(0) != '.') {
ZipEntry entry = new ZipEntry(path.substring(offset));
zos.putNextEntry(entry);
//zos.write(Base.loadBytesRaw(dataFile));
PApplet.saveStream(zos, new FileInputStream(dataFile));
zos.closeEntry();
}
}
}
}
}
/**
* Slurps up .class files from a colon (or semicolon on windows)
* separated list of paths and adds them to a ZipOutputStream.
*/
protected void packClassPathIntoZipFile(String path,
ZipOutputStream zos,
HashMap<String,Object> zipFileContents)
throws IOException {
String[] pieces = PApplet.split(path, File.pathSeparatorChar);
for (int i = 0; i < pieces.length; i++) {
if (pieces[i].length() == 0) continue;
// is it a jar file or directory?
if (pieces[i].toLowerCase().endsWith(".jar") ||
pieces[i].toLowerCase().endsWith(".zip")) {
try {
ZipFile file = new ZipFile(pieces[i]);
Enumeration<?> entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()) {
// actually 'continue's for all dir entries
} else {
String entryName = entry.getName();
// ignore contents of the META-INF folders
if (entryName.indexOf("META-INF") == 0) continue;
// don't allow duplicate entries
if (zipFileContents.get(entryName) != null) continue;
zipFileContents.put(entryName, new Object());
ZipEntry entree = new ZipEntry(entryName);
zos.putNextEntry(entree);
byte buffer[] = new byte[(int) entry.getSize()];
InputStream is = file.getInputStream(entry);
int offset = 0;
int remaining = buffer.length;
while (remaining > 0) {
int count = is.read(buffer, offset, remaining);
offset += count;
remaining -= count;
}
zos.write(buffer);
zos.flush();
zos.closeEntry();
}
}
} catch (IOException e) {
System.err.println("Error in file " + pieces[i]);
e.printStackTrace();
}
} else { // not a .jar or .zip, prolly a directory
File dir = new File(pieces[i]);
// but must be a dir, since it's one of several paths
// just need to check if it exists
if (dir.exists()) {
packClassPathIntoZipFileRecursive(dir, null, zos);
}
}
}
}
/**
* Continue the process of magical exporting. This function
* can be called recursively to walk through folders looking
* for more goodies that will be added to the ZipOutputStream.
*/
static protected void packClassPathIntoZipFileRecursive(File dir,
String sofar,
ZipOutputStream zos)
throws IOException {
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
// ignore . .. and .DS_Store
if (files[i].charAt(0) == '.') continue;
File sub = new File(dir, files[i]);
String nowfar = (sofar == null) ?
files[i] : (sofar + "/" + files[i]);
if (sub.isDirectory()) {
packClassPathIntoZipFileRecursive(sub, nowfar, zos);
} else {
// don't add .jar and .zip files, since they only work
// inside the root, and they're unpacked
if (!files[i].toLowerCase().endsWith(".jar") &&
!files[i].toLowerCase().endsWith(".zip") &&
files[i].charAt(0) != '.') {
ZipEntry entry = new ZipEntry(nowfar);
zos.putNextEntry(entry);
//zos.write(Base.loadBytesRaw(sub));
PApplet.saveStream(zos, new FileInputStream(sub));
zos.closeEntry();
}
}
}
}
}
| true | true | protected boolean exportApplication(File destFolder,
int exportPlatform,
int exportBits,
boolean embedJava) throws IOException, SketchException {
// TODO this should probably be a dialog box instead of a warning
// on the terminal. And the message should be written better than this.
// http://code.google.com/p/processing/issues/detail?id=884
for (Library library : importedLibraries) {
if (!library.supportsArch(exportPlatform, exportBits)) {
String pn = PConstants.platformNames[exportPlatform];
Base.showWarning("Quibbles 'n Bits",
"The application." + pn + exportBits +
" folder will not be created\n" +
"because no " + exportBits + "-bit version of " +
library.getName() + " is available for " + pn, null);
return true; // don't cancel all exports for this, just move along
}
}
/// prep the output directory
mode.prepareExportFolder(destFolder);
/// figure out where the jar files will be placed
File jarFolder = new File(destFolder, "lib");
/// where all the skeleton info lives
/// on macosx, need to copy .app skeleton since that's
/// also where the jar files will be placed
File dotAppFolder = null;
// String jdkFolderName = null;
String jvmRuntime = "";
if (exportPlatform == PConstants.MACOSX) {
dotAppFolder = new File(destFolder, sketch.getName() + ".app");
File contentsOrig = new File(Base.getJavaHome(), "../../../../..");
if (embedJava) {
File jdkFolder = new File(Base.getJavaHome(), "../../..");
String jdkFolderName = jdkFolder.getCanonicalFile().getName();
jvmRuntime = "<key>JVMRuntime</key>\n <string>" + jdkFolderName + "</string>";
}
// File dotAppSkeleton = mode.getContentFile("application/template.app");
// Base.copyDir(dotAppSkeleton, dotAppFolder);
File contentsFolder = new File(dotAppFolder, "Contents");
contentsFolder.mkdirs();
// Info.plist will be written later
// set the jar folder to a different location than windows/linux
//jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
jarFolder = new File(contentsFolder, "Java");
File macosFolder = new File(contentsFolder, "MacOS");
macosFolder.mkdirs();
Base.copyFile(new File(contentsOrig, "MacOS/Processing"),
new File(contentsFolder, "MacOS/" + sketch.getName()));
File pkgInfo = new File(contentsFolder, "PkgInfo");
PrintWriter writer = PApplet.createWriter(pkgInfo);
writer.println("APPL????");
writer.flush();
writer.close();
// Use faster(?) native copy here (also to do sym links)
if (embedJava) {
Base.copyDirNative(new File(contentsOrig, "PlugIns"),
new File(contentsFolder, "PlugIns"));
}
File resourcesFolder = new File(contentsFolder, "Resources");
Base.copyDir(new File(contentsOrig, "Resources/en.lproj"),
new File(resourcesFolder, "en.lproj"));
Base.copyFile(mode.getContentFile("application/sketch.icns"),
new File(resourcesFolder, "sketch.icns"));
/*
String stubName = "Contents/MacOS/JavaApplicationStub";
// need to set the stub to executable
// will work on osx or *nix, but just dies on windows, oh well..
if (Base.isWindows()) {
File warningFile = new File(destFolder, "readme.txt");
PrintWriter pw = PApplet.createWriter(warningFile);
pw.println("This application was created on Windows, which does not");
pw.println("properly support setting files as \"executable\",");
pw.println("a necessity for applications on Mac OS X.");
pw.println();
pw.println("To fix this, use the Terminal on Mac OS X, and from this");
pw.println("directory, type the following:");
pw.println();
pw.println("chmod +x " + dotAppFolder.getName() + "/" + stubName);
pw.flush();
pw.close();
} else {
File stubFile = new File(dotAppFolder, stubName);
String stubPath = stubFile.getAbsolutePath();
Runtime.getRuntime().exec(new String[] { "chmod", "+x", stubPath });
}
*/
} else if (exportPlatform == PConstants.LINUX) {
if (embedJava) {
Base.copyDirNative(Base.getJavaHome(), new File(destFolder, "java"));
}
} else if (exportPlatform == PConstants.WINDOWS) {
if (embedJava) {
Base.copyDir(Base.getJavaHome(), new File(destFolder, "java"));
}
}
/// make the jar folder (all platforms)
if (!jarFolder.exists()) jarFolder.mkdirs();
/// on windows, copy the exe file
if (exportPlatform == PConstants.WINDOWS) {
if (exportBits == 64) {
// We don't yet have a 64-bit launcher, so this is a workaround for now.
File batFile = new File(destFolder, sketch.getName() + ".bat");
PrintWriter writer = PApplet.createWriter(batFile);
writer.println("@echo off");
writer.println("java -Djava.ext.dirs=lib -Djava.library.path=lib " + sketch.getName());
writer.flush();
writer.close();
} else {
Base.copyFile(mode.getContentFile("application/template.exe"),
new File(destFolder, sketch.getName() + ".exe"));
}
}
/// start copying all jar files
Vector<String> jarListVector = new Vector<String>();
/// create the main .jar file
// HashMap<String,Object> zipFileContents = new HashMap<String,Object>();
FileOutputStream zipOutputFile =
new FileOutputStream(new File(jarFolder, sketch.getName() + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// ZipEntry entry;
// add the manifest file so that the .jar can be double clickable
addManifest(zos);
// add the project's .class files to the jar
// (just grabs everything from the build directory,
// since there may be some inner classes)
// TODO this needs to be recursive (for packages)
// File classFiles[] = tempClassesFolder.listFiles(new FilenameFilter() {
// public boolean accept(File dir, String name) {
// return name.endsWith(".class");
// }
// });
// for (File file : classFiles) {
// entry = new ZipEntry(file.getName());
// zos.putNextEntry(entry);
// zos.write(Base.loadBytesRaw(file));
// zos.closeEntry();
// }
addClasses(zos, binFolder);
// add the data folder to the main jar file
// addDataFolder(zos);
// For 2.0a2, make the data folder a separate directory, rather than
// packaging potentially large files into the JAR. On OS X, we have to hide
// the folder inside the .app package, while Linux and Windows will have a
// 'data' folder next to 'lib'.
if (sketch.hasDataFolder()) {
if (exportPlatform == PConstants.MACOSX) {
Base.copyDir(sketch.getDataFolder(), new File(jarFolder, "data"));
} else {
Base.copyDir(sketch.getDataFolder(), new File(destFolder, "data"));
}
}
// add the contents of the code folder to the jar
if (sketch.hasCodeFolder()) {
String includes = Base.contentsToClassPath(sketch.getCodeFolder());
// Use tokens to get rid of extra blanks, which causes huge exports
String[] codeList = PApplet.splitTokens(includes, File.pathSeparator);
// String cp = "";
for (int i = 0; i < codeList.length; i++) {
if (codeList[i].toLowerCase().endsWith(".jar") ||
codeList[i].toLowerCase().endsWith(".zip")) {
File exportFile = new File(codeList[i]);
String exportFilename = exportFile.getName();
Base.copyFile(exportFile, new File(jarFolder, exportFilename));
jarListVector.add(exportFilename);
} else {
// cp += codeList[i] + File.pathSeparator;
}
}
// packClassPathIntoZipFile(cp, zos, zipFileContents); // this was double adding the code folder prior to 2.0a2
}
zos.flush();
zos.close();
jarListVector.add(sketch.getName() + ".jar");
// /// add core.jar to the jar destination folder
//
// File bagelJar = Base.isMacOS() ?
// Base.getContentFile("core.jar") :
// Base.getContentFile("lib/core.jar");
// Base.copyFile(bagelJar, new File(jarFolder, "core.jar"));
// jarListVector.add("core.jar");
/// add contents of 'library' folders to the export
for (Library library : importedLibraries) {
// add each item from the library folder / export list to the output
for (File exportFile : library.getApplicationExports(exportPlatform, exportBits)) {
// System.out.println("export: " + exportFile);
String exportName = exportFile.getName();
if (!exportFile.exists()) {
System.err.println(exportFile.getName() +
" is mentioned in export.txt, but it's " +
"a big fat lie and does not exist.");
} else if (exportFile.isDirectory()) {
//System.err.println("Ignoring sub-folder \"" + exportList[i] + "\"");
// if (exportPlatform == PConstants.MACOSX) {
// // For OS X, copy subfolders to Contents/Resources/Java
Base.copyDir(exportFile, new File(jarFolder, exportName));
// } else {
// // For other platforms, just copy the folder to the same directory
// // as the application.
// Base.copyDir(exportFile, new File(destFolder, exportName));
// }
} else if (exportName.toLowerCase().endsWith(".zip") ||
exportName.toLowerCase().endsWith(".jar")) {
Base.copyFile(exportFile, new File(jarFolder, exportName));
jarListVector.add(exportName);
// old style, prior to 2.0a2
// } else if ((exportPlatform == PConstants.MACOSX) &&
// (exportFile.getName().toLowerCase().endsWith(".jnilib"))) {
// // jnilib files can be placed in Contents/Resources/Java
// Base.copyFile(exportFile, new File(jarFolder, exportName));
//
// } else {
// // copy the file to the main directory.. prolly a .dll or something
// Base.copyFile(exportFile, new File(destFolder, exportName));
// }
// first 2.0a2 attempt, until below...
// } else if (exportPlatform == PConstants.MACOSX) {
// Base.copyFile(exportFile, new File(jarFolder, exportName));
//
// } else {
// Base.copyFile(exportFile, new File(destFolder, exportName));
} else {
// Starting with 2.0a2 put extra export files (DLLs, plugins folder,
// anything else for libraries) inside lib or Contents/Resources/Java
Base.copyFile(exportFile, new File(jarFolder, exportName));
}
}
}
/// create platform-specific CLASSPATH based on included jars
String jarList[] = new String[jarListVector.size()];
jarListVector.copyInto(jarList);
StringBuffer exportClassPath = new StringBuffer();
if (exportPlatform == PConstants.MACOSX) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$JAVAROOT/" + jarList[i]);
}
} else if (exportPlatform == PConstants.WINDOWS) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(",");
exportClassPath.append(jarList[i]);
}
} else {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$APPDIR/lib/" + jarList[i]);
}
}
/// figure out run options for the VM
// this is too vague. if anyone is using it, we can bring it back
// String runOptions = Preferences.get("run.options");
List<String> runOptions = new ArrayList<String>();
if (Preferences.getBoolean("run.options.memory")) {
runOptions.add("-Xms" + Preferences.get("run.options.memory.initial") + "m");
runOptions.add("-Xmx" + Preferences.get("run.options.memory.maximum") + "m");
}
StringBuilder jvmOptionsList = new StringBuilder();
for (String opt : runOptions) {
jvmOptionsList.append(" <string>");
jvmOptionsList.append(opt);
jvmOptionsList.append("</string>");
jvmOptionsList.append('\n');
}
// if (exportPlatform == PConstants.MACOSX) {
// // If no bits specified (libs are all universal, or no native libs)
// // then exportBits will be 0, and can be controlled via "Get Info".
// // Otherwise, need to specify the bits as a VM option.
// if (exportBits == 32) {
// runOptions += " -d32";
// } else if (exportBits == 64) {
// runOptions += " -d64";
// }
// }
/// macosx: write out Info.plist (template for classpath, etc)
if (exportPlatform == PConstants.MACOSX) {
//String PLIST_TEMPLATE = "template.plist";
String PLIST_TEMPLATE = "Info.plist.tmpl";
File plistTemplate = new File(sketch.getFolder(), PLIST_TEMPLATE);
if (!plistTemplate.exists()) {
//plistTemplate = mode.getContentFile("application/template.plist");
plistTemplate = mode.getContentFile("application/Info.plist.tmpl");
}
File plistFile = new File(dotAppFolder, "Contents/Info.plist");
PrintWriter pw = PApplet.createWriter(plistFile);
String lines[] = PApplet.loadStrings(plistTemplate);
for (int i = 0; i < lines.length; i++) {
if (lines[i].indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(lines[i]);
int index = 0;
while ((index = sb.indexOf("@@jvm_runtime@@")) != -1) {
sb.replace(index, index + "@@jvm_runtime@@".length(),
jvmRuntime);
}
while ((index = sb.indexOf("@@jvm_options_list@@")) != -1) {
sb.replace(index, index + "@@jvm_options_list@@".length(),
jvmOptionsList.toString());
}
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
sketch.getName());
}
// while ((index = sb.indexOf("@@classpath@@")) != -1) {
// sb.replace(index, index + "@@classpath@@".length(),
// exportClassPath.toString());
// }
while ((index = sb.indexOf("@@lsuipresentationmode@@")) != -1) {
sb.replace(index, index + "@@lsuipresentationmode@@".length(),
Preferences.getBoolean("export.application.fullscreen") ? "4" : "0");
}
// while ((index = sb.indexOf("@@lsarchitecturepriority@@")) != -1) {
// // More about this mess: http://support.apple.com/kb/TS2827
// // First default to exportBits == 0 case
// String arch = "<string>x86_64</string>\n <string>i386</string>";
// if (exportBits == 32) {
// arch = "<string>i386</string>";
// } else if (exportBits == 64) {
// arch = "<string>x86_64</string>";
// }
// sb.replace(index, index + "@@lsarchitecturepriority@@".length(), arch);
// }
lines[i] = sb.toString();
}
// explicit newlines to avoid Windows CRLF
pw.print(lines[i] + "\n");
}
pw.flush();
pw.close();
} else if (exportPlatform == PConstants.WINDOWS) {
File argsFile = new File(destFolder + "/lib/args.txt");
PrintWriter pw = PApplet.createWriter(argsFile);
// Since this is only on Windows, make sure we use Windows CRLF
pw.print(runOptions + "\r\n");
pw.print(sketch.getName() + "\r\n");
pw.print(exportClassPath);
pw.flush();
pw.close();
} else {
File shellScript = new File(destFolder, sketch.getName());
PrintWriter pw = PApplet.createWriter(shellScript);
// Do the newlines explicitly so that Windows CRLF
// isn't used when exporting for Unix.
pw.print("#!/bin/sh\n\n");
//ps.print("APPDIR=`dirname $0`\n");
pw.print("APPDIR=$(dirname \"$0\")\n"); // more posix compliant
// another fix for bug #234, LD_LIBRARY_PATH ignored on some platforms
//ps.print("LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$APPDIR\n");
pw.print("java " + Preferences.get("run.options") +
" -Djava.library.path=\"$APPDIR:$APPDIR/lib\"" +
" -cp \"" + exportClassPath + "\"" +
" " + sketch.getName() + " \"$@\"\n");
pw.flush();
pw.close();
String shellPath = shellScript.getAbsolutePath();
// will work on osx or *nix, but just dies on windows, oh well..
if (!Base.isWindows()) {
Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
}
}
/// copy the source files to the target
/// (we like to encourage people to share their code)
File sourceFolder = new File(destFolder, "source");
sourceFolder.mkdirs();
for (SketchCode code : sketch.getCode()) {
try {
code.copyTo(new File(sourceFolder, code.getFileName()));
} catch (IOException e) {
e.printStackTrace();
}
}
// move the .java file from the preproc there too
String preprocFilename = sketch.getName() + ".java";
File preprocFile = new File(srcFolder, preprocFilename);
if (preprocFile.exists()) {
Base.copyFile(preprocFile, new File(sourceFolder, preprocFilename));
} else {
System.err.println("Could not copy source file: " + preprocFile.getAbsolutePath());
}
/// remove the .class files from the export folder.
// for (File file : classFiles) {
// if (!file.delete()) {
// Base.showWarning("Could not delete",
// file.getName() + " could not \n" +
// "be deleted from the applet folder. \n" +
// "You'll need to remove it by hand.", null);
// }
// }
// these will now be removed automatically via the temp folder deleteOnExit()
/// goodbye
return true;
}
| protected boolean exportApplication(File destFolder,
int exportPlatform,
int exportBits,
boolean embedJava) throws IOException, SketchException {
// TODO this should probably be a dialog box instead of a warning
// on the terminal. And the message should be written better than this.
// http://code.google.com/p/processing/issues/detail?id=884
for (Library library : importedLibraries) {
if (!library.supportsArch(exportPlatform, exportBits)) {
String pn = PConstants.platformNames[exportPlatform];
Base.showWarning("Quibbles 'n Bits",
"The application." + pn + exportBits +
" folder will not be created\n" +
"because no " + exportBits + "-bit version of " +
library.getName() + " is available for " + pn, null);
return true; // don't cancel all exports for this, just move along
}
}
/// prep the output directory
mode.prepareExportFolder(destFolder);
/// figure out where the jar files will be placed
File jarFolder = new File(destFolder, "lib");
/// where all the skeleton info lives
/// on macosx, need to copy .app skeleton since that's
/// also where the jar files will be placed
File dotAppFolder = null;
// String jdkFolderName = null;
String jvmRuntime = "";
if (exportPlatform == PConstants.MACOSX) {
dotAppFolder = new File(destFolder, sketch.getName() + ".app");
File contentsOrig = new File(Base.getJavaHome(), "../../../../..");
if (embedJava) {
File jdkFolder = new File(Base.getJavaHome(), "../../..");
String jdkFolderName = jdkFolder.getCanonicalFile().getName();
jvmRuntime = "<key>JVMRuntime</key>\n <string>" + jdkFolderName + "</string>";
}
// File dotAppSkeleton = mode.getContentFile("application/template.app");
// Base.copyDir(dotAppSkeleton, dotAppFolder);
File contentsFolder = new File(dotAppFolder, "Contents");
contentsFolder.mkdirs();
// Info.plist will be written later
// set the jar folder to a different location than windows/linux
//jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
jarFolder = new File(contentsFolder, "Java");
File macosFolder = new File(contentsFolder, "MacOS");
macosFolder.mkdirs();
Base.copyFile(new File(contentsOrig, "MacOS/Processing"),
new File(contentsFolder, "MacOS/" + sketch.getName()));
File pkgInfo = new File(contentsFolder, "PkgInfo");
PrintWriter writer = PApplet.createWriter(pkgInfo);
writer.println("APPL????");
writer.flush();
writer.close();
// Use faster(?) native copy here (also to do sym links)
if (embedJava) {
Base.copyDirNative(new File(contentsOrig, "PlugIns"),
new File(contentsFolder, "PlugIns"));
}
File resourcesFolder = new File(contentsFolder, "Resources");
Base.copyDir(new File(contentsOrig, "Resources/en.lproj"),
new File(resourcesFolder, "en.lproj"));
Base.copyFile(mode.getContentFile("application/sketch.icns"),
new File(resourcesFolder, "sketch.icns"));
/*
String stubName = "Contents/MacOS/JavaApplicationStub";
// need to set the stub to executable
// will work on osx or *nix, but just dies on windows, oh well..
if (Base.isWindows()) {
File warningFile = new File(destFolder, "readme.txt");
PrintWriter pw = PApplet.createWriter(warningFile);
pw.println("This application was created on Windows, which does not");
pw.println("properly support setting files as \"executable\",");
pw.println("a necessity for applications on Mac OS X.");
pw.println();
pw.println("To fix this, use the Terminal on Mac OS X, and from this");
pw.println("directory, type the following:");
pw.println();
pw.println("chmod +x " + dotAppFolder.getName() + "/" + stubName);
pw.flush();
pw.close();
} else {
File stubFile = new File(dotAppFolder, stubName);
String stubPath = stubFile.getAbsolutePath();
Runtime.getRuntime().exec(new String[] { "chmod", "+x", stubPath });
}
*/
} else if (exportPlatform == PConstants.LINUX) {
if (embedJava) {
Base.copyDirNative(Base.getJavaHome(), new File(destFolder, "java"));
}
} else if (exportPlatform == PConstants.WINDOWS) {
if (embedJava) {
Base.copyDir(Base.getJavaHome(), new File(destFolder, "java"));
}
}
/// make the jar folder (all platforms)
if (!jarFolder.exists()) jarFolder.mkdirs();
/// on windows, copy the exe file
if (exportPlatform == PConstants.WINDOWS) {
if (exportBits == 64) {
// We don't yet have a 64-bit launcher, so this is a workaround for now.
File batFile = new File(destFolder, sketch.getName() + ".bat");
PrintWriter writer = PApplet.createWriter(batFile);
writer.println("@echo off");
writer.println("java -Djava.ext.dirs=lib -Djava.library.path=lib " + sketch.getName());
writer.flush();
writer.close();
} else {
Base.copyFile(mode.getContentFile("application/template.exe"),
new File(destFolder, sketch.getName() + ".exe"));
}
}
/// start copying all jar files
Vector<String> jarListVector = new Vector<String>();
/// create the main .jar file
// HashMap<String,Object> zipFileContents = new HashMap<String,Object>();
FileOutputStream zipOutputFile =
new FileOutputStream(new File(jarFolder, sketch.getName() + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// ZipEntry entry;
// add the manifest file so that the .jar can be double clickable
addManifest(zos);
// add the project's .class files to the jar
// (just grabs everything from the build directory,
// since there may be some inner classes)
// TODO this needs to be recursive (for packages)
// File classFiles[] = tempClassesFolder.listFiles(new FilenameFilter() {
// public boolean accept(File dir, String name) {
// return name.endsWith(".class");
// }
// });
// for (File file : classFiles) {
// entry = new ZipEntry(file.getName());
// zos.putNextEntry(entry);
// zos.write(Base.loadBytesRaw(file));
// zos.closeEntry();
// }
addClasses(zos, binFolder);
// add the data folder to the main jar file
// addDataFolder(zos);
// For 2.0a2, make the data folder a separate directory, rather than
// packaging potentially large files into the JAR. On OS X, we have to hide
// the folder inside the .app package, while Linux and Windows will have a
// 'data' folder next to 'lib'.
if (sketch.hasDataFolder()) {
if (exportPlatform == PConstants.MACOSX) {
Base.copyDir(sketch.getDataFolder(), new File(jarFolder, "data"));
} else {
Base.copyDir(sketch.getDataFolder(), new File(destFolder, "data"));
}
}
// add the contents of the code folder to the jar
if (sketch.hasCodeFolder()) {
String includes = Base.contentsToClassPath(sketch.getCodeFolder());
// Use tokens to get rid of extra blanks, which causes huge exports
String[] codeList = PApplet.splitTokens(includes, File.pathSeparator);
// String cp = "";
for (int i = 0; i < codeList.length; i++) {
if (codeList[i].toLowerCase().endsWith(".jar") ||
codeList[i].toLowerCase().endsWith(".zip")) {
File exportFile = new File(codeList[i]);
String exportFilename = exportFile.getName();
Base.copyFile(exportFile, new File(jarFolder, exportFilename));
jarListVector.add(exportFilename);
} else {
// cp += codeList[i] + File.pathSeparator;
}
}
// packClassPathIntoZipFile(cp, zos, zipFileContents); // this was double adding the code folder prior to 2.0a2
}
zos.flush();
zos.close();
jarListVector.add(sketch.getName() + ".jar");
// /// add core.jar to the jar destination folder
//
// File bagelJar = Base.isMacOS() ?
// Base.getContentFile("core.jar") :
// Base.getContentFile("lib/core.jar");
// Base.copyFile(bagelJar, new File(jarFolder, "core.jar"));
// jarListVector.add("core.jar");
/// add contents of 'library' folders to the export
for (Library library : importedLibraries) {
// add each item from the library folder / export list to the output
for (File exportFile : library.getApplicationExports(exportPlatform, exportBits)) {
// System.out.println("export: " + exportFile);
String exportName = exportFile.getName();
if (!exportFile.exists()) {
System.err.println(exportFile.getName() +
" is mentioned in export.txt, but it's " +
"a big fat lie and does not exist.");
} else if (exportFile.isDirectory()) {
//System.err.println("Ignoring sub-folder \"" + exportList[i] + "\"");
// if (exportPlatform == PConstants.MACOSX) {
// // For OS X, copy subfolders to Contents/Resources/Java
Base.copyDir(exportFile, new File(jarFolder, exportName));
// } else {
// // For other platforms, just copy the folder to the same directory
// // as the application.
// Base.copyDir(exportFile, new File(destFolder, exportName));
// }
} else if (exportName.toLowerCase().endsWith(".zip") ||
exportName.toLowerCase().endsWith(".jar")) {
Base.copyFile(exportFile, new File(jarFolder, exportName));
jarListVector.add(exportName);
// old style, prior to 2.0a2
// } else if ((exportPlatform == PConstants.MACOSX) &&
// (exportFile.getName().toLowerCase().endsWith(".jnilib"))) {
// // jnilib files can be placed in Contents/Resources/Java
// Base.copyFile(exportFile, new File(jarFolder, exportName));
//
// } else {
// // copy the file to the main directory.. prolly a .dll or something
// Base.copyFile(exportFile, new File(destFolder, exportName));
// }
// first 2.0a2 attempt, until below...
// } else if (exportPlatform == PConstants.MACOSX) {
// Base.copyFile(exportFile, new File(jarFolder, exportName));
//
// } else {
// Base.copyFile(exportFile, new File(destFolder, exportName));
} else {
// Starting with 2.0a2 put extra export files (DLLs, plugins folder,
// anything else for libraries) inside lib or Contents/Resources/Java
Base.copyFile(exportFile, new File(jarFolder, exportName));
}
}
}
/// create platform-specific CLASSPATH based on included jars
String jarList[] = new String[jarListVector.size()];
jarListVector.copyInto(jarList);
StringBuffer exportClassPath = new StringBuffer();
if (exportPlatform == PConstants.MACOSX) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$JAVAROOT/" + jarList[i]);
}
} else if (exportPlatform == PConstants.WINDOWS) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(",");
exportClassPath.append(jarList[i]);
}
} else {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$APPDIR/lib/" + jarList[i]);
}
}
/// figure out run options for the VM
// this is too vague. if anyone is using it, we can bring it back
// String runOptions = Preferences.get("run.options");
List<String> runOptions = new ArrayList<String>();
if (Preferences.getBoolean("run.options.memory")) {
runOptions.add("-Xms" + Preferences.get("run.options.memory.initial") + "m");
runOptions.add("-Xmx" + Preferences.get("run.options.memory.maximum") + "m");
}
StringBuilder jvmOptionsList = new StringBuilder();
for (String opt : runOptions) {
jvmOptionsList.append(" <string>");
jvmOptionsList.append(opt);
jvmOptionsList.append("</string>");
jvmOptionsList.append('\n');
}
// if (exportPlatform == PConstants.MACOSX) {
// // If no bits specified (libs are all universal, or no native libs)
// // then exportBits will be 0, and can be controlled via "Get Info".
// // Otherwise, need to specify the bits as a VM option.
// if (exportBits == 32) {
// runOptions += " -d32";
// } else if (exportBits == 64) {
// runOptions += " -d64";
// }
// }
/// macosx: write out Info.plist (template for classpath, etc)
if (exportPlatform == PConstants.MACOSX) {
//String PLIST_TEMPLATE = "template.plist";
String PLIST_TEMPLATE = "Info.plist.tmpl";
File plistTemplate = new File(sketch.getFolder(), PLIST_TEMPLATE);
if (!plistTemplate.exists()) {
//plistTemplate = mode.getContentFile("application/template.plist");
plistTemplate = mode.getContentFile("application/Info.plist.tmpl");
}
File plistFile = new File(dotAppFolder, "Contents/Info.plist");
PrintWriter pw = PApplet.createWriter(plistFile);
String lines[] = PApplet.loadStrings(plistTemplate);
for (int i = 0; i < lines.length; i++) {
if (lines[i].indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(lines[i]);
int index = 0;
while ((index = sb.indexOf("@@jvm_runtime@@")) != -1) {
sb.replace(index, index + "@@jvm_runtime@@".length(),
jvmRuntime);
}
while ((index = sb.indexOf("@@jvm_options_list@@")) != -1) {
sb.replace(index, index + "@@jvm_options_list@@".length(),
jvmOptionsList.toString());
}
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
sketch.getName());
}
// while ((index = sb.indexOf("@@classpath@@")) != -1) {
// sb.replace(index, index + "@@classpath@@".length(),
// exportClassPath.toString());
// }
while ((index = sb.indexOf("@@lsuipresentationmode@@")) != -1) {
sb.replace(index, index + "@@lsuipresentationmode@@".length(),
Preferences.getBoolean("export.application.fullscreen") ? "4" : "0");
}
// while ((index = sb.indexOf("@@lsarchitecturepriority@@")) != -1) {
// // More about this mess: http://support.apple.com/kb/TS2827
// // First default to exportBits == 0 case
// String arch = "<string>x86_64</string>\n <string>i386</string>";
// if (exportBits == 32) {
// arch = "<string>i386</string>";
// } else if (exportBits == 64) {
// arch = "<string>x86_64</string>";
// }
// sb.replace(index, index + "@@lsarchitecturepriority@@".length(), arch);
// }
lines[i] = sb.toString();
}
// explicit newlines to avoid Windows CRLF
pw.print(lines[i] + "\n");
}
pw.flush();
pw.close();
} else if (exportPlatform == PConstants.WINDOWS) {
File argsFile = new File(destFolder + "/lib/args.txt");
PrintWriter pw = PApplet.createWriter(argsFile);
// Since this is only on Windows, make sure we use Windows CRLF
pw.print(PApplet.join(runOptions.toArray(new String[0]), " ") + "\r\n");
pw.print(sketch.getName() + "\r\n");
pw.print(exportClassPath);
pw.flush();
pw.close();
} else {
File shellScript = new File(destFolder, sketch.getName());
PrintWriter pw = PApplet.createWriter(shellScript);
// Do the newlines explicitly so that Windows CRLF
// isn't used when exporting for Unix.
pw.print("#!/bin/sh\n\n");
//ps.print("APPDIR=`dirname $0`\n");
pw.print("APPDIR=$(dirname \"$0\")\n"); // more posix compliant
// another fix for bug #234, LD_LIBRARY_PATH ignored on some platforms
//ps.print("LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$APPDIR\n");
pw.print("java " + Preferences.get("run.options") +
" -Djava.library.path=\"$APPDIR:$APPDIR/lib\"" +
" -cp \"" + exportClassPath + "\"" +
" " + sketch.getName() + " \"$@\"\n");
pw.flush();
pw.close();
String shellPath = shellScript.getAbsolutePath();
// will work on osx or *nix, but just dies on windows, oh well..
if (!Base.isWindows()) {
Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
}
}
/// copy the source files to the target
/// (we like to encourage people to share their code)
File sourceFolder = new File(destFolder, "source");
sourceFolder.mkdirs();
for (SketchCode code : sketch.getCode()) {
try {
code.copyTo(new File(sourceFolder, code.getFileName()));
} catch (IOException e) {
e.printStackTrace();
}
}
// move the .java file from the preproc there too
String preprocFilename = sketch.getName() + ".java";
File preprocFile = new File(srcFolder, preprocFilename);
if (preprocFile.exists()) {
Base.copyFile(preprocFile, new File(sourceFolder, preprocFilename));
} else {
System.err.println("Could not copy source file: " + preprocFile.getAbsolutePath());
}
/// remove the .class files from the export folder.
// for (File file : classFiles) {
// if (!file.delete()) {
// Base.showWarning("Could not delete",
// file.getName() + " could not \n" +
// "be deleted from the applet folder. \n" +
// "You'll need to remove it by hand.", null);
// }
// }
// these will now be removed automatically via the temp folder deleteOnExit()
/// goodbye
return true;
}
|
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java
index be4e6d6c..f6c83dcf 100644
--- a/src/org/mozilla/javascript/Interpreter.java
+++ b/src/org/mozilla/javascript/Interpreter.java
@@ -1,2808 +1,2808 @@
/* -*- 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-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
*
* 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;
import java.io.*;
import org.mozilla.javascript.debug.*;
public class Interpreter {
// Additional interpreter-specific codes
private static final int
// To indicating a line number change in icodes.
LINE_ICODE = TokenStream.LAST_TOKEN + 1,
SOURCEFILE_ICODE = TokenStream.LAST_TOKEN + 2,
// To store shorts and ints inline
SHORTNUMBER_ICODE = TokenStream.LAST_TOKEN + 3,
INTNUMBER_ICODE = TokenStream.LAST_TOKEN + 4,
// To return undefined value
RETURN_UNDEF_ICODE = TokenStream.LAST_TOKEN + 5,
// Last icode
END_ICODE = TokenStream.LAST_TOKEN + 6;
public IRFactory createIRFactory(TokenStream ts,
ClassNameHelper nameHelper, Scriptable scope)
{
return new IRFactory(ts, scope);
}
public Node transform(Node tree, TokenStream ts, Scriptable scope) {
return (new NodeTransformer()).transform(tree, null, ts, scope);
}
public Object compile(Context cx, Scriptable scope, Node tree,
Object securityDomain,
SecuritySupport securitySupport,
ClassNameHelper nameHelper)
throws IOException
{
version = cx.getLanguageVersion();
itsData = new InterpreterData(cx, securityDomain);
if (tree instanceof FunctionNode) {
FunctionNode f = (FunctionNode) tree;
itsData.itsFunctionType = f.getFunctionType();
InterpretedFunction result = generateFunctionICode(cx, scope, f);
createFunctionObject(result, scope, false);
return result;
}
return generateScriptICode(cx, scope, tree);
}
private InterpretedScript generateScriptICode(Context cx,
Scriptable scope,
Node tree)
{
itsSourceFile = (String) tree.getProp(Node.SOURCENAME_PROP);
itsData.itsSourceFile = itsSourceFile;
debugSource = (String) tree.getProp(Node.DEBUGSOURCE_PROP);
generateNestedFunctions(cx, scope, tree);
generateRegExpLiterals(cx, scope, tree);
itsVariableTable = (VariableTable)tree.getProp(Node.VARS_PROP);
generateICodeFromTree(tree);
if (Context.printICode) dumpICode(itsData);
InterpretedScript result = new InterpretedScript(cx, itsData);
setArgNames(result);
if (cx.debugger != null) {
cx.debugger.handleCompilationDone(cx, result, debugSource);
}
return result;
}
private InterpretedFunction generateFunctionICode(Context cx,
Scriptable scope,
FunctionNode theFunction)
{
// check if function has own source, which is the case
// with Function(...)
String savedSource = debugSource;
debugSource = (String)theFunction.getProp(Node.DEBUGSOURCE_PROP);
if (debugSource == null) {
debugSource = savedSource;
}
generateNestedFunctions(cx, scope, theFunction);
generateRegExpLiterals(cx, scope, theFunction);
itsData.itsNeedsActivation = theFunction.requiresActivation();
itsVariableTable = theFunction.getVariableTable();
generateICodeFromTree(theFunction.getLastChild());
itsData.itsName = theFunction.getFunctionName();
itsData.itsSourceFile = (String) theFunction.getProp(
Node.SOURCENAME_PROP);
itsData.itsSource = (String)theFunction.getProp(Node.SOURCE_PROP);
if (Context.printICode) dumpICode(itsData);
InterpretedFunction result = new InterpretedFunction(cx, itsData);
setArgNames(result);
if (cx.debugger != null) {
cx.debugger.handleCompilationDone(cx, result, debugSource);
}
debugSource = savedSource;
return result;
}
private void setArgNames(NativeFunction f) {
String[] argNames = new String[itsVariableTable.size()];
itsVariableTable.getAllVariables(argNames);
f.argNames = argNames;
f.argCount = (short)itsVariableTable.getParameterCount();
}
private void generateNestedFunctions(Context cx, Scriptable scope,
Node tree)
{
ObjArray functionList = (ObjArray) tree.getProp(Node.FUNCTION_PROP);
if (functionList == null) return;
int N = functionList.size();
InterpretedFunction[] array = new InterpretedFunction[N];
for (int i = 0; i != N; i++) {
FunctionNode def = (FunctionNode)functionList.get(i);
Interpreter jsi = new Interpreter();
jsi.itsSourceFile = itsSourceFile;
jsi.itsData = new InterpreterData(cx, itsData.securityDomain);
jsi.itsData.itsCheckThis = def.getCheckThis();
jsi.itsData.itsFunctionType = def.getFunctionType();
jsi.itsInFunctionFlag = true;
jsi.debugSource = debugSource;
array[i] = jsi.generateFunctionICode(cx, scope, def);
def.putIntProp(Node.FUNCTION_PROP, i);
}
itsData.itsNestedFunctions = array;
}
private void generateRegExpLiterals(Context cx,
Scriptable scope,
Node tree)
{
ObjArray regexps = (ObjArray)tree.getProp(Node.REGEXP_PROP);
if (regexps == null) return;
RegExpProxy rep = cx.getRegExpProxy();
if (rep == null) {
throw cx.reportRuntimeError0("msg.no.regexp");
}
int N = regexps.size();
Object[] array = new Object[N];
for (int i = 0; i != N; i++) {
Node regexp = (Node) regexps.get(i);
Node left = regexp.getFirstChild();
Node right = regexp.getLastChild();
String source = left.getString();
String global = (left != right) ? right.getString() : null;
array[i] = rep.newRegExp(cx, scope, source, global, false);
regexp.putIntProp(Node.REGEXP_PROP, i);
}
itsData.itsRegExpLiterals = array;
}
private void generateICodeFromTree(Node tree) {
int theICodeTop = 0;
theICodeTop = generateICode(tree, theICodeTop);
itsLabels.fixLabelGotos(itsData.itsICode);
// add END_ICODE only to scripts as function always ends with RETURN
if (itsData.itsFunctionType == 0) {
theICodeTop = addByte(END_ICODE, theICodeTop);
}
itsData.itsICodeTop = theICodeTop;
if (itsData.itsICode.length != theICodeTop) {
// Make itsData.itsICode length exactly theICodeTop to save memory
// and catch bugs with jumps beyound icode as early as possible
byte[] tmp = new byte[theICodeTop];
System.arraycopy(itsData.itsICode, 0, tmp, 0, theICodeTop);
itsData.itsICode = tmp;
}
if (itsStrings.size() == 0) {
itsData.itsStringTable = null;
}else {
itsData.itsStringTable = new String[itsStrings.size()];
ObjToIntMap.Iterator iter = itsStrings.newIterator();
for (iter.start(); !iter.done(); iter.next()) {
String str = (String)iter.getKey();
int index = iter.getValue();
if (itsData.itsStringTable[index] != null) Context.codeBug();
itsData.itsStringTable[index] = str;
}
}
if (itsDoubleTableTop == 0) {
itsData.itsDoubleTable = null;
}else if (itsData.itsDoubleTable.length != itsDoubleTableTop) {
double[] tmp = new double[itsDoubleTableTop];
System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0,
itsDoubleTableTop);
itsData.itsDoubleTable = tmp;
}
itsData.itsMaxVars = itsVariableTable.size();
// itsMaxFrameArray: interpret method needs this amount for its
// stack and sDbl arrays
itsData.itsMaxFrameArray = itsData.itsMaxVars
+ itsData.itsMaxLocals
+ itsData.itsMaxTryDepth
+ itsData.itsMaxStack;
}
private int updateLineNumber(Node node, int iCodeTop) {
Object datum = node.getDatum();
if (datum == null || !(datum instanceof Number))
return iCodeTop;
int lineno = ((Number) datum).intValue();
if (lineno != itsLineNumber && lineno >= 0) {
itsLineNumber = lineno;
iCodeTop = addByte(LINE_ICODE, iCodeTop);
iCodeTop = addShort(lineno, iCodeTop);
}
return iCodeTop;
}
private void badTree(Node node) {
try {
out = new PrintWriter(new FileOutputStream("icode.txt", true));
out.println("Un-handled node : " + node.toString());
out.close();
}
catch (IOException x) {}
throw new RuntimeException("Un-handled node : "
+ node.toString());
}
private int generateICode(Node node, int iCodeTop) {
int type = node.getType();
Node child = node.getFirstChild();
Node firstChild = child;
switch (type) {
case TokenStream.FUNCTION : {
Node fn = (Node) node.getProp(Node.FUNCTION_PROP);
int index = fn.getExistingIntProp(Node.FUNCTION_PROP);
iCodeTop = addByte(TokenStream.CLOSURE, iCodeTop);
iCodeTop = addShort(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.SCRIPT :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
if (child.getType() != TokenStream.FUNCTION)
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
}
break;
case TokenStream.CASE :
iCodeTop = updateLineNumber(node, iCodeTop);
child = child.getNextSibling();
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
}
break;
case TokenStream.LABEL :
case TokenStream.WITH :
case TokenStream.LOOP :
case TokenStream.DEFAULT :
case TokenStream.BLOCK :
case TokenStream.VOID :
case TokenStream.NOP :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
}
break;
case TokenStream.COMMA :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
break;
case TokenStream.SWITCH : {
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
int theLocalSlot = itsData.itsMaxLocals++;
iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
ObjArray cases = (ObjArray) node.getProp(Node.CASES_PROP);
for (int i = 0; i < cases.size(); i++) {
Node thisCase = (Node)cases.get(i);
Node first = thisCase.getFirstChild();
// the case expression is the firstmost child
// the rest will be generated when the case
// statements are encountered as siblings of
// the switch statement.
iCodeTop = generateICode(first, iCodeTop);
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addByte(TokenStream.SHEQ, iCodeTop);
itsStackDepth--;
Node target = new Node(TokenStream.TARGET);
thisCase.addChildAfter(target, first);
iCodeTop = addGoto(target, TokenStream.IFEQ, iCodeTop);
}
Node defaultNode = (Node) node.getProp(Node.DEFAULT_PROP);
if (defaultNode != null) {
Node defaultTarget = new Node(TokenStream.TARGET);
defaultNode.getFirstChild().
addChildToFront(defaultTarget);
iCodeTop = addGoto(defaultTarget, TokenStream.GOTO,
iCodeTop);
}
Node breakTarget = (Node) node.getProp(Node.BREAK_PROP);
iCodeTop = addGoto(breakTarget, TokenStream.GOTO,
iCodeTop);
}
break;
case TokenStream.TARGET : {
markTargetLabel(node, iCodeTop);
// if this target has a FINALLY_PROP, it is a JSR target
// and so has a PC value on the top of the stack
if (node.getProp(Node.FINALLY_PROP) != null) {
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
}
break;
case TokenStream.EQOP :
case TokenStream.RELOP : {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
int op = node.getInt();
if (version == Context.VERSION_1_2) {
if (op == TokenStream.EQ)
op = TokenStream.SHEQ;
else if (op == TokenStream.NE)
op = TokenStream.SHNE;
}
iCodeTop = addByte(op, iCodeTop);
itsStackDepth--;
}
break;
case TokenStream.NEW :
case TokenStream.CALL : {
if (itsSourceFile != null
&& (itsData.itsSourceFile == null
|| !itsSourceFile.equals(itsData.itsSourceFile)))
{
itsData.itsSourceFile = itsSourceFile;
}
iCodeTop = addByte(SOURCEFILE_ICODE, iCodeTop);
int childCount = 0;
int nameIndex = -1;
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
if (nameIndex == -1) {
int childType = child.getType();
if (childType == TokenStream.NAME
|| childType == TokenStream.GETPROP)
{
nameIndex = itsStrings.size() - 1;
}
}
child = child.getNextSibling();
childCount++;
}
if (node.getProp(Node.SPECIALCALL_PROP) != null) {
// embed line number and source filename
iCodeTop = addByte(TokenStream.CALLSPECIAL, iCodeTop);
iCodeTop = addShort(itsLineNumber, iCodeTop);
iCodeTop = addString(itsSourceFile, iCodeTop);
} else {
iCodeTop = addByte(type, iCodeTop);
iCodeTop = addShort(nameIndex, iCodeTop);
}
itsStackDepth -= (childCount - 1); // always a result value
// subtract from child count to account for [thisObj &] fun
if (type == TokenStream.NEW)
childCount -= 1;
else
childCount -= 2;
iCodeTop = addShort(childCount, iCodeTop);
if (childCount > itsData.itsMaxCalleeArgs)
itsData.itsMaxCalleeArgs = childCount;
iCodeTop = addByte(SOURCEFILE_ICODE, iCodeTop);
}
break;
case TokenStream.NEWLOCAL :
case TokenStream.NEWTEMP : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
}
break;
case TokenStream.USELOCAL : {
if (node.getProp(Node.TARGET_PROP) != null)
iCodeTop = addByte(TokenStream.RETSUB, iCodeTop);
else {
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
Node temp = (Node) node.getProp(Node.LOCAL_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
}
break;
case TokenStream.USETEMP : {
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
Node temp = (Node) node.getProp(Node.TEMP_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.IFEQ :
case TokenStream.IFNE :
iCodeTop = generateICode(child, iCodeTop);
itsStackDepth--; // after the conditional GOTO, really
// fall thru...
case TokenStream.GOTO : {
Node target = (Node)(node.getProp(Node.TARGET_PROP));
iCodeTop = addGoto(target, (byte) type, iCodeTop);
}
break;
case TokenStream.JSR : {
/*
mark the target with a FINALLY_PROP to indicate
that it will have an incoming PC value on the top
of the stack.
!!!
This only works if the target follows the JSR
in the tree.
!!!
*/
Node target = (Node)(node.getProp(Node.TARGET_PROP));
target.putProp(Node.FINALLY_PROP, node);
// Bug 115717 is due to adding a GOSUB here before
// we insert an ENDTRY. I'm not sure of the best way
// to fix this; perhaps we need to maintain a stack
// of pending trys and have some knowledge of how
// many trys we need to close when we perform a
// GOTO or GOSUB.
iCodeTop = addGoto(target, TokenStream.GOSUB, iCodeTop);
}
break;
case TokenStream.AND : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int falseJumpStart = iCodeTop;
iCodeTop = addForwardGoto(TokenStream.IFNE, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
resolveForwardGoto(falseJumpStart, iCodeTop);
}
break;
case TokenStream.OR : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int trueJumpStart = iCodeTop;
iCodeTop = addForwardGoto(TokenStream.IFEQ, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
itsStackDepth--;
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
resolveForwardGoto(trueJumpStart, iCodeTop);
}
break;
case TokenStream.GETPROP : {
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__"))
iCodeTop = addByte(TokenStream.GETPROTO, iCodeTop);
else
if (s.equals("__parent__"))
iCodeTop = addByte(TokenStream.GETSCOPEPARENT, iCodeTop);
else
badTree(node);
}
else {
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.GETPROP, iCodeTop);
itsStackDepth--;
}
}
break;
case TokenStream.DELPROP :
case TokenStream.BITAND :
case TokenStream.BITOR :
case TokenStream.BITXOR :
case TokenStream.LSH :
case TokenStream.RSH :
case TokenStream.URSH :
case TokenStream.ADD :
case TokenStream.SUB :
case TokenStream.MOD :
case TokenStream.DIV :
case TokenStream.MUL :
case TokenStream.GETELEM :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
itsStackDepth--;
break;
case TokenStream.CONVERT : {
iCodeTop = generateICode(child, iCodeTop);
Object toType = node.getProp(Node.TYPE_PROP);
if (toType == ScriptRuntime.NumberClass)
iCodeTop = addByte(TokenStream.POS, iCodeTop);
else
badTree(node);
}
break;
case TokenStream.UNARYOP :
iCodeTop = generateICode(child, iCodeTop);
switch (node.getInt()) {
case TokenStream.VOID :
iCodeTop = addByte(TokenStream.POP, iCodeTop);
iCodeTop = addByte(TokenStream.UNDEFINED, iCodeTop);
break;
case TokenStream.NOT : {
int trueJumpStart = iCodeTop;
iCodeTop = addForwardGoto(TokenStream.IFEQ,
iCodeTop);
iCodeTop = addByte(TokenStream.TRUE, iCodeTop);
int beyondJumpStart = iCodeTop;
iCodeTop = addForwardGoto(TokenStream.GOTO,
iCodeTop);
resolveForwardGoto(trueJumpStart, iCodeTop);
iCodeTop = addByte(TokenStream.FALSE, iCodeTop);
resolveForwardGoto(beyondJumpStart, iCodeTop);
}
break;
case TokenStream.BITNOT :
iCodeTop = addByte(TokenStream.BITNOT, iCodeTop);
break;
case TokenStream.TYPEOF :
iCodeTop = addByte(TokenStream.TYPEOF, iCodeTop);
break;
case TokenStream.SUB :
iCodeTop = addByte(TokenStream.NEG, iCodeTop);
break;
case TokenStream.ADD :
iCodeTop = addByte(TokenStream.POS, iCodeTop);
break;
default:
badTree(node);
break;
}
break;
case TokenStream.SETPROP : {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__"))
iCodeTop = addByte(TokenStream.SETPROTO, iCodeTop);
else
if (s.equals("__parent__"))
iCodeTop = addByte(TokenStream.SETPARENT, iCodeTop);
else
badTree(node);
}
else {
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.SETPROP, iCodeTop);
itsStackDepth -= 2;
}
}
break;
case TokenStream.SETELEM :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
itsStackDepth -= 2;
break;
case TokenStream.SETNAME :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.SETNAME, iCodeTop);
iCodeTop = addString(firstChild.getString(), iCodeTop);
itsStackDepth--;
break;
case TokenStream.TYPEOF : {
String name = node.getString();
int index = -1;
// use typeofname if an activation frame exists
// since the vars all exist there instead of in jregs
if (itsInFunctionFlag && !itsData.itsNeedsActivation)
index = itsVariableTable.getOrdinal(name);
if (index == -1) {
iCodeTop = addByte(TokenStream.TYPEOFNAME, iCodeTop);
iCodeTop = addString(name, iCodeTop);
}
else {
iCodeTop = addByte(TokenStream.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
iCodeTop = addByte(TokenStream.TYPEOF, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.PARENT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.GETPARENT, iCodeTop);
break;
case TokenStream.GETBASE :
case TokenStream.BINDNAME :
case TokenStream.NAME :
case TokenStream.STRING :
iCodeTop = addByte(type, iCodeTop);
iCodeTop = addString(node.getString(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case TokenStream.INC :
case TokenStream.DEC : {
int childType = child.getType();
switch (childType) {
case TokenStream.GETVAR : {
String name = child.getString();
if (itsData.itsNeedsActivation) {
iCodeTop = addByte(TokenStream.SCOPE, iCodeTop);
iCodeTop = addByte(TokenStream.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.PROPINC
: TokenStream.PROPDEC,
iCodeTop);
itsStackDepth--;
}
else {
int i = itsVariableTable.getOrdinal(name);
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.VARINC
: TokenStream.VARDEC,
iCodeTop);
iCodeTop = addByte(i, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
}
break;
case TokenStream.GETPROP :
case TokenStream.GETELEM : {
Node getPropChild = child.getFirstChild();
iCodeTop = generateICode(getPropChild,
iCodeTop);
getPropChild = getPropChild.getNextSibling();
iCodeTop = generateICode(getPropChild,
iCodeTop);
if (childType == TokenStream.GETPROP)
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.PROPINC
: TokenStream.PROPDEC,
iCodeTop);
else
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.ELEMINC
: TokenStream.ELEMDEC,
iCodeTop);
itsStackDepth--;
}
break;
default : {
iCodeTop = addByte(type == TokenStream.INC
? TokenStream.NAMEINC
: TokenStream.NAMEDEC,
iCodeTop);
iCodeTop = addString(child.getString(),
iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
}
break;
case TokenStream.NUMBER : {
double num = node.getDouble();
int inum = (int)num;
if (inum == num) {
if (inum == 0) {
iCodeTop = addByte(TokenStream.ZERO, iCodeTop);
}
else if (inum == 1) {
iCodeTop = addByte(TokenStream.ONE, iCodeTop);
}
else if ((short)inum == inum) {
iCodeTop = addByte(SHORTNUMBER_ICODE, iCodeTop);
iCodeTop = addShort(inum, iCodeTop);
}
else {
iCodeTop = addByte(INTNUMBER_ICODE, iCodeTop);
iCodeTop = addInt(inum, iCodeTop);
}
}
else {
iCodeTop = addByte(TokenStream.NUMBER, iCodeTop);
iCodeTop = addDouble(num, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case TokenStream.POP :
case TokenStream.POPV :
iCodeTop = updateLineNumber(node, iCodeTop);
case TokenStream.ENTERWITH :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
itsStackDepth--;
break;
case TokenStream.GETTHIS :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(type, iCodeTop);
break;
case TokenStream.NEWSCOPE :
iCodeTop = addByte(type, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case TokenStream.LEAVEWITH :
iCodeTop = addByte(type, iCodeTop);
break;
case TokenStream.TRY : {
itsTryDepth++;
if (itsTryDepth > itsData.itsMaxTryDepth)
itsData.itsMaxTryDepth = itsTryDepth;
Node catchTarget = (Node)node.getProp(Node.TARGET_PROP);
Node finallyTarget = (Node)node.getProp(Node.FINALLY_PROP);
int tryStart = iCodeTop;
if (catchTarget == null) {
iCodeTop = addByte(TokenStream.TRY, iCodeTop);
iCodeTop = addShort(0, iCodeTop);
}
else {
iCodeTop = addGoto(catchTarget, TokenStream.TRY,
iCodeTop);
}
iCodeTop = addShort(0, iCodeTop);
Node lastChild = null;
/*
when we encounter the child of the catchTarget, we
set the stackDepth to 1 to account for the incoming
exception object.
*/
boolean insertedEndTry = false;
while (child != null) {
if (catchTarget != null && lastChild == catchTarget) {
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
/*
When the following child is the catchTarget
(or the finallyTarget if there are no catches),
the current child is the goto at the end of
the try statemets, we need to emit the endtry
before that goto.
*/
Node nextSibling = child.getNextSibling();
if (!insertedEndTry && nextSibling != null &&
(nextSibling == catchTarget ||
nextSibling == finallyTarget))
{
iCodeTop = addByte(TokenStream.ENDTRY,
iCodeTop);
insertedEndTry = true;
}
iCodeTop = generateICode(child, iCodeTop);
lastChild = child;
child = child.getNextSibling();
}
itsStackDepth = 0;
if (finallyTarget != null) {
// normal flow goes around the finally handler stublet
int skippyJumpStart = iCodeTop;
iCodeTop = addForwardGoto(TokenStream.GOTO, iCodeTop);
int finallyOffset = iCodeTop - tryStart;
recordJumpOffset(tryStart + 3, finallyOffset);
// on entry the stack will have the exception object
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int theLocalSlot = itsData.itsMaxLocals++;
iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addByte(TokenStream.POP, iCodeTop);
iCodeTop = addGoto(finallyTarget, TokenStream.GOSUB,
iCodeTop);
iCodeTop = addByte(TokenStream.USETEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addByte(TokenStream.JTHROW, iCodeTop);
itsStackDepth = 0;
resolveForwardGoto(skippyJumpStart, iCodeTop);
}
itsTryDepth--;
}
break;
case TokenStream.THROW :
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.THROW, iCodeTop);
itsStackDepth--;
break;
case TokenStream.RETURN :
iCodeTop = updateLineNumber(node, iCodeTop);
if (child != null) {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.RETURN, iCodeTop);
itsStackDepth--;
}
else {
iCodeTop = addByte(RETURN_UNDEF_ICODE, iCodeTop);
}
break;
case TokenStream.GETVAR : {
String name = node.getString();
if (itsData.itsNeedsActivation) {
// SETVAR handled this by turning into a SETPROP, but
// we can't do that to a GETVAR without manufacturing
// bogus children. Instead we use a special op to
// push the current scope.
iCodeTop = addByte(TokenStream.SCOPE, iCodeTop);
iCodeTop = addByte(TokenStream.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addByte(TokenStream.GETPROP, iCodeTop);
itsStackDepth--;
}
else {
int index = itsVariableTable.getOrdinal(name);
iCodeTop = addByte(TokenStream.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
}
break;
case TokenStream.SETVAR : {
if (itsData.itsNeedsActivation) {
child.setType(TokenStream.BINDNAME);
node.setType(TokenStream.SETNAME);
iCodeTop = generateICode(node, iCodeTop);
}
else {
String name = child.getString();
child = child.getNextSibling();
iCodeTop = generateICode(child, iCodeTop);
int index = itsVariableTable.getOrdinal(name);
iCodeTop = addByte(TokenStream.SETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
}
}
break;
case TokenStream.PRIMARY:
iCodeTop = addByte(node.getInt(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case TokenStream.ENUMINIT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addByte(TokenStream.ENUMINIT, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
itsStackDepth--;
break;
case TokenStream.ENUMNEXT : {
iCodeTop = addByte(TokenStream.ENUMNEXT, iCodeTop);
Node init = (Node)node.getProp(Node.ENUM_PROP);
iCodeTop = addLocalRef(init, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
case TokenStream.ENUMDONE :
// could release the local here??
break;
case TokenStream.OBJECT : {
Node regexp = (Node) node.getProp(Node.REGEXP_PROP);
int index = regexp.getExistingIntProp(Node.REGEXP_PROP);
iCodeTop = addByte(TokenStream.OBJECT, iCodeTop);
iCodeTop = addShort(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
default :
badTree(node);
break;
}
return iCodeTop;
}
private int addLocalRef(Node node, int iCodeTop)
{
int theLocalSlot = node.getIntProp(Node.LOCAL_PROP, -1);
if (theLocalSlot == -1) {
theLocalSlot = itsData.itsMaxLocals++;
node.putIntProp(Node.LOCAL_PROP, theLocalSlot);
}
iCodeTop = addByte(theLocalSlot, iCodeTop);
if (theLocalSlot >= itsData.itsMaxLocals)
itsData.itsMaxLocals = theLocalSlot + 1;
return iCodeTop;
}
private int getTargetLabel(Node target) {
int targetLabel = target.getIntProp(Node.LABEL_PROP, -1);
if (targetLabel == -1) {
targetLabel = itsLabels.acquireLabel();
target.putIntProp(Node.LABEL_PROP, targetLabel);
}
return targetLabel;
}
private void markTargetLabel(Node target, int iCodeTop) {
int label = getTargetLabel(target);
itsLabels.markLabel(label, iCodeTop);
}
private int addGoto(Node target, int gotoOp, int iCodeTop) {
int targetLabel = getTargetLabel(target);
int gotoPC = iCodeTop;
iCodeTop = addByte(gotoOp, iCodeTop);
iCodeTop = addShort(0, iCodeTop);
int targetPC = itsLabels.getLabelPC(targetLabel);
if (targetPC != -1) {
recordJumpOffset(gotoPC + 1, targetPC - gotoPC);
}
else {
itsLabels.addLabelFixup(targetLabel, gotoPC + 1);
}
return iCodeTop;
}
private int addForwardGoto(int gotoOp, int iCodeTop) {
iCodeTop = addByte(gotoOp, iCodeTop);
iCodeTop = addShort(0, iCodeTop);
return iCodeTop;
}
private void resolveForwardGoto(int jumpStart, int iCodeTop) {
if (jumpStart + 3 > iCodeTop) Context.codeBug();
int offset = iCodeTop - jumpStart;
// +1 to write after jump icode
recordJumpOffset(jumpStart + 1, offset);
}
private void recordJumpOffset(int pos, int offset) {
if (offset != (short)offset) {
throw Context.reportRuntimeError
("Program too complex: too big jump offset");
}
itsData.itsICode[pos] = (byte)(offset >> 8);
itsData.itsICode[pos + 1] = (byte)offset;
}
private int addByte(int b, int iCodeTop) {
byte[] array = itsData.itsICode;
if (iCodeTop == array.length) {
array = increaseICodeCapasity(iCodeTop, 1);
}
array[iCodeTop++] = (byte)b;
return iCodeTop;
}
private int addShort(int s, int iCodeTop) {
byte[] array = itsData.itsICode;
if (iCodeTop + 2 > array.length) {
array = increaseICodeCapasity(iCodeTop, 2);
}
array[iCodeTop] = (byte)(s >>> 8);
array[iCodeTop + 1] = (byte)s;
return iCodeTop + 2;
}
private int addInt(int i, int iCodeTop) {
byte[] array = itsData.itsICode;
if (iCodeTop + 4 > array.length) {
array = increaseICodeCapasity(iCodeTop, 4);
}
array[iCodeTop] = (byte)(i >>> 24);
array[iCodeTop + 1] = (byte)(i >>> 16);
array[iCodeTop + 2] = (byte)(i >>> 8);
array[iCodeTop + 3] = (byte)i;
return iCodeTop + 4;
}
private int addDouble(double num, int iCodeTop) {
int index = itsDoubleTableTop;
if (index == 0) {
itsData.itsDoubleTable = new double[64];
}
else if (itsData.itsDoubleTable.length == index) {
double[] na = new double[index * 2];
System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index);
itsData.itsDoubleTable = na;
}
itsData.itsDoubleTable[index] = num;
itsDoubleTableTop = index + 1;
iCodeTop = addShort(index, iCodeTop);
return iCodeTop;
}
private int addString(String str, int iCodeTop) {
int index = itsStrings.get(str, -1);
if (index == -1) {
index = itsStrings.size();
itsStrings.put(str, index);
}
iCodeTop = addShort(index, iCodeTop);
return iCodeTop;
}
private byte[] increaseICodeCapasity(int iCodeTop, int extraSize) {
int capacity = itsData.itsICode.length;
if (iCodeTop + extraSize <= capacity) Context.codeBug();
capacity *= 2;
if (iCodeTop + extraSize > capacity) {
capacity = iCodeTop + extraSize;
}
byte[] array = new byte[capacity];
System.arraycopy(itsData.itsICode, 0, array, 0, iCodeTop);
itsData.itsICode = array;
return array;
}
private static int getShort(byte[] iCode, int pc) {
return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getInt(byte[] iCode, int pc) {
return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16)
| ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF);
}
private static int getTarget(byte[] iCode, int pc) {
int displacement = getShort(iCode, pc);
return pc - 1 + displacement;
}
static PrintWriter out;
static {
if (Context.printICode) {
try {
out = new PrintWriter(new FileOutputStream("icode.txt"));
out.close();
}
catch (IOException x) {
}
}
}
private static String icodeToName(int icode) {
if (Context.printICode) {
if (icode <= TokenStream.LAST_TOKEN) {
return TokenStream.tokenToName(icode);
}else {
switch (icode) {
case LINE_ICODE: return "line";
case SOURCEFILE_ICODE: return "sourcefile";
case SHORTNUMBER_ICODE: return "shortnumber";
case INTNUMBER_ICODE: return "intnumber";
case RETURN_UNDEF_ICODE: return "return_undef";
case END_ICODE: return "end";
}
}
return "<UNKNOWN ICODE: "+icode+">";
}
return "";
}
private static void dumpICode(InterpreterData theData) {
if (Context.printICode) {
try {
int iCodeLength = theData.itsICodeTop;
byte iCode[] = theData.itsICode;
String[] strings = theData.itsStringTable;
out = new PrintWriter(new FileOutputStream("icode.txt", true));
out.println("ICode dump, for " + theData.itsName
+ ", length = " + iCodeLength);
out.println("MaxStack = " + theData.itsMaxStack);
for (int pc = 0; pc < iCodeLength; ) {
out.print("[" + pc + "] ");
int token = iCode[pc] & 0xff;
String tname = icodeToName(token);
int old_pc = pc;
++pc;
int icodeLength = icodeTokenLength(token);
switch (token) {
default:
if (icodeLength != 1) Context.codeBug();
out.println(tname);
break;
case TokenStream.GOSUB :
case TokenStream.GOTO :
case TokenStream.IFEQ :
case TokenStream.IFNE : {
int newPC = getTarget(iCode, pc);
out.println(tname + " " + newPC);
pc += 2;
}
break;
case TokenStream.TRY : {
int catch_offset = getShort(iCode, pc);
int finally_offset = getShort(iCode, pc + 2);
int catch_pc = (catch_offset == 0)
? -1 : pc - 1 + catch_offset;
int finally_pc = (finally_offset == 0)
? -1 : pc - 1 + finally_offset;
out.println(tname + " " + catch_pc
+ " " + finally_pc);
pc += 4;
}
break;
case TokenStream.RETSUB :
case TokenStream.ENUMINIT :
case TokenStream.ENUMNEXT :
case TokenStream.VARINC :
case TokenStream.VARDEC :
case TokenStream.GETVAR :
case TokenStream.SETVAR :
case TokenStream.NEWTEMP :
case TokenStream.USETEMP : {
int slot = (iCode[pc] & 0xFF);
out.println(tname + " " + slot);
pc++;
}
break;
case TokenStream.CALLSPECIAL : {
int line = getShort(iCode, pc);
String name = strings[getShort(iCode, pc + 2)];
int count = getShort(iCode, pc + 4);
out.println(tname + " " + count
+ " " + line + " " + name);
pc += 6;
}
break;
case TokenStream.OBJECT :
case TokenStream.CLOSURE :
case TokenStream.NEW :
case TokenStream.CALL : {
int count = getShort(iCode, pc + 2);
String name = strings[getShort(iCode, pc)];
out.println(tname + " " + count + " \""
+ name + "\"");
pc += 4;
}
break;
case SHORTNUMBER_ICODE : {
int value = getShort(iCode, pc);
out.println(tname + " " + value);
pc += 2;
}
break;
case INTNUMBER_ICODE : {
int value = getInt(iCode, pc);
out.println(tname + " " + value);
pc += 4;
}
break;
case TokenStream.NUMBER : {
int index = getShort(iCode, pc);
double value = theData.itsDoubleTable[index];
out.println(tname + " " + value);
pc += 2;
}
break;
case TokenStream.TYPEOFNAME :
case TokenStream.GETBASE :
case TokenStream.BINDNAME :
case TokenStream.SETNAME :
case TokenStream.NAME :
case TokenStream.NAMEINC :
case TokenStream.NAMEDEC :
case TokenStream.STRING :
out.println(tname + " \""
+ strings[getShort(iCode, pc)] + "\"");
pc += 2;
break;
case LINE_ICODE : {
int line = getShort(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
}
break;
}
if (old_pc + icodeLength != pc) Context.codeBug();
}
out.close();
}
catch (IOException x) {}
}
}
private static int icodeTokenLength(int icodeToken) {
switch (icodeToken) {
case TokenStream.SCOPE :
case TokenStream.GETPROTO :
case TokenStream.GETPARENT :
case TokenStream.GETSCOPEPARENT :
case TokenStream.SETPROTO :
case TokenStream.SETPARENT :
case TokenStream.DELPROP :
case TokenStream.TYPEOF :
case TokenStream.NEWSCOPE :
case TokenStream.ENTERWITH :
case TokenStream.LEAVEWITH :
case TokenStream.RETURN :
case TokenStream.ENDTRY :
case TokenStream.THROW :
case TokenStream.JTHROW :
case TokenStream.GETTHIS :
case TokenStream.SETELEM :
case TokenStream.GETELEM :
case TokenStream.SETPROP :
case TokenStream.GETPROP :
case TokenStream.PROPINC :
case TokenStream.PROPDEC :
case TokenStream.ELEMINC :
case TokenStream.ELEMDEC :
case TokenStream.BITNOT :
case TokenStream.BITAND :
case TokenStream.BITOR :
case TokenStream.BITXOR :
case TokenStream.LSH :
case TokenStream.RSH :
case TokenStream.URSH :
case TokenStream.NEG :
case TokenStream.POS :
case TokenStream.SUB :
case TokenStream.MUL :
case TokenStream.DIV :
case TokenStream.MOD :
case TokenStream.ADD :
case TokenStream.POPV :
case TokenStream.POP :
case TokenStream.DUP :
case TokenStream.LT :
case TokenStream.GT :
case TokenStream.LE :
case TokenStream.GE :
case TokenStream.IN :
case TokenStream.INSTANCEOF :
case TokenStream.EQ :
case TokenStream.NE :
case TokenStream.SHEQ :
case TokenStream.SHNE :
case TokenStream.ZERO :
case TokenStream.ONE :
case TokenStream.NULL :
case TokenStream.THIS :
case TokenStream.THISFN :
case TokenStream.FALSE :
case TokenStream.TRUE :
case TokenStream.UNDEFINED :
case SOURCEFILE_ICODE :
case RETURN_UNDEF_ICODE:
case END_ICODE:
return 1;
case TokenStream.GOSUB :
case TokenStream.GOTO :
case TokenStream.IFEQ :
case TokenStream.IFNE :
// target pc offset
return 1 + 2;
case TokenStream.TRY :
// catch pc offset or 0
// finally pc offset or 0
return 1 + 2 + 2;
case TokenStream.RETSUB :
case TokenStream.ENUMINIT :
case TokenStream.ENUMNEXT :
case TokenStream.VARINC :
case TokenStream.VARDEC :
case TokenStream.GETVAR :
case TokenStream.SETVAR :
case TokenStream.NEWTEMP :
case TokenStream.USETEMP :
// slot index
return 1 + 1;
case TokenStream.CALLSPECIAL :
// line number
// name string index
// arg count
return 1 + 2 + 2 + 2;
case TokenStream.OBJECT :
case TokenStream.CLOSURE :
case TokenStream.NEW :
case TokenStream.CALL :
// name string index
// arg count
return 1 + 2 + 2;
case SHORTNUMBER_ICODE :
// short number
return 1 + 2;
case INTNUMBER_ICODE :
// int number
return 1 + 4;
case TokenStream.NUMBER :
// index of double number
return 1 + 2;
case TokenStream.TYPEOFNAME :
case TokenStream.GETBASE :
case TokenStream.BINDNAME :
case TokenStream.SETNAME :
case TokenStream.NAME :
case TokenStream.NAMEINC :
case TokenStream.NAMEDEC :
case TokenStream.STRING :
// string index
return 1 + 2;
case LINE_ICODE :
// line number
return 1 + 2;
default:
Context.codeBug(); // Bad icodeToken
return 0;
}
}
static int[] getLineNumbers(InterpreterData data) {
UintMap presentLines = new UintMap();
int iCodeLength = data.itsICodeTop;
byte[] iCode = data.itsICode;
for (int pc = 0; pc != iCodeLength;) {
int icodeToken = iCode[pc] & 0xff;
int icodeLength = icodeTokenLength(icodeToken);
if (icodeToken == LINE_ICODE) {
if (icodeLength != 3) Context.codeBug();
int line = getShort(iCode, pc + 1);
presentLines.put(line, 0);
}
pc += icodeLength;
}
return presentLines.getKeys();
}
private static void createFunctionObject(InterpretedFunction fn,
Scriptable scope,
boolean fromEvalCode)
{
fn.setPrototype(ScriptableObject.getFunctionPrototype(scope));
fn.setParentScope(scope);
InterpreterData idata = fn.itsData;
String fnName = idata.itsName;
if (fnName.length() == 0)
return;
int type = idata.itsFunctionType;
if (type == FunctionNode.FUNCTION_STATEMENT) {
if (fn.itsClosure == null) {
if (fromEvalCode) {
scope.put(fnName, scope, fn);
} else {
// ECMA specifies that functions defined in global and
// function scope should have DONTDELETE set.
ScriptableObject.defineProperty(scope,
fnName, fn, ScriptableObject.PERMANENT);
}
}
} else if (type == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) {
if (fn.itsClosure != null) {
scope.put(fnName, scope, fn);
}
}
}
public static Object interpret(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
// If securityDomain is different, update domain in Cotext
// and call self under new domain
Object savedDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = idata.securityDomain;
try {
return interpret(cx, scope, thisObj, args, fnOrScript, idata);
} finally {
cx.interpreterSecurityDomain = savedDomain;
}
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int TRY_STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
final int STACK_SHFT = TRY_STACK_SHFT + idata.itsMaxTryDepth;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[TRY_STACK_SHFT <= i < STACK_SHFT]: stack of try scopes
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[TRY_STACK_SHFT <= i < STACK_SHFT]: stack of try block pc, stored as doubles
// sDbl[any other i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int tryStackTop = 0; // add TRY_STACK_SHFT to get real index
int definedArgs = fnOrScript.argCount;
if (definedArgs != 0) {
if (definedArgs > args.length) { definedArgs = args.length; }
for (int i = 0; i != definedArgs; ++i) {
stack[VAR_SHFT + i] = args[i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
DebuggableScript dscript = (DebuggableScript)fnOrScript;
debuggerFrame = cx.debugger.getFrame(cx, dscript);
}
if (idata.itsFunctionType != 0) {
if (fnOrScript.itsClosure != null) {
scope = fnOrScript.itsClosure;
} else if (!idata.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
createFunctionObject(idata.itsNestedFunctions[i], scope,
idata.itsFromEvalCode);
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
Object result = undefined;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: while (true) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case TokenStream.ENDTRY :
tryStackTop--;
break;
case TokenStream.TRY :
stack[TRY_STACK_SHFT + tryStackTop] = scope;
sDbl[TRY_STACK_SHFT + tryStackTop] = (double)pc;
++tryStackTop;
// Skip starting pc of catch/finally blocks
pc += 4;
break;
case TokenStream.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(scope, lhs, rhs);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.IFNE : {
Object val = stack[stackTop];
boolean valBln;
if (val != DBL_MRK) {
valBln = !ScriptRuntime.toBoolean(val);
} else {
double valDbl = sDbl[stackTop];
valBln = !(valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
}
case TokenStream.IFEQ : {
boolean valBln;
Object val = stack[stackTop];
if (val != DBL_MRK) {
valBln = ScriptRuntime.toBoolean(val);
} else {
double valDbl = sDbl[stackTop];
valBln = (valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
}
case TokenStream.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
case TokenStream.GOSUB :
sDbl[++stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue;
case TokenStream.RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot];
continue;
}
case TokenStream.POP :
stackTop--;
break;
case TokenStream.DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case TokenStream.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break;
case TokenStream.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case RETURN_UNDEF_ICODE :
result = undefined;
break Loop;
case END_ICODE:
break Loop;
case TokenStream.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case TokenStream.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case TokenStream.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case TokenStream.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case TokenStream.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case TokenStream.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case TokenStream.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case TokenStream.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case TokenStream.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case TokenStream.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case TokenStream.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case TokenStream.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case TokenStream.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case TokenStream.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case TokenStream.BINDNAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case TokenStream.GETBASE : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case TokenStream.SETNAME : {
String name = strings[getShort(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case TokenStream.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs);
break;
}
case TokenStream.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case TokenStream.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case TokenStream.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case TokenStream.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case TokenStream.PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case TokenStream.PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case TokenStream.ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case TokenStream.ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case TokenStream.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case TokenStream.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case TokenStream.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case TokenStream.CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int lineNum = getShort(iCode, pc + 1);
String name = strings[getShort(iCode, pc + 3)];
int count = getShort(iCode, pc + 5);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, lhs, rhs, outArgs,
thisObj, scope, name, lineNum);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case TokenStream.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
int count = getShort(iCode, pc + 3);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined) {
int i = getShort(iCode, pc + 1);
if (i != -1) lhs = strings[i];
}
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs, outArgs,
calleeScope);
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case TokenStream.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getShort(iCode, pc + 3);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined && getShort(iCode, pc + 1) != -1) {
// special code for better error message for call
// to undefined
lhs = strings[getShort(iCode, pc + 1)];
}
stack[stackTop] = ScriptRuntime.newObject(cx, lhs, outArgs, scope);
pc += 4; instructionCount = cx.instructionCount;
break;
}
case TokenStream.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case TokenStream.TYPEOFNAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case TokenStream.STRING :
stack[++stackTop] = strings[getShort(iCode, pc + 1)];
pc += 2;
break;
case SHORTNUMBER_ICODE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case INTNUMBER_ICODE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case TokenStream.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.NAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case TokenStream.NAMEINC : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case TokenStream.NAMEDEC : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case TokenStream.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case TokenStream.VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case TokenStream.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case TokenStream.NULL :
stack[++stackTop] = null;
break;
case TokenStream.THIS :
stack[++stackTop] = thisObj;
break;
case TokenStream.THISFN :
stack[++stackTop] = fnOrScript;
break;
case TokenStream.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case TokenStream.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case TokenStream.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case TokenStream.THROW : {
Object exception = stack[stackTop];
if (exception == DBL_MRK) exception = doubleWrap(sDbl[stackTop]);
--stackTop;
throw new JavaScriptException(exception);
}
case TokenStream.JTHROW : {
Object exception = stack[stackTop];
// No need to check for DBL_MRK: exception must be Exception
--stackTop;
if (exception instanceof JavaScriptException)
throw (JavaScriptException)exception;
else
throw (RuntimeException)exception;
}
case TokenStream.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
break;
}
case TokenStream.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
break;
case TokenStream.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case TokenStream.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case TokenStream.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case TokenStream.GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case TokenStream.GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case TokenStream.GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case TokenStream.SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case TokenStream.SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case TokenStream.SCOPE :
stack[++stackTop] = scope;
break;
case TokenStream.CLOSURE : {
int i = getShort(iCode, pc + 1);
InterpretedFunction f = idata.itsNestedFunctions[i];
InterpretedFunction closure = new InterpretedFunction(f, scope, cx);
createFunctionObject(closure, scope, idata.itsFromEvalCode);
stack[++stackTop] = closure;
pc += 2;
break;
}
case TokenStream.OBJECT : {
int i = getShort(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case SOURCEFILE_ICODE :
cx.interpreterSourceFile = idata.itsSourceFile;
break;
case LINE_ICODE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3;
int exType;
Object catchObj = ex; // Object seen by script catch
for (;;) {
if (catchObj instanceof JavaScriptException) {
catchObj = ScriptRuntime.unwrapJavaScriptException
((JavaScriptException)catchObj);
exType = SCRIPT_THROW;
} else if (catchObj instanceof EcmaError) {
// an offical ECMA error object,
catchObj = ((EcmaError)catchObj).getErrorObject();
exType = ECMA;
} else if (catchObj instanceof RuntimeException) {
if (catchObj instanceof WrappedException) {
Object w = ((WrappedException) catchObj).unwrap();
if (w instanceof Throwable) {
- catchObj = (Throwable) w;
+ catchObj = ex = (Throwable) w;
continue;
}
}
catchObj = null; // script can not catch this
exType = RUNTIME;
} else {
// Error instance
catchObj = null; // script can not catch this
exType = OTHER;
}
break;
}
if (exType != OTHER && debuggerFrame != null) {
debuggerFrame.onExceptionThrown(cx, ex);
}
boolean rethrow = true;
if (exType != OTHER && tryStackTop > 0) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
--tryStackTop;
int try_pc = (int)sDbl[TRY_STACK_SHFT + tryStackTop];
if (exType == SCRIPT_THROW || exType == ECMA) {
// Allow JS to catch only JavaScriptException and
// EcmaError
int catch_offset = getShort(iCode, try_pc + 1);
if (catch_offset != 0) {
// Has catch block
rethrow = false;
pc = try_pc + catch_offset;
stackTop = STACK_SHFT;
stack[stackTop] = catchObj;
}
}
if (rethrow) {
int finally_offset = getShort(iCode, try_pc + 3);
if (finally_offset != 0) {
// has finally block
rethrow = false;
pc = try_pc + finally_offset;
stackTop = STACK_SHFT;
stack[stackTop] = ex;
}
}
}
if (rethrow) {
if (debuggerFrame != null) {
debuggerFrame.onExit(cx, true, ex);
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (exType == SCRIPT_THROW)
throw (JavaScriptException)ex;
if (exType == ECMA || exType == RUNTIME)
throw (RuntimeException)ex;
throw (Error)ex;
}
// We caught an exception,
// Notify instruction observer if necessary
// and point pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc;
// restore scope at try point
scope = (Scriptable)stack[TRY_STACK_SHFT + tryStackTop];
}
}
if (debuggerFrame != null) {
debuggerFrame.onExit(cx, false, result);
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
return result;
}
private static Object doubleWrap(double x) {
return new Double(x);
}
private static int stack_int32(Object[] stack, double[] stackDbl, int i) {
Object x = stack[i];
return (x != DBL_MRK)
? ScriptRuntime.toInt32(x)
: ScriptRuntime.toInt32(stackDbl[i]);
}
private static double stack_double(Object[] stack, double[] stackDbl,
int i)
{
Object x = stack[i];
return (x != DBL_MRK) ? ScriptRuntime.toNumber(x) : stackDbl[i];
}
private static void do_add(Object[] stack, double[] stackDbl, int stackTop)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
stackDbl[stackTop] += rDbl;
}
else {
do_add(lhs, rDbl, stack, stackDbl, stackTop, true);
}
}
else if (lhs == DBL_MRK) {
do_add(rhs, stackDbl[stackTop], stack, stackDbl, stackTop, false);
}
else {
if (lhs instanceof Scriptable)
lhs = ((Scriptable) lhs).getDefaultValue(null);
if (rhs instanceof Scriptable)
rhs = ((Scriptable) rhs).getDefaultValue(null);
if (lhs instanceof String || rhs instanceof String) {
stack[stackTop] = ScriptRuntime.toString(lhs)
+ ScriptRuntime.toString(rhs);
}
else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
double rDbl = (rhs instanceof Number)
? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
}
// x + y when x is Number, see
private static void do_add
(Object lhs, double rDbl,
Object[] stack, double[] stackDbl, int stackTop,
boolean left_right_order)
{
if (lhs instanceof Scriptable) {
if (lhs == Undefined.instance) {
lhs = ScriptRuntime.NaNobj;
} else {
lhs = ((Scriptable)lhs).getDefaultValue(null);
}
}
if (lhs instanceof String) {
if (left_right_order) {
stack[stackTop] = (String)lhs + ScriptRuntime.toString(rDbl);
}
else {
stack[stackTop] = ScriptRuntime.toString(rDbl) + (String)lhs;
}
}
else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
private static boolean do_eq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == stackDbl[stackTop + 1]);
}
else {
result = do_eq(stackDbl[stackTop + 1], lhs);
}
}
else {
if (lhs == DBL_MRK) {
result = do_eq(stackDbl[stackTop], rhs);
}
else {
result = ScriptRuntime.eq(lhs, rhs);
}
}
return result;
}
// Optimized version of ScriptRuntime.eq if x is a Number
private static boolean do_eq(double x, Object y) {
for (;;) {
if (y instanceof Number) {
return x == ((Number) y).doubleValue();
}
if (y instanceof String) {
return x == ScriptRuntime.toNumber((String)y);
}
if (y instanceof Boolean) {
return x == (((Boolean)y).booleanValue() ? 1 : 0);
}
if (y instanceof Scriptable) {
if (y == Undefined.instance) { return false; }
y = ScriptRuntime.toPrimitive(y);
continue;
}
return false;
}
}
private static boolean do_sheq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
}
else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
}
else if (rhs instanceof Number) {
double rDbl = ((Number)rhs).doubleValue();
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
}
else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
}
else {
result = ScriptRuntime.shallowEq(lhs, rhs);
}
return result;
}
private static void do_getElem(Context cx,
Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object lhs = stack[stackTop - 1];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 1]);
Object result;
Object id = stack[stackTop];
if (id != DBL_MRK) {
result = ScriptRuntime.getElem(lhs, id, scope);
}
else {
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(cx, scope, lhs);
double val = stackDbl[stackTop];
int index = (int)val;
if (index == val) {
result = ScriptRuntime.getElem(obj, index);
}
else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.getStrIdElem(obj, s);
}
}
stack[stackTop - 1] = result;
}
private static void do_setElem(Context cx,
Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(stackDbl[stackTop]);
Object lhs = stack[stackTop - 2];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 2]);
Object result;
Object id = stack[stackTop - 1];
if (id != DBL_MRK) {
result = ScriptRuntime.setElem(lhs, id, rhs, scope);
}
else {
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(cx, scope, lhs);
double val = stackDbl[stackTop - 1];
int index = (int)val;
if (index == val) {
result = ScriptRuntime.setElem(obj, index, rhs);
}
else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.setStrIdElem(obj, s, rhs, scope);
}
}
stack[stackTop - 2] = result;
}
private static Object[] getArgsArray(Object[] stack, double[] sDbl,
int stackTop, int count)
{
if (count == 0) {
return ScriptRuntime.emptyArgs;
}
Object[] args = new Object[count];
do {
Object val = stack[stackTop];
if (val == DBL_MRK)
val = doubleWrap(sDbl[stackTop]);
args[--count] = val;
--stackTop;
} while (count != 0);
return args;
}
private static Object activationGet(NativeFunction f,
Scriptable activation, int slot)
{
String name = f.argNames[slot];
Object val = activation.get(name, activation);
// Activation parameter or var is permanent
if (val == Scriptable.NOT_FOUND) Context.codeBug();
return val;
}
private static void activationPut(NativeFunction f,
Scriptable activation, int slot,
Object value)
{
String name = f.argNames[slot];
activation.put(name, activation, value);
}
private boolean itsInFunctionFlag;
private InterpreterData itsData;
private VariableTable itsVariableTable;
private int itsTryDepth = 0;
private int itsStackDepth = 0;
private String itsSourceFile;
private int itsLineNumber = 0;
private LabelTable itsLabels = new LabelTable();
private int itsDoubleTableTop;
private ObjToIntMap itsStrings = new ObjToIntMap(20);
private int version;
private boolean inLineStepMode;
private String debugSource;
private static final Object DBL_MRK = new Object();
}
| true | true | public static Object interpret(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
// If securityDomain is different, update domain in Cotext
// and call self under new domain
Object savedDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = idata.securityDomain;
try {
return interpret(cx, scope, thisObj, args, fnOrScript, idata);
} finally {
cx.interpreterSecurityDomain = savedDomain;
}
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int TRY_STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
final int STACK_SHFT = TRY_STACK_SHFT + idata.itsMaxTryDepth;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[TRY_STACK_SHFT <= i < STACK_SHFT]: stack of try scopes
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[TRY_STACK_SHFT <= i < STACK_SHFT]: stack of try block pc, stored as doubles
// sDbl[any other i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int tryStackTop = 0; // add TRY_STACK_SHFT to get real index
int definedArgs = fnOrScript.argCount;
if (definedArgs != 0) {
if (definedArgs > args.length) { definedArgs = args.length; }
for (int i = 0; i != definedArgs; ++i) {
stack[VAR_SHFT + i] = args[i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
DebuggableScript dscript = (DebuggableScript)fnOrScript;
debuggerFrame = cx.debugger.getFrame(cx, dscript);
}
if (idata.itsFunctionType != 0) {
if (fnOrScript.itsClosure != null) {
scope = fnOrScript.itsClosure;
} else if (!idata.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
createFunctionObject(idata.itsNestedFunctions[i], scope,
idata.itsFromEvalCode);
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
Object result = undefined;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: while (true) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case TokenStream.ENDTRY :
tryStackTop--;
break;
case TokenStream.TRY :
stack[TRY_STACK_SHFT + tryStackTop] = scope;
sDbl[TRY_STACK_SHFT + tryStackTop] = (double)pc;
++tryStackTop;
// Skip starting pc of catch/finally blocks
pc += 4;
break;
case TokenStream.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(scope, lhs, rhs);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.IFNE : {
Object val = stack[stackTop];
boolean valBln;
if (val != DBL_MRK) {
valBln = !ScriptRuntime.toBoolean(val);
} else {
double valDbl = sDbl[stackTop];
valBln = !(valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
}
case TokenStream.IFEQ : {
boolean valBln;
Object val = stack[stackTop];
if (val != DBL_MRK) {
valBln = ScriptRuntime.toBoolean(val);
} else {
double valDbl = sDbl[stackTop];
valBln = (valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
}
case TokenStream.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
case TokenStream.GOSUB :
sDbl[++stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue;
case TokenStream.RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot];
continue;
}
case TokenStream.POP :
stackTop--;
break;
case TokenStream.DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case TokenStream.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break;
case TokenStream.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case RETURN_UNDEF_ICODE :
result = undefined;
break Loop;
case END_ICODE:
break Loop;
case TokenStream.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case TokenStream.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case TokenStream.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case TokenStream.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case TokenStream.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case TokenStream.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case TokenStream.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case TokenStream.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case TokenStream.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case TokenStream.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case TokenStream.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case TokenStream.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case TokenStream.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case TokenStream.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case TokenStream.BINDNAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case TokenStream.GETBASE : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case TokenStream.SETNAME : {
String name = strings[getShort(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case TokenStream.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs);
break;
}
case TokenStream.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case TokenStream.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case TokenStream.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case TokenStream.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case TokenStream.PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case TokenStream.PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case TokenStream.ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case TokenStream.ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case TokenStream.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case TokenStream.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case TokenStream.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case TokenStream.CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int lineNum = getShort(iCode, pc + 1);
String name = strings[getShort(iCode, pc + 3)];
int count = getShort(iCode, pc + 5);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, lhs, rhs, outArgs,
thisObj, scope, name, lineNum);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case TokenStream.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
int count = getShort(iCode, pc + 3);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined) {
int i = getShort(iCode, pc + 1);
if (i != -1) lhs = strings[i];
}
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs, outArgs,
calleeScope);
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case TokenStream.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getShort(iCode, pc + 3);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined && getShort(iCode, pc + 1) != -1) {
// special code for better error message for call
// to undefined
lhs = strings[getShort(iCode, pc + 1)];
}
stack[stackTop] = ScriptRuntime.newObject(cx, lhs, outArgs, scope);
pc += 4; instructionCount = cx.instructionCount;
break;
}
case TokenStream.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case TokenStream.TYPEOFNAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case TokenStream.STRING :
stack[++stackTop] = strings[getShort(iCode, pc + 1)];
pc += 2;
break;
case SHORTNUMBER_ICODE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case INTNUMBER_ICODE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case TokenStream.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.NAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case TokenStream.NAMEINC : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case TokenStream.NAMEDEC : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case TokenStream.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case TokenStream.VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case TokenStream.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case TokenStream.NULL :
stack[++stackTop] = null;
break;
case TokenStream.THIS :
stack[++stackTop] = thisObj;
break;
case TokenStream.THISFN :
stack[++stackTop] = fnOrScript;
break;
case TokenStream.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case TokenStream.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case TokenStream.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case TokenStream.THROW : {
Object exception = stack[stackTop];
if (exception == DBL_MRK) exception = doubleWrap(sDbl[stackTop]);
--stackTop;
throw new JavaScriptException(exception);
}
case TokenStream.JTHROW : {
Object exception = stack[stackTop];
// No need to check for DBL_MRK: exception must be Exception
--stackTop;
if (exception instanceof JavaScriptException)
throw (JavaScriptException)exception;
else
throw (RuntimeException)exception;
}
case TokenStream.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
break;
}
case TokenStream.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
break;
case TokenStream.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case TokenStream.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case TokenStream.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case TokenStream.GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case TokenStream.GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case TokenStream.GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case TokenStream.SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case TokenStream.SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case TokenStream.SCOPE :
stack[++stackTop] = scope;
break;
case TokenStream.CLOSURE : {
int i = getShort(iCode, pc + 1);
InterpretedFunction f = idata.itsNestedFunctions[i];
InterpretedFunction closure = new InterpretedFunction(f, scope, cx);
createFunctionObject(closure, scope, idata.itsFromEvalCode);
stack[++stackTop] = closure;
pc += 2;
break;
}
case TokenStream.OBJECT : {
int i = getShort(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case SOURCEFILE_ICODE :
cx.interpreterSourceFile = idata.itsSourceFile;
break;
case LINE_ICODE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3;
int exType;
Object catchObj = ex; // Object seen by script catch
for (;;) {
if (catchObj instanceof JavaScriptException) {
catchObj = ScriptRuntime.unwrapJavaScriptException
((JavaScriptException)catchObj);
exType = SCRIPT_THROW;
} else if (catchObj instanceof EcmaError) {
// an offical ECMA error object,
catchObj = ((EcmaError)catchObj).getErrorObject();
exType = ECMA;
} else if (catchObj instanceof RuntimeException) {
if (catchObj instanceof WrappedException) {
Object w = ((WrappedException) catchObj).unwrap();
if (w instanceof Throwable) {
catchObj = (Throwable) w;
continue;
}
}
catchObj = null; // script can not catch this
exType = RUNTIME;
} else {
// Error instance
catchObj = null; // script can not catch this
exType = OTHER;
}
break;
}
if (exType != OTHER && debuggerFrame != null) {
debuggerFrame.onExceptionThrown(cx, ex);
}
boolean rethrow = true;
if (exType != OTHER && tryStackTop > 0) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
--tryStackTop;
int try_pc = (int)sDbl[TRY_STACK_SHFT + tryStackTop];
if (exType == SCRIPT_THROW || exType == ECMA) {
// Allow JS to catch only JavaScriptException and
// EcmaError
int catch_offset = getShort(iCode, try_pc + 1);
if (catch_offset != 0) {
// Has catch block
rethrow = false;
pc = try_pc + catch_offset;
stackTop = STACK_SHFT;
stack[stackTop] = catchObj;
}
}
if (rethrow) {
int finally_offset = getShort(iCode, try_pc + 3);
if (finally_offset != 0) {
// has finally block
rethrow = false;
pc = try_pc + finally_offset;
stackTop = STACK_SHFT;
stack[stackTop] = ex;
}
}
}
if (rethrow) {
if (debuggerFrame != null) {
debuggerFrame.onExit(cx, true, ex);
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (exType == SCRIPT_THROW)
throw (JavaScriptException)ex;
if (exType == ECMA || exType == RUNTIME)
throw (RuntimeException)ex;
throw (Error)ex;
}
// We caught an exception,
// Notify instruction observer if necessary
// and point pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc;
// restore scope at try point
scope = (Scriptable)stack[TRY_STACK_SHFT + tryStackTop];
}
}
if (debuggerFrame != null) {
debuggerFrame.onExit(cx, false, result);
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
return result;
}
| public static Object interpret(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
// If securityDomain is different, update domain in Cotext
// and call self under new domain
Object savedDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = idata.securityDomain;
try {
return interpret(cx, scope, thisObj, args, fnOrScript, idata);
} finally {
cx.interpreterSecurityDomain = savedDomain;
}
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int TRY_STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
final int STACK_SHFT = TRY_STACK_SHFT + idata.itsMaxTryDepth;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[TRY_STACK_SHFT <= i < STACK_SHFT]: stack of try scopes
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[TRY_STACK_SHFT <= i < STACK_SHFT]: stack of try block pc, stored as doubles
// sDbl[any other i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int tryStackTop = 0; // add TRY_STACK_SHFT to get real index
int definedArgs = fnOrScript.argCount;
if (definedArgs != 0) {
if (definedArgs > args.length) { definedArgs = args.length; }
for (int i = 0; i != definedArgs; ++i) {
stack[VAR_SHFT + i] = args[i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
DebuggableScript dscript = (DebuggableScript)fnOrScript;
debuggerFrame = cx.debugger.getFrame(cx, dscript);
}
if (idata.itsFunctionType != 0) {
if (fnOrScript.itsClosure != null) {
scope = fnOrScript.itsClosure;
} else if (!idata.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
createFunctionObject(idata.itsNestedFunctions[i], scope,
idata.itsFromEvalCode);
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
Object result = undefined;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: while (true) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case TokenStream.ENDTRY :
tryStackTop--;
break;
case TokenStream.TRY :
stack[TRY_STACK_SHFT + tryStackTop] = scope;
sDbl[TRY_STACK_SHFT + tryStackTop] = (double)pc;
++tryStackTop;
// Skip starting pc of catch/finally blocks
pc += 4;
break;
case TokenStream.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(scope, lhs, rhs);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case TokenStream.IFNE : {
Object val = stack[stackTop];
boolean valBln;
if (val != DBL_MRK) {
valBln = !ScriptRuntime.toBoolean(val);
} else {
double valDbl = sDbl[stackTop];
valBln = !(valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
}
case TokenStream.IFEQ : {
boolean valBln;
Object val = stack[stackTop];
if (val != DBL_MRK) {
valBln = ScriptRuntime.toBoolean(val);
} else {
double valDbl = sDbl[stackTop];
valBln = (valDbl == valDbl && valDbl != 0.0);
}
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
}
pc += 2;
break;
}
case TokenStream.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue;
case TokenStream.GOSUB :
sDbl[++stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue;
case TokenStream.RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot];
continue;
}
case TokenStream.POP :
stackTop--;
break;
case TokenStream.DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case TokenStream.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break;
case TokenStream.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case RETURN_UNDEF_ICODE :
result = undefined;
break Loop;
case END_ICODE:
break Loop;
case TokenStream.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case TokenStream.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case TokenStream.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case TokenStream.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case TokenStream.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case TokenStream.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case TokenStream.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case TokenStream.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case TokenStream.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case TokenStream.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case TokenStream.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case TokenStream.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case TokenStream.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case TokenStream.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case TokenStream.BINDNAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case TokenStream.GETBASE : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case TokenStream.SETNAME : {
String name = strings[getShort(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case TokenStream.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs);
break;
}
case TokenStream.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case TokenStream.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case TokenStream.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case TokenStream.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case TokenStream.PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case TokenStream.PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case TokenStream.ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case TokenStream.ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case TokenStream.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case TokenStream.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case TokenStream.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case TokenStream.CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int lineNum = getShort(iCode, pc + 1);
String name = strings[getShort(iCode, pc + 3)];
int count = getShort(iCode, pc + 5);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, lhs, rhs, outArgs,
thisObj, scope, name, lineNum);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case TokenStream.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
int count = getShort(iCode, pc + 3);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined) {
int i = getShort(iCode, pc + 1);
if (i != -1) lhs = strings[i];
}
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs, outArgs,
calleeScope);
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case TokenStream.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getShort(iCode, pc + 3);
Object[] outArgs = getArgsArray(stack, sDbl, stackTop, count);
stackTop -= count;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
if (lhs == undefined && getShort(iCode, pc + 1) != -1) {
// special code for better error message for call
// to undefined
lhs = strings[getShort(iCode, pc + 1)];
}
stack[stackTop] = ScriptRuntime.newObject(cx, lhs, outArgs, scope);
pc += 4; instructionCount = cx.instructionCount;
break;
}
case TokenStream.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case TokenStream.TYPEOFNAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case TokenStream.STRING :
stack[++stackTop] = strings[getShort(iCode, pc + 1)];
pc += 2;
break;
case SHORTNUMBER_ICODE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case INTNUMBER_ICODE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case TokenStream.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getShort(iCode, pc + 1)];
pc += 2;
break;
case TokenStream.NAME : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case TokenStream.NAMEINC : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case TokenStream.NAMEDEC : {
String name = strings[getShort(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case TokenStream.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case TokenStream.VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case TokenStream.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case TokenStream.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case TokenStream.NULL :
stack[++stackTop] = null;
break;
case TokenStream.THIS :
stack[++stackTop] = thisObj;
break;
case TokenStream.THISFN :
stack[++stackTop] = fnOrScript;
break;
case TokenStream.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case TokenStream.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case TokenStream.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case TokenStream.THROW : {
Object exception = stack[stackTop];
if (exception == DBL_MRK) exception = doubleWrap(sDbl[stackTop]);
--stackTop;
throw new JavaScriptException(exception);
}
case TokenStream.JTHROW : {
Object exception = stack[stackTop];
// No need to check for DBL_MRK: exception must be Exception
--stackTop;
if (exception instanceof JavaScriptException)
throw (JavaScriptException)exception;
else
throw (RuntimeException)exception;
}
case TokenStream.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
break;
}
case TokenStream.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
break;
case TokenStream.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case TokenStream.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case TokenStream.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case TokenStream.GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case TokenStream.GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case TokenStream.GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case TokenStream.SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case TokenStream.SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case TokenStream.SCOPE :
stack[++stackTop] = scope;
break;
case TokenStream.CLOSURE : {
int i = getShort(iCode, pc + 1);
InterpretedFunction f = idata.itsNestedFunctions[i];
InterpretedFunction closure = new InterpretedFunction(f, scope, cx);
createFunctionObject(closure, scope, idata.itsFromEvalCode);
stack[++stackTop] = closure;
pc += 2;
break;
}
case TokenStream.OBJECT : {
int i = getShort(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case SOURCEFILE_ICODE :
cx.interpreterSourceFile = idata.itsSourceFile;
break;
case LINE_ICODE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3;
int exType;
Object catchObj = ex; // Object seen by script catch
for (;;) {
if (catchObj instanceof JavaScriptException) {
catchObj = ScriptRuntime.unwrapJavaScriptException
((JavaScriptException)catchObj);
exType = SCRIPT_THROW;
} else if (catchObj instanceof EcmaError) {
// an offical ECMA error object,
catchObj = ((EcmaError)catchObj).getErrorObject();
exType = ECMA;
} else if (catchObj instanceof RuntimeException) {
if (catchObj instanceof WrappedException) {
Object w = ((WrappedException) catchObj).unwrap();
if (w instanceof Throwable) {
catchObj = ex = (Throwable) w;
continue;
}
}
catchObj = null; // script can not catch this
exType = RUNTIME;
} else {
// Error instance
catchObj = null; // script can not catch this
exType = OTHER;
}
break;
}
if (exType != OTHER && debuggerFrame != null) {
debuggerFrame.onExceptionThrown(cx, ex);
}
boolean rethrow = true;
if (exType != OTHER && tryStackTop > 0) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
--tryStackTop;
int try_pc = (int)sDbl[TRY_STACK_SHFT + tryStackTop];
if (exType == SCRIPT_THROW || exType == ECMA) {
// Allow JS to catch only JavaScriptException and
// EcmaError
int catch_offset = getShort(iCode, try_pc + 1);
if (catch_offset != 0) {
// Has catch block
rethrow = false;
pc = try_pc + catch_offset;
stackTop = STACK_SHFT;
stack[stackTop] = catchObj;
}
}
if (rethrow) {
int finally_offset = getShort(iCode, try_pc + 3);
if (finally_offset != 0) {
// has finally block
rethrow = false;
pc = try_pc + finally_offset;
stackTop = STACK_SHFT;
stack[stackTop] = ex;
}
}
}
if (rethrow) {
if (debuggerFrame != null) {
debuggerFrame.onExit(cx, true, ex);
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (exType == SCRIPT_THROW)
throw (JavaScriptException)ex;
if (exType == ECMA || exType == RUNTIME)
throw (RuntimeException)ex;
throw (Error)ex;
}
// We caught an exception,
// Notify instruction observer if necessary
// and point pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc;
// restore scope at try point
scope = (Scriptable)stack[TRY_STACK_SHFT + tryStackTop];
}
}
if (debuggerFrame != null) {
debuggerFrame.onExit(cx, false, result);
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
return result;
}
|
diff --git a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/JavaScriptEngine.java b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/JavaScriptEngine.java
index 2ec5521a1..53ef12455 100644
--- a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/JavaScriptEngine.java
+++ b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/JavaScriptEngine.java
@@ -1,631 +1,632 @@
/*
* Copyright (c) 2002-2008 Gargoyle Software Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by Gargoyle Software Inc.
* (http://www.GargoyleSoftware.com/)."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
* 4. The name "Gargoyle Software" must not be used to endorse or promote
* products derived from this software without prior written permission.
* For written permission, please contact [email protected].
* 5. Products derived from this software may not be called "HtmlUnit", nor may
* "HtmlUnit" appear in their name, without prior written permission of
* Gargoyle Software Inc.
*
* 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 GARGOYLE
* SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gargoylesoftware.htmlunit.javascript;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextAction;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.FunctionObject;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import com.gargoylesoftware.htmlunit.Assert;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.ScriptPreProcessor;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.configuration.ClassConfiguration;
import com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration;
import com.gargoylesoftware.htmlunit.javascript.host.Window;
/**
* A wrapper for the <a href="http://www.mozilla.org/rhino">Rhino javascript engine</a>
* that provides browser specific features.<br/>
* Like all classes in this package, this class is not intended for direct use
* and may change without notice.
*
* @version $Revision$
* @author <a href="mailto:[email protected]">Mike Bowler</a>
* @author <a href="mailto:[email protected]">Chen Jun</a>
* @author David K. Taylor
* @author Chris Erskine
* @author <a href="mailto:[email protected]">Ben Curren</a>
* @author David D. Kilzer
* @author Marc Guillemot
* @author Daniel Gredler
* @author Ahmed Ashour
* @see <a href="http://groups-beta.google.com/group/netscape.public.mozilla.jseng/browse_thread/thread/b4edac57329cf49f/069e9307ec89111f">
* Rhino and Java Browser</a>
*/
public class JavaScriptEngine implements Serializable {
private static final long serialVersionUID = -5414040051465432088L;
private final WebClient webClient_;
private static final Log ScriptEngineLog_ = LogFactory.getLog(JavaScriptEngine.class);
private static final ThreadLocal javaScriptRunning_ = new ThreadLocal();
/**
* Cache parsed scripts (only for js files, not for js code embedded in html code)
* The WeakHashMap allows cached scripts to be GCed when the WebResponses are not retained
* in the {@link com.gargoylesoftware.htmlunit.Cache} anymore.
*/
private final transient Map cachedScripts_ = Collections.synchronizedMap(new WeakHashMap());
/**
* Key used to place the scope in which the execution of some javascript code
* started as thread local attribute in current context.<br/>
* This is needed to resolve some relative locations relatively to the page
* in which the script is executed and not to the page which location is changed.
*/
public static final String KEY_STARTING_SCOPE = "startingScope";
/**
* Initialize a context listener so we can count JS contexts and make sure we
* are freeing them as necessary.
*/
static {
final HtmlUnitContextFactory contextFactory = new HtmlUnitContextFactory(getScriptEngineLog());
ContextFactory.initGlobal(contextFactory);
}
/**
* Create an instance for the specified webclient
*
* @param webClient The webClient that will own this engine.
*/
public JavaScriptEngine(final WebClient webClient) {
webClient_ = webClient;
}
/**
* Return the web client that this engine is associated with.
* @return The web client.
*/
public final WebClient getWebClient() {
return webClient_;
}
/**
* Perform initialization for the given webWindow
* @param webWindow the web window to initialize for
*/
public void initialize(final WebWindow webWindow) {
Assert.notNull("webWindow", webWindow);
final ContextAction action = new ContextAction()
{
public Object run(final Context cx) {
try {
init(webWindow, cx);
}
catch (final Exception e) {
getLog().error("Exception while initializing JavaScript for the page", e);
throw new ScriptException(null, e); // BUG: null is not useful.
}
return null;
}
};
Context.call(action);
}
/**
* Initializes all the JS stuff for the window
* @param webWindow the web window
* @param context the current context
* @throws Exception if something goes wrong
*/
private void init(final WebWindow webWindow, final Context context) throws Exception {
final WebClient webClient = webWindow.getWebClient();
final Map prototypes = new HashMap();
final Map prototypesPerJSName = new HashMap();
final Window window = new Window(this);
final JavaScriptConfiguration jsConfig = JavaScriptConfiguration.getInstance(webClient.getBrowserVersion());
context.initStandardObjects(window);
StringPrimitivePrototypeBugFixer.installWorkaround(window);
// put custom object to be called as very last prototype to call the fallback getter (if any)
final Scriptable fallbackCaller = new ScriptableObject()
{
private static final long serialVersionUID = -7124423159070941606L;
public Object get(final String name, final Scriptable start) {
if (start instanceof ScriptableWithFallbackGetter) {
return ((ScriptableWithFallbackGetter) start).getWithFallback(name);
}
return NOT_FOUND;
}
public String getClassName() {
return "htmlUnitHelper-fallbackCaller";
}
};
ScriptableObject.getObjectPrototype(window).setPrototype(fallbackCaller);
final Iterator it = jsConfig.keySet().iterator();
while (it.hasNext()) {
final String jsClassName = (String) it.next();
final ClassConfiguration config = jsConfig.getClassConfiguration(jsClassName);
final boolean isWindow = Window.class.getName().equals(config.getLinkedClass().getName());
if (isWindow) {
configureConstantsPropertiesAndFunctions(config, window);
}
else {
final Scriptable prototype = configureClass(config, window);
if (config.isJsObject()) {
prototypes.put(config.getLinkedClass(), prototype);
// for FF, place object with prototype property in Window scope
if (!getWebClient().getBrowserVersion().isIE()) {
final Scriptable obj = (Scriptable) config.getLinkedClass().newInstance();
obj.put("prototype", obj, prototype);
obj.setPrototype(prototype);
+ obj.setParentScope(window);
ScriptableObject.defineProperty(window,
config.getClassName(), obj, ScriptableObject.DONTENUM);
}
}
prototypesPerJSName.put(config.getClassName(), prototype);
}
}
// once all prototypes have been build, it's possible to configure the chains
final Scriptable objectPrototype = ScriptableObject.getObjectPrototype(window);
for (final Iterator iter = prototypesPerJSName.entrySet().iterator(); iter.hasNext();) {
final Map.Entry entry = (Map.Entry) iter.next();
final String name = (String) entry.getKey();
final ClassConfiguration config = jsConfig.getClassConfiguration(name);
final Scriptable prototype = (Scriptable) entry.getValue();
if (!StringUtils.isEmpty(config.getExtendedClass())) {
final Scriptable parentPrototype = (Scriptable) prototypesPerJSName.get(config.getExtendedClass());
prototype.setPrototype(parentPrototype);
}
else {
prototype.setPrototype(objectPrototype);
}
}
// eval hack (cf unit tests testEvalScopeOtherWindow and testEvalScopeLocal
final Class[] evalFnTypes = {String.class};
final Member evalFn = Window.class.getMethod("custom_eval", evalFnTypes);
final FunctionObject jsCustomEval = new FunctionObject("eval", evalFn, window);
window.associateValue("custom_eval", jsCustomEval);
for (final Iterator classnames = jsConfig.keySet().iterator(); classnames.hasNext();) {
final String jsClassName = (String) classnames.next();
final ClassConfiguration config = jsConfig.getClassConfiguration(jsClassName);
final Method jsConstructor = config.getJsConstructor();
if (jsConstructor != null) {
final Scriptable prototype = (Scriptable) prototypesPerJSName.get(jsClassName);
if (prototype != null) {
final FunctionObject jsCtor = new FunctionObject(jsClassName, jsConstructor, window);
jsCtor.addAsConstructor(window, prototype);
}
}
}
window.setPrototypes(prototypes);
window.initialize(webWindow);
}
/**
* Configures the specified class for access via JavaScript.
* @param config The configuration settings for the class to be configured.
* @param window The scope within which to configure the class.
* @throws InstantiationException If the new class cannot be instantiated
* @throws IllegalAccessException If we don't have access to create the new instance.
* @throws InvocationTargetException if an exception is thrown during creation of the new object.
* @return the created prototype
*/
private Scriptable configureClass(final ClassConfiguration config, final Scriptable window)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
final Class jsHostClass = config.getLinkedClass();
final ScriptableObject prototype = (ScriptableObject) jsHostClass.newInstance();
prototype.setParentScope(window);
configureConstantsPropertiesAndFunctions(config, prototype);
return prototype;
}
/**
* Configure constants, properties and functions on the object
* @param config the configuration for the object
* @param scriptable the object to configure
*/
private void configureConstantsPropertiesAndFunctions(final ClassConfiguration config,
final ScriptableObject scriptable) {
// the constants
for (final Iterator constantsIterator = config.constants().iterator(); constantsIterator.hasNext();) {
final String constant = (String) constantsIterator.next();
final Class linkedClass = config.getLinkedClass();
try {
final Object value = linkedClass.getField(constant).get(null);
scriptable.defineProperty(constant, value, ScriptableObject.CONST);
}
catch (final Exception e) {
throw Context.reportRuntimeError("Can not get field '" + constant + "' for type: "
+ config.getClassName());
}
}
// the properties
for (final Iterator propertiesIterator = config.propertyKeys().iterator(); propertiesIterator.hasNext();) {
final String entryKey = (String) propertiesIterator.next();
final Method readMethod = config.getPropertyReadMethod(entryKey);
final Method writeMethod = config.getPropertyWriteMethod(entryKey);
scriptable.defineProperty(entryKey, null, readMethod, writeMethod, ScriptableObject.EMPTY);
}
// the functions
for (final Iterator functionsIterator = config.functionKeys().iterator(); functionsIterator.hasNext();) {
final String entryKey = (String) functionsIterator.next();
final Method method = config.getFunctionMethod(entryKey);
final FunctionObject functionObject = new FunctionObject(entryKey, method, scriptable);
scriptable.defineProperty(entryKey, functionObject, ScriptableObject.DONTENUM);
}
}
/**
* Return the log object for this class
* @return The log object
*/
protected Log getLog() {
return LogFactory.getLog(getClass());
}
/**
* Compiles the specified javascript code in the context of a given html page.
*
* @param htmlPage The page that the code will execute within
* @param sourceCode The javascript code to execute.
* @param sourceName The name that will be displayed on error conditions.
* @param startLine the line at which the script source starts
* @return The result of executing the specified code.
*/
public Script compile(final HtmlPage htmlPage,
String sourceCode,
final String sourceName,
final int startLine) {
Assert.notNull("sourceCode", sourceCode);
// Pre process the source code
sourceCode = preProcess(htmlPage, sourceCode, sourceName, null);
// PreProcess IE Conditional Compilation if needed
final BrowserVersion browserVersion = htmlPage.getWebClient().getBrowserVersion();
if (browserVersion.isIE() && browserVersion.getBrowserVersionNumeric() >= 4) {
final ScriptPreProcessor ieCCPreProcessor = new IEConditionalCompilationScriptPreProcessor();
sourceCode = ieCCPreProcessor.preProcess(htmlPage, sourceCode, sourceName, null);
}
// Remove HTML comments around the source if needed
final String sourceCodeTrimmed = sourceCode.trim();
if (sourceCodeTrimmed.startsWith("<!--")) {
sourceCode = sourceCode.replaceFirst("<!--", "// <!--");
}
// IE ignores the last line containing uncommented -->
if (getWebClient().getBrowserVersion().isIE() && sourceCodeTrimmed.endsWith("-->")) {
final int lastDoubleSlash = sourceCode.lastIndexOf("//");
final int lastNewLine = Math.max(sourceCode.lastIndexOf('\n'), sourceCode.lastIndexOf('\r'));
if (lastNewLine > lastDoubleSlash) {
sourceCode = sourceCode.substring(0, lastNewLine);
}
}
final Scriptable scope = getScope(htmlPage, null);
final String source = sourceCode;
final ContextAction action = new HtmlUnitContextAction(scope, htmlPage)
{
public Object doRun(final Context cx) {
return cx.compileString(source, sourceName, startLine, null);
}
protected String getSourceCode(final Context cx) {
return source;
}
};
return (Script) Context.call(action);
}
/**
* Execute the specified javascript code in the context of a given html page.
*
* @param htmlPage The page that the code will execute within
* @param sourceCode The javascript code to execute.
* @param sourceName The name that will be displayed on error conditions.
* @param startLine the line at which the script source starts
* @return The result of executing the specified code.
*/
public Object execute(final HtmlPage htmlPage,
final String sourceCode,
final String sourceName,
final int startLine) {
final Script script = compile(htmlPage, sourceCode, sourceName, startLine);
return execute(htmlPage, script);
}
/**
* Execute the specified javascript code in the context of a given html page.
*
* @param htmlPage The page that the code will execute within
* @param script the script to execute
* @return The result of executing the specified code.
*/
public Object execute(final HtmlPage htmlPage, final Script script) {
final Scriptable scope = getScope(htmlPage, null);
final ContextAction action = new HtmlUnitContextAction(scope, htmlPage)
{
public Object doRun(final Context cx) {
return script.exec(cx, scope);
}
protected String getSourceCode(final Context cx) {
return null;
}
};
return Context.call(action);
}
/**
* Call a JavaScript function and return the result.
* @param htmlPage The page
* @param javaScriptFunction The function to call.
* @param thisObject The this object for class method calls.
* @param args The list of arguments to pass to the function.
* @param htmlElement The html element that will act as the context.
* @return The result of the function call.
*/
public Object callFunction(
final HtmlPage htmlPage,
final Object javaScriptFunction,
final Object thisObject,
final Object [] args,
final DomNode htmlElement) {
final Scriptable scope = getScope(htmlPage, htmlElement);
final Function function = (Function) javaScriptFunction;
final ContextAction action = new HtmlUnitContextAction(scope, htmlPage)
{
public Object doRun(final Context cx) {
return callFunction(htmlPage, function, cx, scope, (Scriptable) thisObject, args);
}
protected String getSourceCode(final Context cx) {
return cx.decompileFunction(function, 2);
}
};
return Context.call(action);
}
private Scriptable getScope(final HtmlPage htmlPage, final DomNode htmlElement) {
final Scriptable scope;
if (htmlElement != null) {
scope = htmlElement.getScriptObject();
}
else {
scope = (Window) htmlPage.getEnclosingWindow().getScriptObject();
}
return scope;
}
/**
* Calls the given function taking care of synchronization issues.
* @param htmlPage the html page that caused this script to executed
* @param function the js function to execute
* @param context the context in which execution should occur
* @param scope the execution scope
* @param thisObject the 'this' object
* @param args the function's arguments
* @return the function result
*/
public Object callFunction(final HtmlPage htmlPage, final Function function, final Context context,
final Scriptable scope, final Scriptable thisObject, final Object[] args) {
synchronized (htmlPage) // 2 scripts can't be executed in parallel for one page
{
return function.call(context, scope, thisObject, args);
}
}
/**
* Indicates if JavaScript is running in current thread. <br/>
* This allows code to know if there own evaluation is has been triggered by some JS code.
* @return <code>true</code> if JavaScript is running.
*/
public boolean isScriptRunning() {
return Boolean.TRUE.equals(javaScriptRunning_.get());
}
/**
* Set the number of milliseconds a script is allowed to execute before
* being terminated. A value of 0 or less means no timeout.
*
* @param timeout the timeout value
*/
public static void setTimeout(final long timeout) {
HtmlUnitContextFactory.setTimeout(timeout);
}
/**
* Returns the number of milliseconds a script is allowed to execute before
* being terminated. A value of 0 or less means no timeout.
*
* @return the timeout value
*/
public static long getTimeout() {
return HtmlUnitContextFactory.getTimeout();
}
/**
* Facility for ContextAction usage.
* ContextAction should be preferred because according to Rhino doc it
* "guarantees proper association of Context instances with the current thread and is faster".
*/
private abstract class HtmlUnitContextAction implements ContextAction {
private final Scriptable scope_;
private final HtmlPage htmlPage_;
public HtmlUnitContextAction(final Scriptable scope, final HtmlPage htmlPage) {
scope_ = scope;
htmlPage_ = htmlPage;
}
public final Object run(final Context cx) {
final Boolean javaScriptAlreadyRunning = (Boolean) javaScriptRunning_.get();
javaScriptRunning_.set(Boolean.TRUE);
try {
cx.putThreadLocal(KEY_STARTING_SCOPE, scope_);
synchronized (htmlPage_) // 2 scripts can't be executed in parallel for one page
{
return doRun(cx);
}
}
catch (final Exception e) {
final ScriptException scriptException = new ScriptException(htmlPage_, e, getSourceCode(cx));
if (getWebClient().isThrowExceptionOnScriptError()) {
throw scriptException;
}
else {
// use a ScriptException to log it because it provides good information
// on the source code
getLog().info("Caught script exception", scriptException);
return null;
}
}
catch (final TimeoutError e) {
if (getWebClient().isThrowExceptionOnScriptError()) {
throw new RuntimeException(e);
}
else {
getLog().info("Caught script timeout error", e);
return null;
}
}
finally {
javaScriptRunning_.set(javaScriptAlreadyRunning);
}
}
protected abstract Object doRun(final Context cx);
protected abstract String getSourceCode(final Context cx);
}
/**
* Return the log object that is being used to log information about the script engine.
* @return The log
*/
public static Log getScriptEngineLog() {
return ScriptEngineLog_;
}
/**
* Pre process the specified source code in the context of the given page using the processor specified
* in the webclient. This method delegates to the pre processor handler specified in the
* <code>WebClient</code>. If no pre processor handler is defined, the original source code is returned
* unchanged.
* @param htmlPage The page
* @param sourceCode The code to process.
* @param sourceName A name for the chunk of code. This will be used in error messages.
* @param htmlElement The html element that will act as the context.
* @return The source code after being pre processed
* @see com.gargoylesoftware.htmlunit.ScriptPreProcessor
*/
public String preProcess(
final HtmlPage htmlPage, final String sourceCode, final String sourceName, final HtmlElement htmlElement) {
String newSourceCode = sourceCode;
final ScriptPreProcessor preProcessor = getWebClient().getScriptPreProcessor();
if (preProcessor != null) {
newSourceCode = preProcessor.preProcess(htmlPage, sourceCode, sourceName, htmlElement);
if (newSourceCode == null) {
newSourceCode = "";
}
}
return newSourceCode;
}
/**
* Get the cached script for the given response.
* @param webResponse the response corresponding to the script code
* @return the parsed script
*/
public Script getCachedScript(final WebResponse webResponse) {
return (Script) cachedScripts_.get(webResponse);
}
/**
* Cache a parsed script
* @param webResponse the response corresponding to the script code. A weak reference to this object
* will be used as key for the cache.
* @param script the parsed script to cache
*/
public void cacheScript(final WebResponse webResponse, final Script script) {
cachedScripts_.put(webResponse, script);
}
}
| true | true | private void init(final WebWindow webWindow, final Context context) throws Exception {
final WebClient webClient = webWindow.getWebClient();
final Map prototypes = new HashMap();
final Map prototypesPerJSName = new HashMap();
final Window window = new Window(this);
final JavaScriptConfiguration jsConfig = JavaScriptConfiguration.getInstance(webClient.getBrowserVersion());
context.initStandardObjects(window);
StringPrimitivePrototypeBugFixer.installWorkaround(window);
// put custom object to be called as very last prototype to call the fallback getter (if any)
final Scriptable fallbackCaller = new ScriptableObject()
{
private static final long serialVersionUID = -7124423159070941606L;
public Object get(final String name, final Scriptable start) {
if (start instanceof ScriptableWithFallbackGetter) {
return ((ScriptableWithFallbackGetter) start).getWithFallback(name);
}
return NOT_FOUND;
}
public String getClassName() {
return "htmlUnitHelper-fallbackCaller";
}
};
ScriptableObject.getObjectPrototype(window).setPrototype(fallbackCaller);
final Iterator it = jsConfig.keySet().iterator();
while (it.hasNext()) {
final String jsClassName = (String) it.next();
final ClassConfiguration config = jsConfig.getClassConfiguration(jsClassName);
final boolean isWindow = Window.class.getName().equals(config.getLinkedClass().getName());
if (isWindow) {
configureConstantsPropertiesAndFunctions(config, window);
}
else {
final Scriptable prototype = configureClass(config, window);
if (config.isJsObject()) {
prototypes.put(config.getLinkedClass(), prototype);
// for FF, place object with prototype property in Window scope
if (!getWebClient().getBrowserVersion().isIE()) {
final Scriptable obj = (Scriptable) config.getLinkedClass().newInstance();
obj.put("prototype", obj, prototype);
obj.setPrototype(prototype);
ScriptableObject.defineProperty(window,
config.getClassName(), obj, ScriptableObject.DONTENUM);
}
}
prototypesPerJSName.put(config.getClassName(), prototype);
}
}
// once all prototypes have been build, it's possible to configure the chains
final Scriptable objectPrototype = ScriptableObject.getObjectPrototype(window);
for (final Iterator iter = prototypesPerJSName.entrySet().iterator(); iter.hasNext();) {
final Map.Entry entry = (Map.Entry) iter.next();
final String name = (String) entry.getKey();
final ClassConfiguration config = jsConfig.getClassConfiguration(name);
final Scriptable prototype = (Scriptable) entry.getValue();
if (!StringUtils.isEmpty(config.getExtendedClass())) {
final Scriptable parentPrototype = (Scriptable) prototypesPerJSName.get(config.getExtendedClass());
prototype.setPrototype(parentPrototype);
}
else {
prototype.setPrototype(objectPrototype);
}
}
// eval hack (cf unit tests testEvalScopeOtherWindow and testEvalScopeLocal
final Class[] evalFnTypes = {String.class};
final Member evalFn = Window.class.getMethod("custom_eval", evalFnTypes);
final FunctionObject jsCustomEval = new FunctionObject("eval", evalFn, window);
window.associateValue("custom_eval", jsCustomEval);
for (final Iterator classnames = jsConfig.keySet().iterator(); classnames.hasNext();) {
final String jsClassName = (String) classnames.next();
final ClassConfiguration config = jsConfig.getClassConfiguration(jsClassName);
final Method jsConstructor = config.getJsConstructor();
if (jsConstructor != null) {
final Scriptable prototype = (Scriptable) prototypesPerJSName.get(jsClassName);
if (prototype != null) {
final FunctionObject jsCtor = new FunctionObject(jsClassName, jsConstructor, window);
jsCtor.addAsConstructor(window, prototype);
}
}
}
window.setPrototypes(prototypes);
window.initialize(webWindow);
}
| private void init(final WebWindow webWindow, final Context context) throws Exception {
final WebClient webClient = webWindow.getWebClient();
final Map prototypes = new HashMap();
final Map prototypesPerJSName = new HashMap();
final Window window = new Window(this);
final JavaScriptConfiguration jsConfig = JavaScriptConfiguration.getInstance(webClient.getBrowserVersion());
context.initStandardObjects(window);
StringPrimitivePrototypeBugFixer.installWorkaround(window);
// put custom object to be called as very last prototype to call the fallback getter (if any)
final Scriptable fallbackCaller = new ScriptableObject()
{
private static final long serialVersionUID = -7124423159070941606L;
public Object get(final String name, final Scriptable start) {
if (start instanceof ScriptableWithFallbackGetter) {
return ((ScriptableWithFallbackGetter) start).getWithFallback(name);
}
return NOT_FOUND;
}
public String getClassName() {
return "htmlUnitHelper-fallbackCaller";
}
};
ScriptableObject.getObjectPrototype(window).setPrototype(fallbackCaller);
final Iterator it = jsConfig.keySet().iterator();
while (it.hasNext()) {
final String jsClassName = (String) it.next();
final ClassConfiguration config = jsConfig.getClassConfiguration(jsClassName);
final boolean isWindow = Window.class.getName().equals(config.getLinkedClass().getName());
if (isWindow) {
configureConstantsPropertiesAndFunctions(config, window);
}
else {
final Scriptable prototype = configureClass(config, window);
if (config.isJsObject()) {
prototypes.put(config.getLinkedClass(), prototype);
// for FF, place object with prototype property in Window scope
if (!getWebClient().getBrowserVersion().isIE()) {
final Scriptable obj = (Scriptable) config.getLinkedClass().newInstance();
obj.put("prototype", obj, prototype);
obj.setPrototype(prototype);
obj.setParentScope(window);
ScriptableObject.defineProperty(window,
config.getClassName(), obj, ScriptableObject.DONTENUM);
}
}
prototypesPerJSName.put(config.getClassName(), prototype);
}
}
// once all prototypes have been build, it's possible to configure the chains
final Scriptable objectPrototype = ScriptableObject.getObjectPrototype(window);
for (final Iterator iter = prototypesPerJSName.entrySet().iterator(); iter.hasNext();) {
final Map.Entry entry = (Map.Entry) iter.next();
final String name = (String) entry.getKey();
final ClassConfiguration config = jsConfig.getClassConfiguration(name);
final Scriptable prototype = (Scriptable) entry.getValue();
if (!StringUtils.isEmpty(config.getExtendedClass())) {
final Scriptable parentPrototype = (Scriptable) prototypesPerJSName.get(config.getExtendedClass());
prototype.setPrototype(parentPrototype);
}
else {
prototype.setPrototype(objectPrototype);
}
}
// eval hack (cf unit tests testEvalScopeOtherWindow and testEvalScopeLocal
final Class[] evalFnTypes = {String.class};
final Member evalFn = Window.class.getMethod("custom_eval", evalFnTypes);
final FunctionObject jsCustomEval = new FunctionObject("eval", evalFn, window);
window.associateValue("custom_eval", jsCustomEval);
for (final Iterator classnames = jsConfig.keySet().iterator(); classnames.hasNext();) {
final String jsClassName = (String) classnames.next();
final ClassConfiguration config = jsConfig.getClassConfiguration(jsClassName);
final Method jsConstructor = config.getJsConstructor();
if (jsConstructor != null) {
final Scriptable prototype = (Scriptable) prototypesPerJSName.get(jsClassName);
if (prototype != null) {
final FunctionObject jsCtor = new FunctionObject(jsClassName, jsConstructor, window);
jsCtor.addAsConstructor(window, prototype);
}
}
}
window.setPrototypes(prototypes);
window.initialize(webWindow);
}
|
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/integration/osgi/TestPaymentOSGIWithTestPaymentBundle.java b/beatrix/src/test/java/com/ning/billing/beatrix/integration/osgi/TestPaymentOSGIWithTestPaymentBundle.java
index 1fb576eae..7f466f1ee 100644
--- a/beatrix/src/test/java/com/ning/billing/beatrix/integration/osgi/TestPaymentOSGIWithTestPaymentBundle.java
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/integration/osgi/TestPaymentOSGIWithTestPaymentBundle.java
@@ -1,186 +1,186 @@
/*
* Copyright 2010-2013 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.beatrix.integration.osgi;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import javax.inject.Inject;
import org.joda.time.LocalDate;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.ning.billing.account.api.Account;
import com.ning.billing.account.api.AccountData;
import com.ning.billing.api.TestApiListener.NextEvent;
import com.ning.billing.beatrix.integration.BeatrixIntegrationModule;
import com.ning.billing.beatrix.osgi.SetupBundleWithAssertion;
import com.ning.billing.beatrix.util.InvoiceChecker.ExpectedInvoiceItemCheck;
import com.ning.billing.beatrix.util.PaymentChecker.ExpectedPaymentCheck;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceItemType;
import com.ning.billing.osgi.api.OSGIServiceRegistration;
import com.ning.billing.payment.api.PaymentStatus;
import com.ning.billing.payment.plugin.api.PaymentPluginApi;
import com.ning.billing.payment.plugin.api.PaymentPluginApiException;
import com.ning.billing.payment.plugin.api.PaymentPluginApiWithTestControl;
public class TestPaymentOSGIWithTestPaymentBundle extends TestOSGIBase {
private final String BUNDLE_TEST_RESOURCE = "killbill-osgi-bundles-test-payment";
@Inject
private OSGIServiceRegistration<PaymentPluginApi> paymentPluginApiOSGIServiceRegistration;
@BeforeClass(groups = "slow")
public void beforeClass() throws Exception {
super.beforeClass();
// This is extracted from surefire system configuration-- needs to be added explicitly in IntelliJ for correct running
final String killbillVersion = System.getProperty("killbill.version");
SetupBundleWithAssertion setupTest = new SetupBundleWithAssertion(BUNDLE_TEST_RESOURCE, osgiConfig, killbillVersion);
setupTest.setupJavaBundle();
}
@BeforeMethod(groups = "slow")
public void beforeMethod() throws Exception {
super.beforeMethod();
getTestPluginPaymentApi().resetToNormalbehavior();
}
@Test(groups = "slow")
public void testBasicProcessPaymentOK() throws Exception {
final PaymentPluginApiWithTestControl paymentPluginApi = getTestPluginPaymentApi();
paymentPluginApi.processPayment(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), BigDecimal.TEN, Currency.USD, callContext);
}
@Test(groups = "slow")
public void testBasicProcessPaymentWithPaymentPluginApiException() throws Exception {
boolean gotException = false;
try {
final PaymentPluginApiWithTestControl paymentPluginApi = getTestPluginPaymentApi();
final PaymentPluginApiException e = new PaymentPluginApiException("test-error", "foo");
paymentPluginApi.setPaymentPluginApiExceptionOnNextCalls(e);
paymentPluginApi.processPayment(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), BigDecimal.TEN, Currency.USD, callContext);
Assert.fail("Expected to fail with " + e.toString());
} catch (PaymentPluginApiException e) {
gotException = true;
}
Assert.assertTrue(gotException);
}
@Test(groups = "slow")
public void testBasicProcessPaymentWithRuntimeException() throws Exception {
boolean gotException = false;
try {
final PaymentPluginApiWithTestControl paymentPluginApi = getTestPluginPaymentApi();
final RuntimeException e = new RuntimeException("test-error");
paymentPluginApi.setPaymentRuntimeExceptionOnNextCalls(e);
paymentPluginApi.processPayment(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), BigDecimal.TEN, Currency.USD, callContext);
Assert.fail("Expected to fail with " + e.toString());
} catch (RuntimeException e) {
gotException = true;
}
Assert.assertTrue(gotException);
}
@Test(groups = "slow")
public void testIntegrationOK() throws Exception {
setupIntegration(null, null);
}
@Test(groups = "slow")
public void testIntegrationWithPaymentPluginApiException() throws Exception {
final PaymentPluginApiException e = new PaymentPluginApiException("test-error", "foo");
setupIntegration(e, null);
}
@Test(groups = "slow")
public void testIntegrationWithRuntimeException() throws Exception {
final RuntimeException e = new RuntimeException("test-error");
setupIntegration(null, e);
}
private void setupIntegration(final PaymentPluginApiException expectedException, final RuntimeException expectedRuntimeException) throws Exception {
final PaymentPluginApiWithTestControl paymentPluginApi = getTestPluginPaymentApi();
final AccountData accountData = getAccountData(1);
final Account account = createAccountWithOsgiPaymentMethod(accountData);
// We take april as it has 30 days (easier to play with BCD)
// Set clock to the initial start date - we implicitly assume here that the account timezone is UTC
clock.setDay(new LocalDate(2012, 4, 1));
final SubscriptionBundle bundle = entitlementUserApi.createBundleForAccount(account.getId(), "whatever", callContext);
//
// CREATE SUBSCRIPTION AND EXPECT BOTH EVENTS: NextEvent.CREATE NextEvent.INVOICE
//
final Subscription bpSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.INVOICE);
//
// ADD ADD_ON ON THE SAME DAY TO TRIGGER PAYMENT
//
final List<NextEvent> expectedEvents = new LinkedList<NextEvent>();
expectedEvents.add(NextEvent.CREATE);
expectedEvents.add(NextEvent.INVOICE);
if (expectedException == null && expectedRuntimeException == null) {
expectedEvents.add(NextEvent.PAYMENT);
} else if (expectedException != null) {
paymentPluginApi.setPaymentPluginApiExceptionOnNextCalls(expectedException);
} else if (expectedRuntimeException != null) {
paymentPluginApi.setPaymentRuntimeExceptionOnNextCalls(expectedRuntimeException);
}
createSubscriptionAndCheckForCompletion(bundle.getId(), "Telescopic-Scope", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, expectedEvents.toArray(new NextEvent[expectedEvents.size()]));
Invoice invoice = invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 4, 1), new LocalDate(2012, 5, 1), InvoiceItemType.RECURRING, new BigDecimal("399.95")));
if (expectedException == null && expectedRuntimeException == null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.SUCCESS, invoice.getId(), Currency.USD));
} else if (expectedException != null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.PLUGIN_FAILURE, invoice.getId(), Currency.USD));
} else if (expectedRuntimeException != null) {
- paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.UNKNOWN, invoice.getId(), Currency.USD));
+ paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.PLUGIN_FAILURE, invoice.getId(), Currency.USD));
}
}
private PaymentPluginApiWithTestControl getTestPluginPaymentApi() {
PaymentPluginApiWithTestControl result = (PaymentPluginApiWithTestControl) paymentPluginApiOSGIServiceRegistration.getServiceForName(BeatrixIntegrationModule.OSGI_PLUGIN_NAME);
Assert.assertNotNull(result);
return result;
}
}
| true | true | private void setupIntegration(final PaymentPluginApiException expectedException, final RuntimeException expectedRuntimeException) throws Exception {
final PaymentPluginApiWithTestControl paymentPluginApi = getTestPluginPaymentApi();
final AccountData accountData = getAccountData(1);
final Account account = createAccountWithOsgiPaymentMethod(accountData);
// We take april as it has 30 days (easier to play with BCD)
// Set clock to the initial start date - we implicitly assume here that the account timezone is UTC
clock.setDay(new LocalDate(2012, 4, 1));
final SubscriptionBundle bundle = entitlementUserApi.createBundleForAccount(account.getId(), "whatever", callContext);
//
// CREATE SUBSCRIPTION AND EXPECT BOTH EVENTS: NextEvent.CREATE NextEvent.INVOICE
//
final Subscription bpSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.INVOICE);
//
// ADD ADD_ON ON THE SAME DAY TO TRIGGER PAYMENT
//
final List<NextEvent> expectedEvents = new LinkedList<NextEvent>();
expectedEvents.add(NextEvent.CREATE);
expectedEvents.add(NextEvent.INVOICE);
if (expectedException == null && expectedRuntimeException == null) {
expectedEvents.add(NextEvent.PAYMENT);
} else if (expectedException != null) {
paymentPluginApi.setPaymentPluginApiExceptionOnNextCalls(expectedException);
} else if (expectedRuntimeException != null) {
paymentPluginApi.setPaymentRuntimeExceptionOnNextCalls(expectedRuntimeException);
}
createSubscriptionAndCheckForCompletion(bundle.getId(), "Telescopic-Scope", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, expectedEvents.toArray(new NextEvent[expectedEvents.size()]));
Invoice invoice = invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 4, 1), new LocalDate(2012, 5, 1), InvoiceItemType.RECURRING, new BigDecimal("399.95")));
if (expectedException == null && expectedRuntimeException == null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.SUCCESS, invoice.getId(), Currency.USD));
} else if (expectedException != null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.PLUGIN_FAILURE, invoice.getId(), Currency.USD));
} else if (expectedRuntimeException != null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.UNKNOWN, invoice.getId(), Currency.USD));
}
}
| private void setupIntegration(final PaymentPluginApiException expectedException, final RuntimeException expectedRuntimeException) throws Exception {
final PaymentPluginApiWithTestControl paymentPluginApi = getTestPluginPaymentApi();
final AccountData accountData = getAccountData(1);
final Account account = createAccountWithOsgiPaymentMethod(accountData);
// We take april as it has 30 days (easier to play with BCD)
// Set clock to the initial start date - we implicitly assume here that the account timezone is UTC
clock.setDay(new LocalDate(2012, 4, 1));
final SubscriptionBundle bundle = entitlementUserApi.createBundleForAccount(account.getId(), "whatever", callContext);
//
// CREATE SUBSCRIPTION AND EXPECT BOTH EVENTS: NextEvent.CREATE NextEvent.INVOICE
//
final Subscription bpSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.INVOICE);
//
// ADD ADD_ON ON THE SAME DAY TO TRIGGER PAYMENT
//
final List<NextEvent> expectedEvents = new LinkedList<NextEvent>();
expectedEvents.add(NextEvent.CREATE);
expectedEvents.add(NextEvent.INVOICE);
if (expectedException == null && expectedRuntimeException == null) {
expectedEvents.add(NextEvent.PAYMENT);
} else if (expectedException != null) {
paymentPluginApi.setPaymentPluginApiExceptionOnNextCalls(expectedException);
} else if (expectedRuntimeException != null) {
paymentPluginApi.setPaymentRuntimeExceptionOnNextCalls(expectedRuntimeException);
}
createSubscriptionAndCheckForCompletion(bundle.getId(), "Telescopic-Scope", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, expectedEvents.toArray(new NextEvent[expectedEvents.size()]));
Invoice invoice = invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 4, 1), new LocalDate(2012, 5, 1), InvoiceItemType.RECURRING, new BigDecimal("399.95")));
if (expectedException == null && expectedRuntimeException == null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.SUCCESS, invoice.getId(), Currency.USD));
} else if (expectedException != null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.PLUGIN_FAILURE, invoice.getId(), Currency.USD));
} else if (expectedRuntimeException != null) {
paymentChecker.checkPayment(account.getId(), 1, callContext, new ExpectedPaymentCheck(new LocalDate(2012, 4, 1), new BigDecimal("399.95"), PaymentStatus.PLUGIN_FAILURE, invoice.getId(), Currency.USD));
}
}
|
diff --git a/src/net/enkun/javatter/history/HistoryObjectFactory.java b/src/net/enkun/javatter/history/HistoryObjectFactory.java
index 450d126..21edd71 100644
--- a/src/net/enkun/javatter/history/HistoryObjectFactory.java
+++ b/src/net/enkun/javatter/history/HistoryObjectFactory.java
@@ -1,186 +1,186 @@
package net.enkun.javatter.history;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import com.orekyuu.javatter.util.BackGroundColor;
import com.orekyuu.javatter.util.IconCache;
import twitter4j.Status;
import twitter4j.User;
public class HistoryObjectFactory {
/*
* retweet, favorite, unfavorite => user, status
*
* follow => user
*
* ほいさほいさ
*/
private User user;
private Status status;
private EventType type;
public enum EventType {
Retweet,
Favorite,
Unfavorite,
Follow
}
public HistoryObjectFactory(User user, Status status, EventType type) {
this.user = user;
this.status = status;
this.type = type;
}
public HistoryObjectFactory(User user) {
this.user = user;
this.status = null;
}
public JPanel createHistoryObject(HistoryViewObserver view) {
JPanel base = new JPanel();
base.setBackground(BackGroundColor.color);
base.setAlignmentX(0.0F);
base.setAlignmentY(0.0F);
base.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
base.setLayout(new BorderLayout());
base.add(createImage(), "Before");
base.add(createText(view), "Center");
return base;
}
private JPanel createImage() {
IconCache cache = IconCache.getInstance();
JPanel panel = new JPanel();
panel.setBackground(BackGroundColor.color);
panel.setLayout(new BoxLayout(panel, 3));
try {
URL url = new URL(this.user.getProfileImageURL());
panel.add(new JLabel(cache.getIcon(url)));
} catch (MalformedURLException e) {
e.printStackTrace();
}
panel.setAlignmentX(0.0F);
panel.setAlignmentY(0.0F);
return panel;
}
private JPanel createText(HistoryViewObserver view) {
JPanel textPanel = new JPanel();
textPanel.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
textPanel.setLayout(new BoxLayout(textPanel, 3));
JLabel userName = new JLabel();
userName.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
Font font = new Font("MS ゴシック", 1, 13);
userName.setFont(font);
userName.setText("@" + user.getScreenName() + "に" + type + "されました");
textPanel.add(userName);
- String tweet = this.status.getText();
+ String tweet = this.status == null ? "" : this.status.getText();
JTextPane textArea = new JTextPane();
textArea.setContentType("text/html");
textArea.setEditable(false);
textArea.setText(createHTMLText(tweet));
textArea.setBackground(BackGroundColor.color);
textArea.setAlignmentX(0.0F);
textArea.setAlignmentY(0.0F);
textArea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
Desktop dp = Desktop.getDesktop();
try {
dp.browse(url.toURI());
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
textPanel.add(textArea);
textPanel.add(createButtons(view));
textPanel.setAlignmentX(0.0F);
textPanel.setAlignmentY(0.0F);
textPanel.setBackground(BackGroundColor.color);
return textPanel;
}
private String createHTMLText(String tweet) {
final String urlRegex = "(?<![\\w])https?://(([\\w]|[^ -~])+(([\\w\\-]|[^ -~])+([\\w]|[^ -~]))?\\.)+(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)(?![\\w])(/([\\w\\.\\-\\$&%/:=#~!]*\\??[\\w\\.\\-\\$&%/:=#~!]*[\\w\\-\\$/#])?)?";
Pattern p = Pattern.compile(urlRegex);
Matcher m = p.matcher(urlRegex);
String t = tweet;
while (m.find()) {
String s = m.group();
t = t.replaceFirst(s, "<a href='" + s + "'>" + s + "</a>");
}
t = t.replaceAll("\n", "<br>");
return t;
}
private JPanel createButtons(HistoryViewObserver view) {
//ButtonClickEventListener model = new ButtonClickEventListener(this.user, this.status, view);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, 2));
/*
JButton rep = new JButton("リプ");
rep.addActionListener(model);
model.setHogeButton(rep);
panel.add(rep);
*/
/*
JToggleButton rt = new JToggleButton("RT");
rt.addActionListener(model);
model.setRtButton(rt);
rt.setEnabled(!s.isRetweetedByMe());
panel.add(rt);
JToggleButton fav = new JToggleButton("☆");
fav.addActionListener(model);
fav.setSelected(s.isFavorited());
model.setFavButton(fav);
panel.add(fav);
*/
panel.setAlignmentX(0.0F);
panel.setAlignmentY(0.0F);
return panel;
}
}
| true | true | private JPanel createText(HistoryViewObserver view) {
JPanel textPanel = new JPanel();
textPanel.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
textPanel.setLayout(new BoxLayout(textPanel, 3));
JLabel userName = new JLabel();
userName.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
Font font = new Font("MS ゴシック", 1, 13);
userName.setFont(font);
userName.setText("@" + user.getScreenName() + "に" + type + "されました");
textPanel.add(userName);
String tweet = this.status.getText();
JTextPane textArea = new JTextPane();
textArea.setContentType("text/html");
textArea.setEditable(false);
textArea.setText(createHTMLText(tweet));
textArea.setBackground(BackGroundColor.color);
textArea.setAlignmentX(0.0F);
textArea.setAlignmentY(0.0F);
textArea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
Desktop dp = Desktop.getDesktop();
try {
dp.browse(url.toURI());
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
textPanel.add(textArea);
textPanel.add(createButtons(view));
textPanel.setAlignmentX(0.0F);
textPanel.setAlignmentY(0.0F);
textPanel.setBackground(BackGroundColor.color);
return textPanel;
}
| private JPanel createText(HistoryViewObserver view) {
JPanel textPanel = new JPanel();
textPanel.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
textPanel.setLayout(new BoxLayout(textPanel, 3));
JLabel userName = new JLabel();
userName.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
Font font = new Font("MS ゴシック", 1, 13);
userName.setFont(font);
userName.setText("@" + user.getScreenName() + "に" + type + "されました");
textPanel.add(userName);
String tweet = this.status == null ? "" : this.status.getText();
JTextPane textArea = new JTextPane();
textArea.setContentType("text/html");
textArea.setEditable(false);
textArea.setText(createHTMLText(tweet));
textArea.setBackground(BackGroundColor.color);
textArea.setAlignmentX(0.0F);
textArea.setAlignmentY(0.0F);
textArea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
Desktop dp = Desktop.getDesktop();
try {
dp.browse(url.toURI());
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
textPanel.add(textArea);
textPanel.add(createButtons(view));
textPanel.setAlignmentX(0.0F);
textPanel.setAlignmentY(0.0F);
textPanel.setBackground(BackGroundColor.color);
return textPanel;
}
|
diff --git a/src/com/android/thememanager/ThemeZipUtils.java b/src/com/android/thememanager/ThemeZipUtils.java
index 8311070..681c5fd 100644
--- a/src/com/android/thememanager/ThemeZipUtils.java
+++ b/src/com/android/thememanager/ThemeZipUtils.java
@@ -1,280 +1,288 @@
/*
* Copyright (C) 2012 The ChameleonOS Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.thememanager;
import android.content.Context;
import android.content.res.IThemeManagerService;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.ServiceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.zip.*;
public class ThemeZipUtils {
private static final String TAG = "ThemeZipUtils";
/**
* Simple copy routine given an input stream and an output stream
*/
private static void copyInputStream(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
out.close();
}
public static void extractTheme(String src, String dst, Context context) throws IOException {
ZipInputStream zip = new ZipInputStream(new BufferedInputStream(
new FileInputStream(src)));
ZipEntry ze = null;
while ((ze = zip.getNextEntry()) != null) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory /data/system/theme/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
}
Log.d(TAG, "Creating file " + ze.getName());
if (ze.getName().contains("bootanimation.zip")) {
File f = new File(dst + "/" + ze.getName());
if (f.exists())
f.delete();
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getRealMetrics(dm);
extractBootAnimation(zip, dst + "/" + ze.getName(),
new Point(dm.widthPixels, dm.heightPixels));
} else
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
zip.closeEntry();
}
zip.close();
}
public static void extractThemeElement(String src, String dst, int elementType, Context context) throws IOException {
ZipInputStream zip = new ZipInputStream(new BufferedInputStream(
new FileInputStream(src)));
ZipEntry ze = null;
boolean done = false;
while ((ze = zip.getNextEntry()) != null && !done) {
switch (elementType) {
case Theme.THEME_ELEMENT_TYPE_ICONS:
if (ze.getName().equals("icons")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_WALLPAPER:
if (ze.getName().contains("wallpaper")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory " + dst + "/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
case Theme.THEME_ELEMENT_TYPE_SYSTEMUI:
if (ze.getName().equals("com.android.systemui")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_FRAMEWORK:
if (ze.getName().equals("framework-res")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_LOCKSCREEN:
if (ze.getName().equals("lockscreen")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_RINGTONES:
if (ze.getName().contains("ringtones")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory /data/system/theme/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
case Theme.THEME_ELEMENT_TYPE_BOOTANIMATION:
if (ze.getName().contains("boots")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory /data/system/theme/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
File f = new File(dst + "/" + ze.getName());
if (f.exists())
f.delete();
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getRealMetrics(dm);
extractBootAnimation(zip, dst + "/" + ze.getName(),
new Point(dm.widthPixels, dm.heightPixels));
//copyInputStream(zip,
// new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
+ case Theme.THEME_ELEMENT_TYPE_MMS:
+ if (ze.getName().equals("com.android.mms")) {
+ copyInputStream(zip,
+ new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
+ (new File(dst + "/" + ze.getName())).setReadable(true, false);
+ done = true;
+ }
+ break;
}
zip.closeEntry();
}
zip.close();
}
public static void extractBootAnimation(InputStream input, String dst, Point screenDims)
throws IOException {
OutputStream os = new FileOutputStream(dst);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os));
ZipInputStream bootAni = new ZipInputStream(input);
ZipEntry ze = null;
zos.setMethod(ZipOutputStream.STORED);
byte[] bytes = new byte[1024];
int len = 0;
CRC32 crc32 = new CRC32();
int scaledWidth = 0;
int scaledHeight = 0;
if (screenDims.x > screenDims.y) {
scaledWidth = screenDims.y;
scaledHeight = screenDims.x;
} else {
scaledWidth = screenDims.x;
scaledHeight = screenDims.y;
}
while ((ze = bootAni.getNextEntry()) != null) {
crc32.reset();
ZipEntry entry = new ZipEntry(ze.getName());
entry.setMethod(ZipEntry.STORED);
entry.setCrc(ze.getCrc());
entry.setSize(ze.getSize());
entry.setCompressedSize(ze.getSize());
if (!ze.getName().equals("desc.txt")) {
if (ze.getName().toLowerCase().endsWith(".png") || ze.getName().toLowerCase().endsWith(".jpg")) {
Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(bootAni, null, null),
scaledWidth, scaledHeight, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(ze.getName().toLowerCase().endsWith("png") ?
Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 80, bos);
byte[] bitmapdata = bos.toByteArray();
crc32.reset();
crc32.update(bitmapdata);
entry.setSize(bitmapdata.length);
entry.setCompressedSize(bitmapdata.length);
entry.setCrc(crc32.getValue());
zos.putNextEntry(entry);
zos.write(bitmapdata);
bos.close();
bmp.recycle();
}
} else {
String line = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(bootAni));
String[] info = reader.readLine().split(" ");
int width = Integer.parseInt(info[0]);
int height = Integer.parseInt(info[1]);
if (width == height)
scaledHeight = scaledWidth;
crc32.reset();
int size = 0;
ByteBuffer buffer = ByteBuffer.wrap(bytes);
line = String.format("%d %d %s\n", scaledWidth, scaledHeight, info[2]);
buffer.put(line.getBytes());
size += line.getBytes().length;
crc32.update(line.getBytes());
while ((line = reader.readLine()) != null) {
line = String.format("%s\n", line);
buffer.put(line.getBytes());
size += line.getBytes().length;
crc32.update(line.getBytes());
}
entry.setCrc(crc32.getValue());
entry.setSize(size);
entry.setCompressedSize(size);
zos.putNextEntry(entry);
zos.write(buffer.array(), 0, size);
}
zos.closeEntry();
}
zos.close();
}
}
| true | true | public static void extractThemeElement(String src, String dst, int elementType, Context context) throws IOException {
ZipInputStream zip = new ZipInputStream(new BufferedInputStream(
new FileInputStream(src)));
ZipEntry ze = null;
boolean done = false;
while ((ze = zip.getNextEntry()) != null && !done) {
switch (elementType) {
case Theme.THEME_ELEMENT_TYPE_ICONS:
if (ze.getName().equals("icons")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_WALLPAPER:
if (ze.getName().contains("wallpaper")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory " + dst + "/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
case Theme.THEME_ELEMENT_TYPE_SYSTEMUI:
if (ze.getName().equals("com.android.systemui")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_FRAMEWORK:
if (ze.getName().equals("framework-res")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_LOCKSCREEN:
if (ze.getName().equals("lockscreen")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_RINGTONES:
if (ze.getName().contains("ringtones")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory /data/system/theme/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
case Theme.THEME_ELEMENT_TYPE_BOOTANIMATION:
if (ze.getName().contains("boots")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory /data/system/theme/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
File f = new File(dst + "/" + ze.getName());
if (f.exists())
f.delete();
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getRealMetrics(dm);
extractBootAnimation(zip, dst + "/" + ze.getName(),
new Point(dm.widthPixels, dm.heightPixels));
//copyInputStream(zip,
// new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
}
zip.closeEntry();
}
zip.close();
}
| public static void extractThemeElement(String src, String dst, int elementType, Context context) throws IOException {
ZipInputStream zip = new ZipInputStream(new BufferedInputStream(
new FileInputStream(src)));
ZipEntry ze = null;
boolean done = false;
while ((ze = zip.getNextEntry()) != null && !done) {
switch (elementType) {
case Theme.THEME_ELEMENT_TYPE_ICONS:
if (ze.getName().equals("icons")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_WALLPAPER:
if (ze.getName().contains("wallpaper")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory " + dst + "/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
case Theme.THEME_ELEMENT_TYPE_SYSTEMUI:
if (ze.getName().equals("com.android.systemui")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_FRAMEWORK:
if (ze.getName().equals("framework-res")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_LOCKSCREEN:
if (ze.getName().equals("lockscreen")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
case Theme.THEME_ELEMENT_TYPE_RINGTONES:
if (ze.getName().contains("ringtones")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory /data/system/theme/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
case Theme.THEME_ELEMENT_TYPE_BOOTANIMATION:
if (ze.getName().contains("boots")) {
if (ze.isDirectory()) {
// Assume directories are stored parents first then children
Log.d(TAG, "Creating directory /data/system/theme/" + ze.getName());
File dir = new File(dst + "/" + ze.getName());
dir.mkdir();
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);
zip.closeEntry();
continue;
} else {
File f = new File(dst + "/" + ze.getName());
if (f.exists())
f.delete();
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getRealMetrics(dm);
extractBootAnimation(zip, dst + "/" + ze.getName(),
new Point(dm.widthPixels, dm.heightPixels));
//copyInputStream(zip,
// new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
}
}
break;
case Theme.THEME_ELEMENT_TYPE_MMS:
if (ze.getName().equals("com.android.mms")) {
copyInputStream(zip,
new BufferedOutputStream(new FileOutputStream(dst + "/" + ze.getName())));
(new File(dst + "/" + ze.getName())).setReadable(true, false);
done = true;
}
break;
}
zip.closeEntry();
}
zip.close();
}
|
diff --git a/netbeans-suite/jcae-netbeans/src/org/jcae/netbeans/mesh/DecimateAction.java b/netbeans-suite/jcae-netbeans/src/org/jcae/netbeans/mesh/DecimateAction.java
index 5d9c5abf..bb452138 100644
--- a/netbeans-suite/jcae-netbeans/src/org/jcae/netbeans/mesh/DecimateAction.java
+++ b/netbeans-suite/jcae-netbeans/src/org/jcae/netbeans/mesh/DecimateAction.java
@@ -1,122 +1,121 @@
/*
* Project Info: http://jcae.sourceforge.net
*
* This program 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 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser 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.
*
* (C) Copyright 2006, by EADS CRC
*/
package org.jcae.netbeans.mesh;
import java.io.File;
import org.jcae.netbeans.ProcessExecutor;
import org.jcae.netbeans.Utilities;
import org.openide.filesystems.FileUtil;
import org.openide.nodes.Node;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CookieAction;
public final class DecimateAction extends CookieAction
{
protected void performAction(Node[] activatedNodes)
{
DecimateParameter bean=new DecimateParameter();
if(Utilities.showEditBeanDialog(bean))
{
MeshDataObject c = (MeshDataObject)
activatedNodes[0].getCookie(MeshDataObject.class);
String reference = FileUtil.toFile(
c.getPrimaryFile().getParent()).getPath();
String xmlDir=Utilities.absoluteFileName(
c.getMesh().getMeshFile(), reference);
- File brepFile=new File(Utilities.absoluteFileName(
- c.getMesh().getGeometryFile(), reference));
+ String brepFile=Utilities.absoluteFileName(
+ c.getMesh().getGeometryFile(), reference);
String className="org.jcae.mesh.amibe.algos3d.DecimateHalfEdge";
String[] cmdLinePre=Settings.getDefault().getCommandLineAlgo();
- String[] cmdLine=new String[cmdLinePre.length+7];
+ String[] cmdLine=new String[cmdLinePre.length+6];
System.arraycopy(cmdLinePre, 0, cmdLine, 0, cmdLinePre.length);
int i=cmdLinePre.length;
cmdLine[i++]=className;
cmdLine[i++]=xmlDir;
- cmdLine[i++]="jcae3d";
if(bean.isUseTolerance())
{
cmdLine[i++]="-t";
cmdLine[i++]=Double.toString(bean.getTolerance());
}
else
{
cmdLine[i++]="-n";
cmdLine[i++]=Integer.toString(bean.getTriangle());
}
- cmdLine[i++]=brepFile.getParent();
- cmdLine[i++]=brepFile.getName();
+ cmdLine[i++]=brepFile;
+ cmdLine[i++]=xmlDir;
final MeshNode m =
(MeshNode) activatedNodes[0].getCookie(MeshNode.class);
// level_max tri_max outDir brep soupDir
ProcessExecutor pe=new ProcessExecutor(cmdLine)
{
public void run()
{
super.run();
m.refreshGroups();
}
};
pe.setName("Decimate");
pe.start();
}
}
protected int mode()
{
return CookieAction.MODE_EXACTLY_ONE;
}
public String getName()
{
return NbBundle.getMessage(DecimateAction.class, "CTL_DecimateAction");
}
protected Class[] cookieClasses()
{
return new Class[] {
MeshDataObject.class
};
}
public HelpCtx getHelpCtx()
{
return HelpCtx.DEFAULT_HELP;
}
protected boolean asynchronous()
{
return false;
}
}
| false | true | protected void performAction(Node[] activatedNodes)
{
DecimateParameter bean=new DecimateParameter();
if(Utilities.showEditBeanDialog(bean))
{
MeshDataObject c = (MeshDataObject)
activatedNodes[0].getCookie(MeshDataObject.class);
String reference = FileUtil.toFile(
c.getPrimaryFile().getParent()).getPath();
String xmlDir=Utilities.absoluteFileName(
c.getMesh().getMeshFile(), reference);
File brepFile=new File(Utilities.absoluteFileName(
c.getMesh().getGeometryFile(), reference));
String className="org.jcae.mesh.amibe.algos3d.DecimateHalfEdge";
String[] cmdLinePre=Settings.getDefault().getCommandLineAlgo();
String[] cmdLine=new String[cmdLinePre.length+7];
System.arraycopy(cmdLinePre, 0, cmdLine, 0, cmdLinePre.length);
int i=cmdLinePre.length;
cmdLine[i++]=className;
cmdLine[i++]=xmlDir;
cmdLine[i++]="jcae3d";
if(bean.isUseTolerance())
{
cmdLine[i++]="-t";
cmdLine[i++]=Double.toString(bean.getTolerance());
}
else
{
cmdLine[i++]="-n";
cmdLine[i++]=Integer.toString(bean.getTriangle());
}
cmdLine[i++]=brepFile.getParent();
cmdLine[i++]=brepFile.getName();
final MeshNode m =
(MeshNode) activatedNodes[0].getCookie(MeshNode.class);
// level_max tri_max outDir brep soupDir
ProcessExecutor pe=new ProcessExecutor(cmdLine)
{
public void run()
{
super.run();
m.refreshGroups();
}
};
pe.setName("Decimate");
pe.start();
}
}
| protected void performAction(Node[] activatedNodes)
{
DecimateParameter bean=new DecimateParameter();
if(Utilities.showEditBeanDialog(bean))
{
MeshDataObject c = (MeshDataObject)
activatedNodes[0].getCookie(MeshDataObject.class);
String reference = FileUtil.toFile(
c.getPrimaryFile().getParent()).getPath();
String xmlDir=Utilities.absoluteFileName(
c.getMesh().getMeshFile(), reference);
String brepFile=Utilities.absoluteFileName(
c.getMesh().getGeometryFile(), reference);
String className="org.jcae.mesh.amibe.algos3d.DecimateHalfEdge";
String[] cmdLinePre=Settings.getDefault().getCommandLineAlgo();
String[] cmdLine=new String[cmdLinePre.length+6];
System.arraycopy(cmdLinePre, 0, cmdLine, 0, cmdLinePre.length);
int i=cmdLinePre.length;
cmdLine[i++]=className;
cmdLine[i++]=xmlDir;
if(bean.isUseTolerance())
{
cmdLine[i++]="-t";
cmdLine[i++]=Double.toString(bean.getTolerance());
}
else
{
cmdLine[i++]="-n";
cmdLine[i++]=Integer.toString(bean.getTriangle());
}
cmdLine[i++]=brepFile;
cmdLine[i++]=xmlDir;
final MeshNode m =
(MeshNode) activatedNodes[0].getCookie(MeshNode.class);
// level_max tri_max outDir brep soupDir
ProcessExecutor pe=new ProcessExecutor(cmdLine)
{
public void run()
{
super.run();
m.refreshGroups();
}
};
pe.setName("Decimate");
pe.start();
}
}
|
diff --git a/src/html2windows/css/level1/SimpleSelector.java b/src/html2windows/css/level1/SimpleSelector.java
index ee3e37c..59bb170 100644
--- a/src/html2windows/css/level1/SimpleSelector.java
+++ b/src/html2windows/css/level1/SimpleSelector.java
@@ -1,17 +1,17 @@
package html2windows.css.level1;
import html2windows.dom.Element;
import html2windows.dom.Document;
abstract class SimpleSelector extends SelectorAdapter{
public boolean match(Element element){
if (realMatch(element)) {
- if (prev() != null && prev().match(element)){
+ if (prev() == null || (prev() != null && prev().match(element))){
return true;
}
}
return false;
}
protected abstract boolean realMatch(Element element);
}
| true | true | public boolean match(Element element){
if (realMatch(element)) {
if (prev() != null && prev().match(element)){
return true;
}
}
return false;
}
| public boolean match(Element element){
if (realMatch(element)) {
if (prev() == null || (prev() != null && prev().match(element))){
return true;
}
}
return false;
}
|
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/DefaultWayPropertySetSource.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/DefaultWayPropertySetSource.java
index 65f92f36e..074998b55 100644
--- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/DefaultWayPropertySetSource.java
+++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/DefaultWayPropertySetSource.java
@@ -1,607 +1,609 @@
/* This program 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 (props, at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.graph_builder.impl.osm;
import org.opentripplanner.common.model.P2;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
/**
* Factory interface for providing a default collection of {@link WayProperties} that determine how
* OSM streets can be traversed in various modes.
*
* Also supports
*
* @author bdferris, novalis
* @see WayPropertySetSource
* @see OpenStreetMapGraphBuilderImpl#setDefaultAccessPermissionsSource(props, WayPropertySetSource)
*/
public class DefaultWayPropertySetSource implements WayPropertySetSource {
/* properties and permissions for ways */
@Override
public WayPropertySet getWayPropertySet() {
WayPropertySet props = new WayPropertySet();
/* no bicycle tags */
/* NONE */
setProperties(props, "highway=raceway",
StreetTraversalPermission.NONE);
setProperties(props, "highway=construction",
StreetTraversalPermission.NONE);
/* PEDESTRIAN */
setProperties(props, "highway=steps",
StreetTraversalPermission.PEDESTRIAN);
+ setProperties(props, "highway=crossing",
+ StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "highway=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "public_transport=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "railway=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "footway=sidewalk;highway=footway",
StreetTraversalPermission.PEDESTRIAN);
/* PEDESTRIAN_AND_BICYCLE */
setProperties(props, "highway=cycleway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.68, 0.68);
setProperties(props, "highway=path",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.75, 0.75);
setProperties(props, "highway=pedestrian",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.90, 0.90);
setProperties(props, "highway=footway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
setProperties(props, "highway=bridleway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.3, 1.3);
/* ALL */
setProperties(props, "highway=living_street",
StreetTraversalPermission.ALL, 0.90, 0.90);
setProperties(props, "highway=unclassified",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=road",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=byway",
StreetTraversalPermission.ALL, 1.3, 1.3);
setProperties(props, "highway=track",
StreetTraversalPermission.ALL, 1.3, 1.3);
setProperties(props, "highway=service",
StreetTraversalPermission.ALL, 1.1, 1.1);
setProperties(props, "highway=residential",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=residential_link",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=tertiary",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=tertiary_link",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=secondary",
StreetTraversalPermission.ALL, 1.5, 1.5);
setProperties(props, "highway=secondary_link",
StreetTraversalPermission.ALL, 1.5, 1.5);
setProperties(props, "highway=primary",
StreetTraversalPermission.ALL, 2.06, 2.06);
setProperties(props, "highway=primary_link",
StreetTraversalPermission.ALL, 2.06, 2.06);
/* BICYCLE_AND_CAR */
// trunk and motorway links are often short distances and necessary connections
setProperties(props, "highway=trunk_link",
StreetTraversalPermission.CAR, 2.06, 2.06);
setProperties(props, "highway=motorway_link",
StreetTraversalPermission.CAR, 2.06, 2.06);
/* CAR */
setProperties(props, "highway=trunk",
StreetTraversalPermission.CAR, 7.47, 7.47);
setProperties(props, "highway=motorway",
StreetTraversalPermission.CAR, 8, 8);
/* cycleway=lane */
setProperties(props, "highway=*;cycleway=lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.87, 0.87);
setProperties(props, "highway=service;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=tertiary;cycleway=lane",
StreetTraversalPermission.ALL, 0.87, 0.87);
setProperties(props, "highway=tertiary_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.87, 0.87);
setProperties(props, "highway=secondary;cycleway=lane",
StreetTraversalPermission.ALL, 0.96, 0.96);
setProperties(props, "highway=secondary_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.96, 0.96);
setProperties(props, "highway=primary;cycleway=lane",
StreetTraversalPermission.ALL, 1.15, 1.15);
setProperties(props, "highway=primary_link;cycleway=lane",
StreetTraversalPermission.ALL, 1.15, 1.15);
setProperties(props, "highway=trunk;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.5, 1.5);
setProperties(props, "highway=trunk_link;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.15, 1.15);
setProperties(props, "highway=motorway;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
setProperties(props, "highway=motorway_link;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.15, 1.15);
/* cycleway=share_busway */
setProperties(props, "highway=*;cycleway=share_busway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.92, 0.92);
setProperties(props, "highway=service;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=residential;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=residential_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=tertiary;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.92, 0.92);
setProperties(props, "highway=tertiary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.92, 0.92);
setProperties(props, "highway=secondary;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.99, 0.99);
setProperties(props, "highway=secondary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.99, 0.99);
setProperties(props, "highway=primary;cycleway=share_busway",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=primary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=trunk;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.75, 1.75);
setProperties(props, "highway=trunk_link;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.25, 1.25);
setProperties(props, "highway=motorway;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.5, 2.5);
setProperties(props, "highway=motorway_link;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.25, 1.25);
/* cycleway=opposite_lane */
setProperties(props, "highway=*;cycleway=opposite_lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 0.87);
setProperties(props, "highway=service;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.1, 0.77);
setProperties(props, "highway=residential;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 0.98, 0.77);
setProperties(props, "highway=residential_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 0.98, 0.77);
setProperties(props, "highway=tertiary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1, 0.87);
setProperties(props, "highway=tertiary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1, 0.87);
setProperties(props, "highway=secondary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.5, 0.96);
setProperties(props, "highway=secondary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.5, 0.96);
setProperties(props, "highway=primary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 2.06, 1.15);
setProperties(props, "highway=primary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 2.06, 1.15);
setProperties(props, "highway=trunk;cycleway=opposite_lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.47, 1.5);
setProperties(props, "highway=trunk_link;cycleway=opposite_lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.06, 1.15);
/* cycleway=track */
setProperties(props, "highway=*;cycleway=track",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.73, 0.73);
setProperties(props, "highway=service;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=residential;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=residential_link;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=tertiary;cycleway=track",
StreetTraversalPermission.ALL, 0.75, 0.75);
setProperties(props, "highway=tertiary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.75, 0.75);
setProperties(props, "highway=secondary;cycleway=track",
StreetTraversalPermission.ALL, 0.8, 0.8);
setProperties(props, "highway=secondary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.8, 0.8);
setProperties(props, "highway=primary;cycleway=track",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=primary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=trunk;cycleway=track",
StreetTraversalPermission.BICYCLE_AND_CAR, 0.9, 0.9);
setProperties(props, "highway=trunk_link;cycleway=track",
StreetTraversalPermission.BICYCLE_AND_CAR, 0.85, 0.85);
/* cycleway=opposite_track */
setProperties(props, "highway=*;cycleway=opposite_track",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 0.73);
setProperties(props, "highway=service;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.1, 0.7);
setProperties(props, "highway=residential;cycleway=opposite_track",
StreetTraversalPermission.ALL, 0.98, 0.7);
setProperties(props, "highway=residential_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 0.98, 0.7);
setProperties(props, "highway=tertiary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1, 0.75);
setProperties(props, "highway=tertiary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1, 0.75);
setProperties(props, "highway=secondary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.5, 0.8);
setProperties(props, "highway=secondary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.5, 0.8);
setProperties(props, "highway=primary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 2.06, 0.85);
setProperties(props, "highway=primary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 2.06, 0.85);
setProperties(props, "highway=trunk;cycleway=opposite_track",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.47, 0.9);
setProperties(props, "highway=trunk_link;cycleway=opposite_track",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.06, 0.85);
/* cycleway=shared_lane a.k.a. bike boulevards or neighborhood greenways */
setProperties(props, "highway=*;cycleway=shared_lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
setProperties(props, "highway=service;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.73, 0.73);
setProperties(props, "highway=residential;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=tertiary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.83, 0.83);
setProperties(props, "highway=tertiary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.83, 0.83);
setProperties(props, "highway=secondary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=secondary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=primary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.75, 1.75);
setProperties(props, "highway=primary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.75, 1.75);
/* cycleway=opposite */
setProperties(props, "highway=*;cycleway=opposite",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 1.4);
setProperties(props, "highway=service;cycleway=opposite",
StreetTraversalPermission.ALL, 1.1, 1.1);
setProperties(props, "highway=residential;cycleway=opposite",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=residential_link;cycleway=opposite",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=tertiary;cycleway=opposite",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=tertiary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=secondary;cycleway=opposite",
StreetTraversalPermission.ALL, 1.5, 1.71);
setProperties(props, "highway=secondary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 1.5, 1.71);
setProperties(props, "highway=primary;cycleway=opposite",
StreetTraversalPermission.ALL, 2.06, 2.99);
setProperties(props, "highway=primary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 2.06, 2.99);
/* path */
setProperties(props, "highway=path;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.68, 0.68);
/* footway */
setProperties(props, "highway=footway;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.75, 0.75);
/* Portland area specific tags */
setProperties(props, "highway=footway;RLIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
setProperties(props, "highway=footway;CCGIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
/* sidewalk and crosswalk */
setProperties(props, "footway=sidewalk;highway=footway;bicycle=yes",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 2.5, 2.5);
setProperties(props, "footway=sidewalk;highway=footway;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
setProperties(props, "highway=footway;footway=crossing",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 2.5, 2.5);
setProperties(props, "highway=footway;footway=crossing;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
/* Portland area specific tags */
setProperties(props, "footway=sidewalk;highway=footway;RLIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1, 1);
setProperties(props, "footway=sidewalk;highway=footway;CCGIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1, 1);
/* bicycles on tracks (tracks are defined in OSM as: Roads for agricultural use, gravel roads in the
forest etc.; usually unpaved/unsealed but may occasionally apply to paved tracks as well.) */
setProperties(props, "highway=track;bicycle=yes",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.18, 1.18);
setProperties(props, "highway=track;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.99, 0.99);
setProperties(props, "highway=track;bicycle=yes;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.18, 1.18);
setProperties(props, "highway=track;bicycle=designated;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.99, 0.99);
/* this is to avoid double counting since tracks are almost of surface type that is penalized*/
setProperties(props, "highway=track;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.3, 1.3);
/* bicycle=designated, but no bike infrastructure is present */
setProperties(props, "highway=*;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.97, 0.97);
setProperties(props, "highway=service;bicycle=designated",
StreetTraversalPermission.ALL, 0.84, 0.84);
setProperties(props, "highway=residential;bicycle=designated",
StreetTraversalPermission.ALL, 0.95, 0.95);
setProperties(props, "highway=residential_link;bicycle=designated",
StreetTraversalPermission.ALL, 0.95, 0.95);
setProperties(props, "highway=tertiary;bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97);
setProperties(props, "highway=tertiary_link;bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97);
setProperties(props, "highway=secondary;bicycle=designated",
StreetTraversalPermission.ALL, 1.46, 1.46);
setProperties(props, "highway=secondary_link;bicycle=designated",
StreetTraversalPermission.ALL, 1.46, 1.46);
setProperties(props, "highway=primary;bicycle=designated",
StreetTraversalPermission.ALL, 2, 2);
setProperties(props, "highway=primary_link;bicycle=designated",
StreetTraversalPermission.ALL, 2, 2);
setProperties(props, "highway=trunk;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.25, 7.25);
setProperties(props, "highway=trunk_link;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
setProperties(props, "highway=motorway;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.76, 7.76);
setProperties(props, "highway=motorway_link;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
/* Automobile speeds in the United States: Based on my (mattwigway) personal experience,
* primarily in California */
setCarSpeed(props, "highway=motorway", 29); // 29 m/s ~= 65 mph
setCarSpeed(props, "highway=motorway_link", 15); // ~= 35 mph
setCarSpeed(props, "highway=trunk", 24.6f); // ~= 55 mph
setCarSpeed(props, "highway=trunk_link", 15); // ~= 35 mph
setCarSpeed(props, "highway=primary", 20); // ~= 45 mph
setCarSpeed(props, "highway=primary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=secondary", 15); // ~= 35 mph
setCarSpeed(props, "highway=secondary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=tertiary", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=tertiary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=living_street", 2.2f); // ~= 5 mph
// generally, these will not allow cars at all, but the docs say
// "For roads used mainly/exclusively for pedestrians . . . which may allow access by
// motorised vehicles only for very limited periods of the day."
// http://wiki.openstreetmap.org/wiki/Key:highway
// This of course makes the street network time-dependent
setCarSpeed(props, "highway=pedestrian", 2.2f); // ~= 5 mph
setCarSpeed(props, "highway=residential", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=unclassified", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=service", 6.7f); // ~= 15 mph
setCarSpeed(props, "highway=track", 4.5f); // ~= 10 mph
setCarSpeed(props, "highway=road", 11.2f); // ~= 25 mph
// default ~= 25 mph
props.setDefaultSpeed(11.2f);
/*** special situations ****/
/* cycleway:left/right=lane/track/shared_lane permutations -
* no longer needed because left/right matching algorithm
* does this
*/
/* cycleway:left=lane */
/* cycleway:right=track */
/* cycleway:left=track */
/* cycleway:right=shared_lane */
/* cycleway:left=shared_lane */
/* cycleway:right=lane, cycleway:left=track */
/* cycleway:right=lane, cycleway:left=shared_lane */
/* cycleway:right=track, cycleway:left=lane */
/* cycleway:right=track, cycleway:left=shared_lane */
/* cycleway:right=shared_lane, cycleway:left=lane */
/* cycleway:right=shared_lane, cycleway:left=track */
/* surface=* mixins */
/* sand and fine gravel are deadly for bikes */
setProperties(props, "surface=fine_gravel",
StreetTraversalPermission.ALL, 100.0, 100.0, true);
setProperties(props, "surface=sand",
StreetTraversalPermission.ALL, 100.0, 100.0, true);
/* unpaved, etc */
setProperties(props, "surface=unpaved",
StreetTraversalPermission.ALL, 1.18, 1.18, true);
setProperties(props, "surface=compacted",
StreetTraversalPermission.ALL, 1.18, 1.18, true);
setProperties(props, "surface=cobblestone",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=paving_stones",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=grass_paver",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=pebblestone",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=gravel",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=ground",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=dirt",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=earth",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=grass",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=mud",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=wood",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=metal",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=artifical_turf",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
// it is extremly unsafe to ride directly on the Scotsman
setProperties(props, "surface=tartan",
StreetTraversalPermission.ALL, 3.0, 3.0, true);
/* Portland-local mixins */
/* the RLIS/CCGIS:bicycle=designated mixins are coded out as they are no longer neccessary because of
of the bicycle=designated block of code above. This switch makes our weighting system less reliant
on tags that aren't generally used by the OSM community, and prevents the double counting that was
occuring on streets with both bicycle infrastructure and an RLIS:bicycle=designated tag */
/* setProperties(props, "RLIS:bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97, true); */
setProperties(props, "RLIS:bicycle=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.45, true);
setProperties(props, "RLIS:bicycle:right=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.0, true);
setProperties(props, "RLIS:bicycle:left=caution_area",
StreetTraversalPermission.ALL, 1.0, 1.45, true);
/* setProperties(props, "CCGIS:bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97, true); */
setProperties(props, "CCGIS:bicycle=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.45, true);
setProperties(props, "CCGIS:bicycle:right=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.0, true);
setProperties(props, "CCGIS:bicycle:left=caution_area",
StreetTraversalPermission.ALL, 1.0, 1.45, true);
props.defaultProperties.setPermission(StreetTraversalPermission.ALL);
/* and the notes */
createNotes(props, "note=*", "{note}");
createNotes(props, "notes=*", "{notes}");
createNotes(props, "RLIS:bicycle=caution_area", "Caution!");
createNotes(props, "CCGIS:bicycle=caution_area", "Caution!");
createNotes(props, "surface=unpaved", "Unpaved surface");
createNotes(props, "surface=compacted", "Unpaved surface");
createNotes(props, "surface=ground", "Unpaved surface");
createNotes(props, "surface=dirt", "Unpaved surface");
createNotes(props, "surface=earth", "Unpaved surface");
createNotes(props, "surface=grass", "Unpaved surface");
createNotes(props, "surface=mud", "Unpaved surface -- muddy!");
/* and some names */
// Basics
createNames(props, "highway=cycleway", "bike path");
createNames(props, "cycleway=track", "bike path");
createNames(props, "highway=pedestrian", "path");
createNames(props, "highway=pedestrian;area=yes", "open area");
createNames(props, "highway=path", "path");
createNames(props, "highway=footway", "path");
createNames(props, "highway=bridleway", "bridleway");
createNames(props, "highway=footway;bicycle=no", "footpath");
// Platforms
createNames(props, "otp:route_ref=*", "Route {otp:route_ref}");
createNames(props, "highway=platform;ref=*", "Platform {ref}");
createNames(props, "railway=platform;ref=*", "Platform {ref}");
createNames(props, "railway=platform;highway=footway;footway=sidewalk", "platform");
createNames(props, "railway=platform;highway=path;path=sidewalk", "platform");
createNames(props, "railway=platform;highway=pedestrian", "platform");
createNames(props, "railway=platform;highway=path", "platform");
createNames(props, "railway=platform;highway=footway", "platform");
createNames(props, "highway=platform", "platform");
createNames(props, "railway=platform", "platform");
createNames(props, "railway=platform;highway=footway;bicycle=no", "platform");
// Bridges/Tunnels
createNames(props, "highway=pedestrian;bridge=*", "footbridge");
createNames(props, "highway=path;bridge=*", "footbridge");
createNames(props, "highway=footway;bridge=*", "footbridge");
createNames(props, "highway=pedestrian;tunnel=*", "underpass");
createNames(props, "highway=path;tunnel=*", "underpass");
createNames(props, "highway=footway;tunnel=*", "underpass");
// Basic Mappings
createNames(props, "highway=motorway", "road");
createNames(props, "highway=motorway_link", "ramp");
createNames(props, "highway=trunk", "road");
createNames(props, "highway=trunk_link", "ramp");
createNames(props, "highway=primary", "road");
createNames(props, "highway=primary_link", "link");
createNames(props, "highway=secondary", "road");
createNames(props, "highway=secondary_link", "link");
createNames(props, "highway=tertiary", "road");
createNames(props, "highway=tertiary_link", "link");
createNames(props, "highway=unclassified", "road");
createNames(props, "highway=residential", "road");
createNames(props, "highway=living_street", "road");
createNames(props, "highway=road", "road");
createNames(props, "highway=service", "service road");
createNames(props, "highway=service;service=alley", "alley");
createNames(props, "highway=service;service=parking_aisle", "parking aisle");
createNames(props, "highway=byway", "byway");
createNames(props, "highway=track", "track");
createNames(props, "highway=footway;footway=sidewalk", "sidewalk");
createNames(props, "highway=path;path=sidewalk", "sidewalk");
createNames(props, "highway=steps", "steps");
createNames(props, "amenity=bicycle_rental;name=*", "Bicycle rental {name}");
createNames(props, "amenity=bicycle_rental", "Bicycle rental station");
//slope overrides
props.setSlopeOverride(new OSMSpecifier("bridge=*"), true);
props.setSlopeOverride(new OSMSpecifier("tunnel=*"), true);
return props;
}
private void createNames(WayPropertySet propset, String spec, String pattern) {
CreativeNamer namer = new CreativeNamer(pattern);
propset.addCreativeNamer(new OSMSpecifier(spec), namer);
}
private void createNotes(WayPropertySet propset, String spec, String pattern) {
NoteProperties properties = new NoteProperties();
properties.setNotePattern(pattern);
propset.addNote(new OSMSpecifier(spec), properties);
}
private void setProperties(WayPropertySet propset, String spec,
StreetTraversalPermission permission) {
setProperties(propset, spec, permission, 1.0, 1.0);
}
/**
* Note that the safeties here will be adjusted such that the safest street has a safety value
* of 1, with all others scaled proportionately.
*/
private void setProperties(WayPropertySet propset, String spec,
StreetTraversalPermission permission, double safety, double safetyBack) {
setProperties(propset, spec, permission, safety, safetyBack, false);
}
private void setProperties(WayPropertySet propset, String spec,
StreetTraversalPermission permission, double safety, double safetyBack, boolean mixin) {
WayProperties properties = new WayProperties();
properties.setPermission(permission);
properties.setSafetyFeatures(new P2<Double>(safety, safetyBack));
propset.addProperties(new OSMSpecifier(spec), properties, mixin);
}
private void setCarSpeed(WayPropertySet propset, String spec, float speed) {
SpeedPicker picker = new SpeedPicker();
picker.setSpecifier(new OSMSpecifier(spec));
picker.setSpeed(speed);
propset.addSpeedPicker(picker);
}
}
| true | true | public WayPropertySet getWayPropertySet() {
WayPropertySet props = new WayPropertySet();
/* no bicycle tags */
/* NONE */
setProperties(props, "highway=raceway",
StreetTraversalPermission.NONE);
setProperties(props, "highway=construction",
StreetTraversalPermission.NONE);
/* PEDESTRIAN */
setProperties(props, "highway=steps",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "highway=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "public_transport=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "railway=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "footway=sidewalk;highway=footway",
StreetTraversalPermission.PEDESTRIAN);
/* PEDESTRIAN_AND_BICYCLE */
setProperties(props, "highway=cycleway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.68, 0.68);
setProperties(props, "highway=path",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.75, 0.75);
setProperties(props, "highway=pedestrian",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.90, 0.90);
setProperties(props, "highway=footway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
setProperties(props, "highway=bridleway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.3, 1.3);
/* ALL */
setProperties(props, "highway=living_street",
StreetTraversalPermission.ALL, 0.90, 0.90);
setProperties(props, "highway=unclassified",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=road",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=byway",
StreetTraversalPermission.ALL, 1.3, 1.3);
setProperties(props, "highway=track",
StreetTraversalPermission.ALL, 1.3, 1.3);
setProperties(props, "highway=service",
StreetTraversalPermission.ALL, 1.1, 1.1);
setProperties(props, "highway=residential",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=residential_link",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=tertiary",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=tertiary_link",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=secondary",
StreetTraversalPermission.ALL, 1.5, 1.5);
setProperties(props, "highway=secondary_link",
StreetTraversalPermission.ALL, 1.5, 1.5);
setProperties(props, "highway=primary",
StreetTraversalPermission.ALL, 2.06, 2.06);
setProperties(props, "highway=primary_link",
StreetTraversalPermission.ALL, 2.06, 2.06);
/* BICYCLE_AND_CAR */
// trunk and motorway links are often short distances and necessary connections
setProperties(props, "highway=trunk_link",
StreetTraversalPermission.CAR, 2.06, 2.06);
setProperties(props, "highway=motorway_link",
StreetTraversalPermission.CAR, 2.06, 2.06);
/* CAR */
setProperties(props, "highway=trunk",
StreetTraversalPermission.CAR, 7.47, 7.47);
setProperties(props, "highway=motorway",
StreetTraversalPermission.CAR, 8, 8);
/* cycleway=lane */
setProperties(props, "highway=*;cycleway=lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.87, 0.87);
setProperties(props, "highway=service;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=tertiary;cycleway=lane",
StreetTraversalPermission.ALL, 0.87, 0.87);
setProperties(props, "highway=tertiary_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.87, 0.87);
setProperties(props, "highway=secondary;cycleway=lane",
StreetTraversalPermission.ALL, 0.96, 0.96);
setProperties(props, "highway=secondary_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.96, 0.96);
setProperties(props, "highway=primary;cycleway=lane",
StreetTraversalPermission.ALL, 1.15, 1.15);
setProperties(props, "highway=primary_link;cycleway=lane",
StreetTraversalPermission.ALL, 1.15, 1.15);
setProperties(props, "highway=trunk;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.5, 1.5);
setProperties(props, "highway=trunk_link;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.15, 1.15);
setProperties(props, "highway=motorway;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
setProperties(props, "highway=motorway_link;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.15, 1.15);
/* cycleway=share_busway */
setProperties(props, "highway=*;cycleway=share_busway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.92, 0.92);
setProperties(props, "highway=service;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=residential;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=residential_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=tertiary;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.92, 0.92);
setProperties(props, "highway=tertiary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.92, 0.92);
setProperties(props, "highway=secondary;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.99, 0.99);
setProperties(props, "highway=secondary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.99, 0.99);
setProperties(props, "highway=primary;cycleway=share_busway",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=primary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=trunk;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.75, 1.75);
setProperties(props, "highway=trunk_link;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.25, 1.25);
setProperties(props, "highway=motorway;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.5, 2.5);
setProperties(props, "highway=motorway_link;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.25, 1.25);
/* cycleway=opposite_lane */
setProperties(props, "highway=*;cycleway=opposite_lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 0.87);
setProperties(props, "highway=service;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.1, 0.77);
setProperties(props, "highway=residential;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 0.98, 0.77);
setProperties(props, "highway=residential_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 0.98, 0.77);
setProperties(props, "highway=tertiary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1, 0.87);
setProperties(props, "highway=tertiary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1, 0.87);
setProperties(props, "highway=secondary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.5, 0.96);
setProperties(props, "highway=secondary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.5, 0.96);
setProperties(props, "highway=primary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 2.06, 1.15);
setProperties(props, "highway=primary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 2.06, 1.15);
setProperties(props, "highway=trunk;cycleway=opposite_lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.47, 1.5);
setProperties(props, "highway=trunk_link;cycleway=opposite_lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.06, 1.15);
/* cycleway=track */
setProperties(props, "highway=*;cycleway=track",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.73, 0.73);
setProperties(props, "highway=service;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=residential;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=residential_link;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=tertiary;cycleway=track",
StreetTraversalPermission.ALL, 0.75, 0.75);
setProperties(props, "highway=tertiary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.75, 0.75);
setProperties(props, "highway=secondary;cycleway=track",
StreetTraversalPermission.ALL, 0.8, 0.8);
setProperties(props, "highway=secondary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.8, 0.8);
setProperties(props, "highway=primary;cycleway=track",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=primary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=trunk;cycleway=track",
StreetTraversalPermission.BICYCLE_AND_CAR, 0.9, 0.9);
setProperties(props, "highway=trunk_link;cycleway=track",
StreetTraversalPermission.BICYCLE_AND_CAR, 0.85, 0.85);
/* cycleway=opposite_track */
setProperties(props, "highway=*;cycleway=opposite_track",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 0.73);
setProperties(props, "highway=service;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.1, 0.7);
setProperties(props, "highway=residential;cycleway=opposite_track",
StreetTraversalPermission.ALL, 0.98, 0.7);
setProperties(props, "highway=residential_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 0.98, 0.7);
setProperties(props, "highway=tertiary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1, 0.75);
setProperties(props, "highway=tertiary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1, 0.75);
setProperties(props, "highway=secondary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.5, 0.8);
setProperties(props, "highway=secondary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.5, 0.8);
setProperties(props, "highway=primary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 2.06, 0.85);
setProperties(props, "highway=primary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 2.06, 0.85);
setProperties(props, "highway=trunk;cycleway=opposite_track",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.47, 0.9);
setProperties(props, "highway=trunk_link;cycleway=opposite_track",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.06, 0.85);
/* cycleway=shared_lane a.k.a. bike boulevards or neighborhood greenways */
setProperties(props, "highway=*;cycleway=shared_lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
setProperties(props, "highway=service;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.73, 0.73);
setProperties(props, "highway=residential;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=tertiary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.83, 0.83);
setProperties(props, "highway=tertiary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.83, 0.83);
setProperties(props, "highway=secondary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=secondary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=primary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.75, 1.75);
setProperties(props, "highway=primary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.75, 1.75);
/* cycleway=opposite */
setProperties(props, "highway=*;cycleway=opposite",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 1.4);
setProperties(props, "highway=service;cycleway=opposite",
StreetTraversalPermission.ALL, 1.1, 1.1);
setProperties(props, "highway=residential;cycleway=opposite",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=residential_link;cycleway=opposite",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=tertiary;cycleway=opposite",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=tertiary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=secondary;cycleway=opposite",
StreetTraversalPermission.ALL, 1.5, 1.71);
setProperties(props, "highway=secondary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 1.5, 1.71);
setProperties(props, "highway=primary;cycleway=opposite",
StreetTraversalPermission.ALL, 2.06, 2.99);
setProperties(props, "highway=primary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 2.06, 2.99);
/* path */
setProperties(props, "highway=path;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.68, 0.68);
/* footway */
setProperties(props, "highway=footway;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.75, 0.75);
/* Portland area specific tags */
setProperties(props, "highway=footway;RLIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
setProperties(props, "highway=footway;CCGIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
/* sidewalk and crosswalk */
setProperties(props, "footway=sidewalk;highway=footway;bicycle=yes",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 2.5, 2.5);
setProperties(props, "footway=sidewalk;highway=footway;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
setProperties(props, "highway=footway;footway=crossing",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 2.5, 2.5);
setProperties(props, "highway=footway;footway=crossing;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
/* Portland area specific tags */
setProperties(props, "footway=sidewalk;highway=footway;RLIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1, 1);
setProperties(props, "footway=sidewalk;highway=footway;CCGIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1, 1);
/* bicycles on tracks (tracks are defined in OSM as: Roads for agricultural use, gravel roads in the
forest etc.; usually unpaved/unsealed but may occasionally apply to paved tracks as well.) */
setProperties(props, "highway=track;bicycle=yes",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.18, 1.18);
setProperties(props, "highway=track;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.99, 0.99);
setProperties(props, "highway=track;bicycle=yes;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.18, 1.18);
setProperties(props, "highway=track;bicycle=designated;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.99, 0.99);
/* this is to avoid double counting since tracks are almost of surface type that is penalized*/
setProperties(props, "highway=track;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.3, 1.3);
/* bicycle=designated, but no bike infrastructure is present */
setProperties(props, "highway=*;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.97, 0.97);
setProperties(props, "highway=service;bicycle=designated",
StreetTraversalPermission.ALL, 0.84, 0.84);
setProperties(props, "highway=residential;bicycle=designated",
StreetTraversalPermission.ALL, 0.95, 0.95);
setProperties(props, "highway=residential_link;bicycle=designated",
StreetTraversalPermission.ALL, 0.95, 0.95);
setProperties(props, "highway=tertiary;bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97);
setProperties(props, "highway=tertiary_link;bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97);
setProperties(props, "highway=secondary;bicycle=designated",
StreetTraversalPermission.ALL, 1.46, 1.46);
setProperties(props, "highway=secondary_link;bicycle=designated",
StreetTraversalPermission.ALL, 1.46, 1.46);
setProperties(props, "highway=primary;bicycle=designated",
StreetTraversalPermission.ALL, 2, 2);
setProperties(props, "highway=primary_link;bicycle=designated",
StreetTraversalPermission.ALL, 2, 2);
setProperties(props, "highway=trunk;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.25, 7.25);
setProperties(props, "highway=trunk_link;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
setProperties(props, "highway=motorway;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.76, 7.76);
setProperties(props, "highway=motorway_link;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
/* Automobile speeds in the United States: Based on my (mattwigway) personal experience,
* primarily in California */
setCarSpeed(props, "highway=motorway", 29); // 29 m/s ~= 65 mph
setCarSpeed(props, "highway=motorway_link", 15); // ~= 35 mph
setCarSpeed(props, "highway=trunk", 24.6f); // ~= 55 mph
setCarSpeed(props, "highway=trunk_link", 15); // ~= 35 mph
setCarSpeed(props, "highway=primary", 20); // ~= 45 mph
setCarSpeed(props, "highway=primary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=secondary", 15); // ~= 35 mph
setCarSpeed(props, "highway=secondary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=tertiary", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=tertiary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=living_street", 2.2f); // ~= 5 mph
// generally, these will not allow cars at all, but the docs say
// "For roads used mainly/exclusively for pedestrians . . . which may allow access by
// motorised vehicles only for very limited periods of the day."
// http://wiki.openstreetmap.org/wiki/Key:highway
// This of course makes the street network time-dependent
setCarSpeed(props, "highway=pedestrian", 2.2f); // ~= 5 mph
setCarSpeed(props, "highway=residential", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=unclassified", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=service", 6.7f); // ~= 15 mph
setCarSpeed(props, "highway=track", 4.5f); // ~= 10 mph
setCarSpeed(props, "highway=road", 11.2f); // ~= 25 mph
// default ~= 25 mph
props.setDefaultSpeed(11.2f);
/*** special situations ****/
/* cycleway:left/right=lane/track/shared_lane permutations -
* no longer needed because left/right matching algorithm
* does this
*/
/* cycleway:left=lane */
/* cycleway:right=track */
/* cycleway:left=track */
/* cycleway:right=shared_lane */
/* cycleway:left=shared_lane */
/* cycleway:right=lane, cycleway:left=track */
/* cycleway:right=lane, cycleway:left=shared_lane */
/* cycleway:right=track, cycleway:left=lane */
/* cycleway:right=track, cycleway:left=shared_lane */
/* cycleway:right=shared_lane, cycleway:left=lane */
/* cycleway:right=shared_lane, cycleway:left=track */
/* surface=* mixins */
/* sand and fine gravel are deadly for bikes */
setProperties(props, "surface=fine_gravel",
StreetTraversalPermission.ALL, 100.0, 100.0, true);
setProperties(props, "surface=sand",
StreetTraversalPermission.ALL, 100.0, 100.0, true);
/* unpaved, etc */
setProperties(props, "surface=unpaved",
StreetTraversalPermission.ALL, 1.18, 1.18, true);
setProperties(props, "surface=compacted",
StreetTraversalPermission.ALL, 1.18, 1.18, true);
setProperties(props, "surface=cobblestone",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=paving_stones",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=grass_paver",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=pebblestone",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=gravel",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=ground",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=dirt",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=earth",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=grass",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=mud",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=wood",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=metal",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=artifical_turf",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
// it is extremly unsafe to ride directly on the Scotsman
setProperties(props, "surface=tartan",
StreetTraversalPermission.ALL, 3.0, 3.0, true);
/* Portland-local mixins */
/* the RLIS/CCGIS:bicycle=designated mixins are coded out as they are no longer neccessary because of
of the bicycle=designated block of code above. This switch makes our weighting system less reliant
on tags that aren't generally used by the OSM community, and prevents the double counting that was
occuring on streets with both bicycle infrastructure and an RLIS:bicycle=designated tag */
/* setProperties(props, "RLIS:bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97, true); */
setProperties(props, "RLIS:bicycle=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.45, true);
setProperties(props, "RLIS:bicycle:right=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.0, true);
setProperties(props, "RLIS:bicycle:left=caution_area",
StreetTraversalPermission.ALL, 1.0, 1.45, true);
/* setProperties(props, "CCGIS:bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97, true); */
setProperties(props, "CCGIS:bicycle=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.45, true);
setProperties(props, "CCGIS:bicycle:right=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.0, true);
setProperties(props, "CCGIS:bicycle:left=caution_area",
StreetTraversalPermission.ALL, 1.0, 1.45, true);
props.defaultProperties.setPermission(StreetTraversalPermission.ALL);
/* and the notes */
createNotes(props, "note=*", "{note}");
createNotes(props, "notes=*", "{notes}");
createNotes(props, "RLIS:bicycle=caution_area", "Caution!");
createNotes(props, "CCGIS:bicycle=caution_area", "Caution!");
createNotes(props, "surface=unpaved", "Unpaved surface");
createNotes(props, "surface=compacted", "Unpaved surface");
createNotes(props, "surface=ground", "Unpaved surface");
createNotes(props, "surface=dirt", "Unpaved surface");
createNotes(props, "surface=earth", "Unpaved surface");
createNotes(props, "surface=grass", "Unpaved surface");
createNotes(props, "surface=mud", "Unpaved surface -- muddy!");
/* and some names */
// Basics
createNames(props, "highway=cycleway", "bike path");
createNames(props, "cycleway=track", "bike path");
createNames(props, "highway=pedestrian", "path");
createNames(props, "highway=pedestrian;area=yes", "open area");
createNames(props, "highway=path", "path");
createNames(props, "highway=footway", "path");
createNames(props, "highway=bridleway", "bridleway");
createNames(props, "highway=footway;bicycle=no", "footpath");
// Platforms
createNames(props, "otp:route_ref=*", "Route {otp:route_ref}");
createNames(props, "highway=platform;ref=*", "Platform {ref}");
createNames(props, "railway=platform;ref=*", "Platform {ref}");
createNames(props, "railway=platform;highway=footway;footway=sidewalk", "platform");
createNames(props, "railway=platform;highway=path;path=sidewalk", "platform");
createNames(props, "railway=platform;highway=pedestrian", "platform");
createNames(props, "railway=platform;highway=path", "platform");
createNames(props, "railway=platform;highway=footway", "platform");
createNames(props, "highway=platform", "platform");
createNames(props, "railway=platform", "platform");
createNames(props, "railway=platform;highway=footway;bicycle=no", "platform");
// Bridges/Tunnels
createNames(props, "highway=pedestrian;bridge=*", "footbridge");
createNames(props, "highway=path;bridge=*", "footbridge");
createNames(props, "highway=footway;bridge=*", "footbridge");
createNames(props, "highway=pedestrian;tunnel=*", "underpass");
createNames(props, "highway=path;tunnel=*", "underpass");
createNames(props, "highway=footway;tunnel=*", "underpass");
// Basic Mappings
createNames(props, "highway=motorway", "road");
createNames(props, "highway=motorway_link", "ramp");
createNames(props, "highway=trunk", "road");
createNames(props, "highway=trunk_link", "ramp");
createNames(props, "highway=primary", "road");
createNames(props, "highway=primary_link", "link");
createNames(props, "highway=secondary", "road");
createNames(props, "highway=secondary_link", "link");
createNames(props, "highway=tertiary", "road");
createNames(props, "highway=tertiary_link", "link");
createNames(props, "highway=unclassified", "road");
createNames(props, "highway=residential", "road");
createNames(props, "highway=living_street", "road");
createNames(props, "highway=road", "road");
createNames(props, "highway=service", "service road");
createNames(props, "highway=service;service=alley", "alley");
createNames(props, "highway=service;service=parking_aisle", "parking aisle");
createNames(props, "highway=byway", "byway");
createNames(props, "highway=track", "track");
createNames(props, "highway=footway;footway=sidewalk", "sidewalk");
createNames(props, "highway=path;path=sidewalk", "sidewalk");
createNames(props, "highway=steps", "steps");
createNames(props, "amenity=bicycle_rental;name=*", "Bicycle rental {name}");
createNames(props, "amenity=bicycle_rental", "Bicycle rental station");
//slope overrides
props.setSlopeOverride(new OSMSpecifier("bridge=*"), true);
props.setSlopeOverride(new OSMSpecifier("tunnel=*"), true);
return props;
}
| public WayPropertySet getWayPropertySet() {
WayPropertySet props = new WayPropertySet();
/* no bicycle tags */
/* NONE */
setProperties(props, "highway=raceway",
StreetTraversalPermission.NONE);
setProperties(props, "highway=construction",
StreetTraversalPermission.NONE);
/* PEDESTRIAN */
setProperties(props, "highway=steps",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "highway=crossing",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "highway=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "public_transport=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "railway=platform",
StreetTraversalPermission.PEDESTRIAN);
setProperties(props, "footway=sidewalk;highway=footway",
StreetTraversalPermission.PEDESTRIAN);
/* PEDESTRIAN_AND_BICYCLE */
setProperties(props, "highway=cycleway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.68, 0.68);
setProperties(props, "highway=path",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.75, 0.75);
setProperties(props, "highway=pedestrian",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.90, 0.90);
setProperties(props, "highway=footway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
setProperties(props, "highway=bridleway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.3, 1.3);
/* ALL */
setProperties(props, "highway=living_street",
StreetTraversalPermission.ALL, 0.90, 0.90);
setProperties(props, "highway=unclassified",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=road",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=byway",
StreetTraversalPermission.ALL, 1.3, 1.3);
setProperties(props, "highway=track",
StreetTraversalPermission.ALL, 1.3, 1.3);
setProperties(props, "highway=service",
StreetTraversalPermission.ALL, 1.1, 1.1);
setProperties(props, "highway=residential",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=residential_link",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=tertiary",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=tertiary_link",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=secondary",
StreetTraversalPermission.ALL, 1.5, 1.5);
setProperties(props, "highway=secondary_link",
StreetTraversalPermission.ALL, 1.5, 1.5);
setProperties(props, "highway=primary",
StreetTraversalPermission.ALL, 2.06, 2.06);
setProperties(props, "highway=primary_link",
StreetTraversalPermission.ALL, 2.06, 2.06);
/* BICYCLE_AND_CAR */
// trunk and motorway links are often short distances and necessary connections
setProperties(props, "highway=trunk_link",
StreetTraversalPermission.CAR, 2.06, 2.06);
setProperties(props, "highway=motorway_link",
StreetTraversalPermission.CAR, 2.06, 2.06);
/* CAR */
setProperties(props, "highway=trunk",
StreetTraversalPermission.CAR, 7.47, 7.47);
setProperties(props, "highway=motorway",
StreetTraversalPermission.CAR, 8, 8);
/* cycleway=lane */
setProperties(props, "highway=*;cycleway=lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.87, 0.87);
setProperties(props, "highway=service;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=tertiary;cycleway=lane",
StreetTraversalPermission.ALL, 0.87, 0.87);
setProperties(props, "highway=tertiary_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.87, 0.87);
setProperties(props, "highway=secondary;cycleway=lane",
StreetTraversalPermission.ALL, 0.96, 0.96);
setProperties(props, "highway=secondary_link;cycleway=lane",
StreetTraversalPermission.ALL, 0.96, 0.96);
setProperties(props, "highway=primary;cycleway=lane",
StreetTraversalPermission.ALL, 1.15, 1.15);
setProperties(props, "highway=primary_link;cycleway=lane",
StreetTraversalPermission.ALL, 1.15, 1.15);
setProperties(props, "highway=trunk;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.5, 1.5);
setProperties(props, "highway=trunk_link;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.15, 1.15);
setProperties(props, "highway=motorway;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
setProperties(props, "highway=motorway_link;cycleway=lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.15, 1.15);
/* cycleway=share_busway */
setProperties(props, "highway=*;cycleway=share_busway",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.92, 0.92);
setProperties(props, "highway=service;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=residential;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=residential_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=tertiary;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.92, 0.92);
setProperties(props, "highway=tertiary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.92, 0.92);
setProperties(props, "highway=secondary;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.99, 0.99);
setProperties(props, "highway=secondary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 0.99, 0.99);
setProperties(props, "highway=primary;cycleway=share_busway",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=primary_link;cycleway=share_busway",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=trunk;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.75, 1.75);
setProperties(props, "highway=trunk_link;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.25, 1.25);
setProperties(props, "highway=motorway;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.5, 2.5);
setProperties(props, "highway=motorway_link;cycleway=share_busway",
StreetTraversalPermission.BICYCLE_AND_CAR, 1.25, 1.25);
/* cycleway=opposite_lane */
setProperties(props, "highway=*;cycleway=opposite_lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 0.87);
setProperties(props, "highway=service;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.1, 0.77);
setProperties(props, "highway=residential;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 0.98, 0.77);
setProperties(props, "highway=residential_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 0.98, 0.77);
setProperties(props, "highway=tertiary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1, 0.87);
setProperties(props, "highway=tertiary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1, 0.87);
setProperties(props, "highway=secondary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.5, 0.96);
setProperties(props, "highway=secondary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 1.5, 0.96);
setProperties(props, "highway=primary;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 2.06, 1.15);
setProperties(props, "highway=primary_link;cycleway=opposite_lane",
StreetTraversalPermission.ALL, 2.06, 1.15);
setProperties(props, "highway=trunk;cycleway=opposite_lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.47, 1.5);
setProperties(props, "highway=trunk_link;cycleway=opposite_lane",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.06, 1.15);
/* cycleway=track */
setProperties(props, "highway=*;cycleway=track",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.73, 0.73);
setProperties(props, "highway=service;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=residential;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=residential_link;cycleway=track",
StreetTraversalPermission.ALL, 0.7, 0.7);
setProperties(props, "highway=tertiary;cycleway=track",
StreetTraversalPermission.ALL, 0.75, 0.75);
setProperties(props, "highway=tertiary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.75, 0.75);
setProperties(props, "highway=secondary;cycleway=track",
StreetTraversalPermission.ALL, 0.8, 0.8);
setProperties(props, "highway=secondary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.8, 0.8);
setProperties(props, "highway=primary;cycleway=track",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=primary_link;cycleway=track",
StreetTraversalPermission.ALL, 0.85, 0.85);
setProperties(props, "highway=trunk;cycleway=track",
StreetTraversalPermission.BICYCLE_AND_CAR, 0.9, 0.9);
setProperties(props, "highway=trunk_link;cycleway=track",
StreetTraversalPermission.BICYCLE_AND_CAR, 0.85, 0.85);
/* cycleway=opposite_track */
setProperties(props, "highway=*;cycleway=opposite_track",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 0.73);
setProperties(props, "highway=service;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.1, 0.7);
setProperties(props, "highway=residential;cycleway=opposite_track",
StreetTraversalPermission.ALL, 0.98, 0.7);
setProperties(props, "highway=residential_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 0.98, 0.7);
setProperties(props, "highway=tertiary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1, 0.75);
setProperties(props, "highway=tertiary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1, 0.75);
setProperties(props, "highway=secondary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.5, 0.8);
setProperties(props, "highway=secondary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 1.5, 0.8);
setProperties(props, "highway=primary;cycleway=opposite_track",
StreetTraversalPermission.ALL, 2.06, 0.85);
setProperties(props, "highway=primary_link;cycleway=opposite_track",
StreetTraversalPermission.ALL, 2.06, 0.85);
setProperties(props, "highway=trunk;cycleway=opposite_track",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.47, 0.9);
setProperties(props, "highway=trunk_link;cycleway=opposite_track",
StreetTraversalPermission.BICYCLE_AND_CAR, 2.06, 0.85);
/* cycleway=shared_lane a.k.a. bike boulevards or neighborhood greenways */
setProperties(props, "highway=*;cycleway=shared_lane",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
setProperties(props, "highway=service;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.73, 0.73);
setProperties(props, "highway=residential;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=residential_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.77, 0.77);
setProperties(props, "highway=tertiary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.83, 0.83);
setProperties(props, "highway=tertiary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 0.83, 0.83);
setProperties(props, "highway=secondary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=secondary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.25, 1.25);
setProperties(props, "highway=primary;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.75, 1.75);
setProperties(props, "highway=primary_link;cycleway=shared_lane",
StreetTraversalPermission.ALL, 1.75, 1.75);
/* cycleway=opposite */
setProperties(props, "highway=*;cycleway=opposite",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.0, 1.4);
setProperties(props, "highway=service;cycleway=opposite",
StreetTraversalPermission.ALL, 1.1, 1.1);
setProperties(props, "highway=residential;cycleway=opposite",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=residential_link;cycleway=opposite",
StreetTraversalPermission.ALL, 0.98, 0.98);
setProperties(props, "highway=tertiary;cycleway=opposite",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=tertiary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 1, 1);
setProperties(props, "highway=secondary;cycleway=opposite",
StreetTraversalPermission.ALL, 1.5, 1.71);
setProperties(props, "highway=secondary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 1.5, 1.71);
setProperties(props, "highway=primary;cycleway=opposite",
StreetTraversalPermission.ALL, 2.06, 2.99);
setProperties(props, "highway=primary_link;cycleway=opposite",
StreetTraversalPermission.ALL, 2.06, 2.99);
/* path */
setProperties(props, "highway=path;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.68, 0.68);
/* footway */
setProperties(props, "highway=footway;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.75, 0.75);
/* Portland area specific tags */
setProperties(props, "highway=footway;RLIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
setProperties(props, "highway=footway;CCGIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.77, 0.77);
/* sidewalk and crosswalk */
setProperties(props, "footway=sidewalk;highway=footway;bicycle=yes",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 2.5, 2.5);
setProperties(props, "footway=sidewalk;highway=footway;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
setProperties(props, "highway=footway;footway=crossing",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 2.5, 2.5);
setProperties(props, "highway=footway;footway=crossing;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.1, 1.1);
/* Portland area specific tags */
setProperties(props, "footway=sidewalk;highway=footway;RLIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1, 1);
setProperties(props, "footway=sidewalk;highway=footway;CCGIS:bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1, 1);
/* bicycles on tracks (tracks are defined in OSM as: Roads for agricultural use, gravel roads in the
forest etc.; usually unpaved/unsealed but may occasionally apply to paved tracks as well.) */
setProperties(props, "highway=track;bicycle=yes",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.18, 1.18);
setProperties(props, "highway=track;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.99, 0.99);
setProperties(props, "highway=track;bicycle=yes;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.18, 1.18);
setProperties(props, "highway=track;bicycle=designated;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.99, 0.99);
/* this is to avoid double counting since tracks are almost of surface type that is penalized*/
setProperties(props, "highway=track;surface=*",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 1.3, 1.3);
/* bicycle=designated, but no bike infrastructure is present */
setProperties(props, "highway=*;bicycle=designated",
StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE, 0.97, 0.97);
setProperties(props, "highway=service;bicycle=designated",
StreetTraversalPermission.ALL, 0.84, 0.84);
setProperties(props, "highway=residential;bicycle=designated",
StreetTraversalPermission.ALL, 0.95, 0.95);
setProperties(props, "highway=residential_link;bicycle=designated",
StreetTraversalPermission.ALL, 0.95, 0.95);
setProperties(props, "highway=tertiary;bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97);
setProperties(props, "highway=tertiary_link;bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97);
setProperties(props, "highway=secondary;bicycle=designated",
StreetTraversalPermission.ALL, 1.46, 1.46);
setProperties(props, "highway=secondary_link;bicycle=designated",
StreetTraversalPermission.ALL, 1.46, 1.46);
setProperties(props, "highway=primary;bicycle=designated",
StreetTraversalPermission.ALL, 2, 2);
setProperties(props, "highway=primary_link;bicycle=designated",
StreetTraversalPermission.ALL, 2, 2);
setProperties(props, "highway=trunk;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.25, 7.25);
setProperties(props, "highway=trunk_link;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
setProperties(props, "highway=motorway;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 7.76, 7.76);
setProperties(props, "highway=motorway_link;bicycle=designated",
StreetTraversalPermission.BICYCLE_AND_CAR, 2, 2);
/* Automobile speeds in the United States: Based on my (mattwigway) personal experience,
* primarily in California */
setCarSpeed(props, "highway=motorway", 29); // 29 m/s ~= 65 mph
setCarSpeed(props, "highway=motorway_link", 15); // ~= 35 mph
setCarSpeed(props, "highway=trunk", 24.6f); // ~= 55 mph
setCarSpeed(props, "highway=trunk_link", 15); // ~= 35 mph
setCarSpeed(props, "highway=primary", 20); // ~= 45 mph
setCarSpeed(props, "highway=primary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=secondary", 15); // ~= 35 mph
setCarSpeed(props, "highway=secondary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=tertiary", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=tertiary_link", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=living_street", 2.2f); // ~= 5 mph
// generally, these will not allow cars at all, but the docs say
// "For roads used mainly/exclusively for pedestrians . . . which may allow access by
// motorised vehicles only for very limited periods of the day."
// http://wiki.openstreetmap.org/wiki/Key:highway
// This of course makes the street network time-dependent
setCarSpeed(props, "highway=pedestrian", 2.2f); // ~= 5 mph
setCarSpeed(props, "highway=residential", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=unclassified", 11.2f); // ~= 25 mph
setCarSpeed(props, "highway=service", 6.7f); // ~= 15 mph
setCarSpeed(props, "highway=track", 4.5f); // ~= 10 mph
setCarSpeed(props, "highway=road", 11.2f); // ~= 25 mph
// default ~= 25 mph
props.setDefaultSpeed(11.2f);
/*** special situations ****/
/* cycleway:left/right=lane/track/shared_lane permutations -
* no longer needed because left/right matching algorithm
* does this
*/
/* cycleway:left=lane */
/* cycleway:right=track */
/* cycleway:left=track */
/* cycleway:right=shared_lane */
/* cycleway:left=shared_lane */
/* cycleway:right=lane, cycleway:left=track */
/* cycleway:right=lane, cycleway:left=shared_lane */
/* cycleway:right=track, cycleway:left=lane */
/* cycleway:right=track, cycleway:left=shared_lane */
/* cycleway:right=shared_lane, cycleway:left=lane */
/* cycleway:right=shared_lane, cycleway:left=track */
/* surface=* mixins */
/* sand and fine gravel are deadly for bikes */
setProperties(props, "surface=fine_gravel",
StreetTraversalPermission.ALL, 100.0, 100.0, true);
setProperties(props, "surface=sand",
StreetTraversalPermission.ALL, 100.0, 100.0, true);
/* unpaved, etc */
setProperties(props, "surface=unpaved",
StreetTraversalPermission.ALL, 1.18, 1.18, true);
setProperties(props, "surface=compacted",
StreetTraversalPermission.ALL, 1.18, 1.18, true);
setProperties(props, "surface=cobblestone",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=paving_stones",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=grass_paver",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=pebblestone",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=gravel",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=ground",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=dirt",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=earth",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=grass",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=mud",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=wood",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=metal",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
setProperties(props, "surface=artifical_turf",
StreetTraversalPermission.ALL, 1.5, 1.5, true);
// it is extremly unsafe to ride directly on the Scotsman
setProperties(props, "surface=tartan",
StreetTraversalPermission.ALL, 3.0, 3.0, true);
/* Portland-local mixins */
/* the RLIS/CCGIS:bicycle=designated mixins are coded out as they are no longer neccessary because of
of the bicycle=designated block of code above. This switch makes our weighting system less reliant
on tags that aren't generally used by the OSM community, and prevents the double counting that was
occuring on streets with both bicycle infrastructure and an RLIS:bicycle=designated tag */
/* setProperties(props, "RLIS:bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97, true); */
setProperties(props, "RLIS:bicycle=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.45, true);
setProperties(props, "RLIS:bicycle:right=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.0, true);
setProperties(props, "RLIS:bicycle:left=caution_area",
StreetTraversalPermission.ALL, 1.0, 1.45, true);
/* setProperties(props, "CCGIS:bicycle=designated",
StreetTraversalPermission.ALL, 0.97, 0.97, true); */
setProperties(props, "CCGIS:bicycle=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.45, true);
setProperties(props, "CCGIS:bicycle:right=caution_area",
StreetTraversalPermission.ALL, 1.45, 1.0, true);
setProperties(props, "CCGIS:bicycle:left=caution_area",
StreetTraversalPermission.ALL, 1.0, 1.45, true);
props.defaultProperties.setPermission(StreetTraversalPermission.ALL);
/* and the notes */
createNotes(props, "note=*", "{note}");
createNotes(props, "notes=*", "{notes}");
createNotes(props, "RLIS:bicycle=caution_area", "Caution!");
createNotes(props, "CCGIS:bicycle=caution_area", "Caution!");
createNotes(props, "surface=unpaved", "Unpaved surface");
createNotes(props, "surface=compacted", "Unpaved surface");
createNotes(props, "surface=ground", "Unpaved surface");
createNotes(props, "surface=dirt", "Unpaved surface");
createNotes(props, "surface=earth", "Unpaved surface");
createNotes(props, "surface=grass", "Unpaved surface");
createNotes(props, "surface=mud", "Unpaved surface -- muddy!");
/* and some names */
// Basics
createNames(props, "highway=cycleway", "bike path");
createNames(props, "cycleway=track", "bike path");
createNames(props, "highway=pedestrian", "path");
createNames(props, "highway=pedestrian;area=yes", "open area");
createNames(props, "highway=path", "path");
createNames(props, "highway=footway", "path");
createNames(props, "highway=bridleway", "bridleway");
createNames(props, "highway=footway;bicycle=no", "footpath");
// Platforms
createNames(props, "otp:route_ref=*", "Route {otp:route_ref}");
createNames(props, "highway=platform;ref=*", "Platform {ref}");
createNames(props, "railway=platform;ref=*", "Platform {ref}");
createNames(props, "railway=platform;highway=footway;footway=sidewalk", "platform");
createNames(props, "railway=platform;highway=path;path=sidewalk", "platform");
createNames(props, "railway=platform;highway=pedestrian", "platform");
createNames(props, "railway=platform;highway=path", "platform");
createNames(props, "railway=platform;highway=footway", "platform");
createNames(props, "highway=platform", "platform");
createNames(props, "railway=platform", "platform");
createNames(props, "railway=platform;highway=footway;bicycle=no", "platform");
// Bridges/Tunnels
createNames(props, "highway=pedestrian;bridge=*", "footbridge");
createNames(props, "highway=path;bridge=*", "footbridge");
createNames(props, "highway=footway;bridge=*", "footbridge");
createNames(props, "highway=pedestrian;tunnel=*", "underpass");
createNames(props, "highway=path;tunnel=*", "underpass");
createNames(props, "highway=footway;tunnel=*", "underpass");
// Basic Mappings
createNames(props, "highway=motorway", "road");
createNames(props, "highway=motorway_link", "ramp");
createNames(props, "highway=trunk", "road");
createNames(props, "highway=trunk_link", "ramp");
createNames(props, "highway=primary", "road");
createNames(props, "highway=primary_link", "link");
createNames(props, "highway=secondary", "road");
createNames(props, "highway=secondary_link", "link");
createNames(props, "highway=tertiary", "road");
createNames(props, "highway=tertiary_link", "link");
createNames(props, "highway=unclassified", "road");
createNames(props, "highway=residential", "road");
createNames(props, "highway=living_street", "road");
createNames(props, "highway=road", "road");
createNames(props, "highway=service", "service road");
createNames(props, "highway=service;service=alley", "alley");
createNames(props, "highway=service;service=parking_aisle", "parking aisle");
createNames(props, "highway=byway", "byway");
createNames(props, "highway=track", "track");
createNames(props, "highway=footway;footway=sidewalk", "sidewalk");
createNames(props, "highway=path;path=sidewalk", "sidewalk");
createNames(props, "highway=steps", "steps");
createNames(props, "amenity=bicycle_rental;name=*", "Bicycle rental {name}");
createNames(props, "amenity=bicycle_rental", "Bicycle rental station");
//slope overrides
props.setSlopeOverride(new OSMSpecifier("bridge=*"), true);
props.setSlopeOverride(new OSMSpecifier("tunnel=*"), true);
return props;
}
|
diff --git a/src/main/java/org/getchunky/chunky/ChunkyManager.java b/src/main/java/org/getchunky/chunky/ChunkyManager.java
index 121f6f5..4bcc671 100644
--- a/src/main/java/org/getchunky/chunky/ChunkyManager.java
+++ b/src/main/java/org/getchunky/chunky/ChunkyManager.java
@@ -1,239 +1,237 @@
package org.getchunky.chunky;
import org.bukkit.block.Block;
import org.getchunky.chunky.persistance.DatabaseManager;
import org.getchunky.chunky.object.*;
import org.getchunky.chunky.permission.ChunkyPermissions;
import org.getchunky.chunky.util.Logging;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
/**
* @author dumptruckman, SwearWord
*/
public class ChunkyManager {
private static HashMap<String, HashMap<String, ChunkyPermissions>> permissions = new HashMap<String, HashMap<String, ChunkyPermissions>>();
private static HashMap<String, HashMap<String,ChunkyObject>> OBJECTS = new HashMap<String, HashMap<String,ChunkyObject>>();
/**
* Allows objects to be registered for lookup by ID. You probably shouldn't call this method as all ChunkyObjects are automatically registered.
*
* @param object ChunkyObject to register
* @return true if object was not yet registered
*/
public static boolean registerObject(ChunkyObject object) {
HashMap<String,ChunkyObject> ids = OBJECTS.get(object.getType());
if (ids==null) {
ids = new HashMap<String, ChunkyObject>();
OBJECTS.put(object.getType(),ids);
}
if(ids.containsKey(object.getId())) return false;
ids.put(object.getId(), object);
return true;
}
/**
* Looks up an object by ID. This method will return null if the object has not been initialized.
*
* @param type Type of object (Class name)
* @param id Object id
* @return Object associated with id or null
*/
public static ChunkyObject getObject(String type, String id) {
HashMap<String, ChunkyObject> ids = getObjectsOfType(type);
if(ids==null) return null;
return ids.get(id);
}
public static ChunkyObject getObject(String fullId) {
String[] typeId = fullId.split(":");
if (typeId.length < 2) return null;
String id = typeId[1];
for (int i = 2; i < typeId.length; i++) {
id += ":" + typeId[i];
}
return getObject(typeId[0], typeId[1]);
}
public static HashMap<String, ChunkyObject> getObjectsOfType(String type) {
return OBJECTS.get(type);
}
/**
* Strips the type from an id and returns just the name.
*
* @param id
* @return
*/
public static String getNameFromId(String id) {
try {
return id.substring(id.indexOf(":") + 1);
} catch (Exception ignore) {
return null;
}
}
/**
* Compares a ChunkyObject id with a class to determine if the id is a for an object of a certain type.
*
* @param id ID of ChunkyObject
* @param type Class for ChunkyObject to compare to
* @return true if ID is for object of class type
*/
public static boolean isType(String id, Class type) {
String typeName = id.substring(0, id.indexOf(":"));
return type.getName().equals(typeName);
}
/**
* Gets a ChunkyPlayer object from the given player name. The given name will first try a case-insensitive match for any online player, and then a case-sensitive match of offline players. If no player is found, null is returned. If a player is found, this will retrieve the ChunkyPlayer instance for them. It will create a new instance if there is no instance already created.
*
* @see org.getchunky.chunky.ChunkyManager#getChunkyPlayer(OfflinePlayer player) for a quicker lookup method.
*
* @param name Name of the player
* @return A ChunkyPlayer object for the given name.
*/
public static ChunkyPlayer getChunkyPlayer(String name)
{
OfflinePlayer player = Bukkit.getServer().getPlayer(name);
if (player == null) {
player = Bukkit.getServer().getPlayerExact(name);
if (player == null) {
player = Bukkit.getServer().getOfflinePlayer(name);
}
}
if (player == null) return null;
return getChunkyPlayer(player);
}
/**
* The preferred method for retrieving a ChunkyPlayer object.
*
* @param player
* @return A ChunkyPlayer object for the given player.
*/
public static ChunkyPlayer getChunkyPlayer(OfflinePlayer player)
{
String id = player.getName();
ChunkyObject chunkyObject = getObject(ChunkyPlayer.class.getName(),id);
if(chunkyObject != null) {
ChunkyPlayer cPlayer = (ChunkyPlayer)chunkyObject;
- /*
HashSet<ChunkyObject> groups = cPlayer.getOwnables().get(ChunkyGroup.class.getName());
ChunkyGroup friends = (ChunkyGroup)new ChunkyGroup().setId(id + "-friends");
- if (!groups.contains(friends)) {
+ if (groups == null || !groups.contains(friends)) {
friends.setName("friends");
friends.setOwner(cPlayer, false, false);
}
- */
return cPlayer;
}
ChunkyPlayer cPlayer = new ChunkyPlayer();
cPlayer.setId(id).setName(id);
ChunkyGroup friends = new ChunkyGroup();
friends.setId(id + "-friends").setName("friends");
friends.setOwner(cPlayer, false, false);
return cPlayer;
}
/**
* Gets the ChunkyChunk associated with the given chunk coordinates
*
* @param coords Chunk coordinates object
* @return ChunkyChunk at the given coordinates
*/
public static ChunkyChunk getChunk(ChunkyCoordinates coords) {
ChunkyObject chunkyObject = getObject(ChunkyChunk.class.getName(),coords.toString());
if(chunkyObject!=null) return (ChunkyChunk)chunkyObject;
ChunkyChunk chunkyChunk = new ChunkyChunk();
chunkyChunk.setCoord(coords).setId(coords.toString());
return chunkyChunk;
}
/**
* Gets the ChunkyChunk associated with the given chunk coordinates
*
* @param location Location of chunk
* @return ChunkyChunk at the given location
*/
public static ChunkyChunk getChunk(Location location)
{
return getChunk(new ChunkyCoordinates(location));
}
/**
* Gets the ChunkyChunk associated with the given chunk coordinates
*
* @param block Block within chunk
* @return ChunkyChunk at the given location
*/
public static ChunkyChunk getChunk(Block block)
{
return getChunk(new ChunkyCoordinates(block.getChunk()));
}
/**
* Gets the permissions object for the permissions relationship between permObjectId and objectId. Altering this permission object will NOT persist changes.
*
* @param objectId Object being interacted with
* @param permObjectId Object doing the interacting
* @return a ChunkyPermissions objectId containing the permissions for this relationship
*/
public static ChunkyPermissions getPermissions(String objectId, String permObjectId) {
if (!permissions.containsKey(objectId)) {
permissions.put(objectId, new HashMap<String, ChunkyPermissions>());
}
HashMap<String, ChunkyPermissions> perms = permissions.get(objectId);
if (!perms.containsKey(permObjectId)) {
perms.put(permObjectId, new ChunkyPermissions());
}
Logging.debug("ChunkyManager.getPermissions() reports perms as: " + perms.get(permObjectId).toString());
return perms.get(permObjectId);
}
/**
* Allows you to set permissions for an object without having the ChunkyObjects. This WILL persist changes.
*
* @param objectId Object being interacted with
* @param permObjectId Object doing the interacting
* @param flags Flag Set to change permissions to
*/
public static void setPermissions(String objectId, String permObjectId, EnumSet<ChunkyPermissions.Flags> flags) {
setPermissions(objectId, permObjectId, flags, true);
}
/**
* Allows you to set permissions for an object without having the ChunkyObjects. This will optionally persist changes.
*
* @param objectId Object being interacted with
* @param permObjectId Object doing the interacting
* @param flags Flag Set to change permissions to
* @param persist Whether or not to persist these changes. Generally you should persist the changes.
*/
public static void setPermissions(String objectId, String permObjectId, EnumSet<ChunkyPermissions.Flags> flags, boolean persist) {
ChunkyManager.getPermissions(objectId, permObjectId).setFlags(flags);
if (persist)
DatabaseManager.getDatabase().updatePermissions(permObjectId, objectId, flags);
}
/**
* Gets a hashmap of all the permissions set on a specific object. Altering this hashmap can potentially screw up persistence. Use with caution!
*
* @param object Object in question
* @return HashMap of object permissions
*/
public static HashMap<String, ChunkyPermissions> getAllPermissions(String object) {
if (!permissions.containsKey(object)) {
permissions.put(object, new HashMap<String, ChunkyPermissions>());
}
return permissions.get(object);
}
}
| false | true | public static ChunkyPlayer getChunkyPlayer(OfflinePlayer player)
{
String id = player.getName();
ChunkyObject chunkyObject = getObject(ChunkyPlayer.class.getName(),id);
if(chunkyObject != null) {
ChunkyPlayer cPlayer = (ChunkyPlayer)chunkyObject;
/*
HashSet<ChunkyObject> groups = cPlayer.getOwnables().get(ChunkyGroup.class.getName());
ChunkyGroup friends = (ChunkyGroup)new ChunkyGroup().setId(id + "-friends");
if (!groups.contains(friends)) {
friends.setName("friends");
friends.setOwner(cPlayer, false, false);
}
*/
return cPlayer;
}
ChunkyPlayer cPlayer = new ChunkyPlayer();
cPlayer.setId(id).setName(id);
ChunkyGroup friends = new ChunkyGroup();
friends.setId(id + "-friends").setName("friends");
friends.setOwner(cPlayer, false, false);
return cPlayer;
}
| public static ChunkyPlayer getChunkyPlayer(OfflinePlayer player)
{
String id = player.getName();
ChunkyObject chunkyObject = getObject(ChunkyPlayer.class.getName(),id);
if(chunkyObject != null) {
ChunkyPlayer cPlayer = (ChunkyPlayer)chunkyObject;
HashSet<ChunkyObject> groups = cPlayer.getOwnables().get(ChunkyGroup.class.getName());
ChunkyGroup friends = (ChunkyGroup)new ChunkyGroup().setId(id + "-friends");
if (groups == null || !groups.contains(friends)) {
friends.setName("friends");
friends.setOwner(cPlayer, false, false);
}
return cPlayer;
}
ChunkyPlayer cPlayer = new ChunkyPlayer();
cPlayer.setId(id).setName(id);
ChunkyGroup friends = new ChunkyGroup();
friends.setId(id + "-friends").setName("friends");
friends.setOwner(cPlayer, false, false);
return cPlayer;
}
|
diff --git a/htroot/index.java b/htroot/index.java
index 84b408a45..3ae718f7a 100644
--- a/htroot/index.java
+++ b/htroot/index.java
@@ -1,158 +1,158 @@
// index.java
// (C) 2004-2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 2004 on http://www.anomic.de
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// LICENSE
//
// 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
//
// You must compile this file with
// javac -classpath .:../classes index.java
// if the shell's current path is HTROOT
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSearchQuery;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
public class index {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
// access control
boolean publicPage = sb.getConfigBool("publicSearchpage", true);
boolean authorizedAccess = sb.verifyAuthentication(header, false);
if ((post != null) && (post.containsKey("publicPage"))) {
if (!authorizedAccess) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
publicPage = post.get("publicPage", "0").equals("1");
sb.setConfig("publicSearchpage", publicPage);
}
boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
final int searchoptions = (post == null) ? 0 : post.getInt("searchoptions", 0);
final String former = (post == null) ? "" : post.get("former", "");
final int count = Math.min(100, (post == null) ? 10 : post.getInt("count", 10));
final int time = Math.min(60, (post == null) ? (int) sb.getConfigLong("network.unit.search.time", 3) : post.getInt("time", (int) sb.getConfigLong("network.unit.search.time", 3)));
final String urlmaskfilter = (post == null) ? ".*" : post.get("urlmaskfilter", ".*");
final String prefermaskfilter = (post == null) ? "" : post.get("prefermaskfilter", "");
- final String constraint = (post == null) ? null : post.get("constraint", null);
+ final String constraint = (post == null) ? "" : post.get("constraint", "");
final String cat = (post == null) ? "href" : post.get("cat", "href");
final int type = (post == null) ? 0 : post.getInt("type", 0);
final boolean indexDistributeGranted = sb.getConfigBool(plasmaSwitchboard.INDEX_DIST_ALLOW, true);
final boolean indexReceiveGranted = sb.getConfigBool(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true);
global = global && indexDistributeGranted && indexReceiveGranted;
/*
final String referer = (String) header.get(httpHeader.REFERER);
if (referer != null) {
yacyURL url;
try {
url = new yacyURL(referer, null);
} catch (MalformedURLException e) {
url = null;
}
if ((url != null) && (!url.isLocal())) {
final HashMap referrerprop = new HashMap();
referrerprop.put("count", "1");
referrerprop.put("clientip", header.get(httpHeader.CONNECTION_PROP_CLIENTIP));
referrerprop.put("useragent", header.get(httpHeader.USER_AGENT));
referrerprop.put("date", (new serverDate()).toShortString(false));
if (sb.facilityDB != null) try {sb.facilityDB.update("backlinks", referer, referrerprop);} catch (IOException e) {}
}
}
*/
// search domain
int contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
String cds = (post == null) ? "text" : post.get("contentdom", "text");
if (cds.equals("text")) contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
if (cds.equals("audio")) contentdom = plasmaSearchQuery.CONTENTDOM_AUDIO;
if (cds.equals("video")) contentdom = plasmaSearchQuery.CONTENTDOM_VIDEO;
if (cds.equals("image")) contentdom = plasmaSearchQuery.CONTENTDOM_IMAGE;
if (cds.equals("app")) contentdom = plasmaSearchQuery.CONTENTDOM_APP;
//long mylinks = 0;
try {
prop.putNum("links", yacyCore.seedDB.mySeed().getLinkCount());
} catch (NumberFormatException e) { prop.putHTML("links", "0"); }
//prop.put("total-links", groupDigits(mylinks + yacyCore.seedDB.countActiveURL())); // extremely time-intensive!
// we create empty entries for template strings
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (env.getConfigBool("promoteSearchPageGreeting.useNetworkName", false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P WEB SEARCH";
prop.putHTML("promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.putHTML("former", former);
prop.put("num-results", "0");
prop.put("excluded", "0");
prop.put("combine", "0");
prop.put("resultbottomline", "0");
prop.put("searchoptions", searchoptions);
prop.put("searchoptions_count-10", (count == 10) ? "1" : "0");
prop.put("searchoptions_count-50", (count == 50) ? "1" : "0");
prop.put("searchoptions_count-100", (count == 100) ? "1" : "0");
prop.put("searchoptions_resource-global", global ? "1" : "0");
prop.put("searchoptions_resource-global-disabled", (indexReceiveGranted && indexDistributeGranted) ? "0" : "1");
prop.put("searchoptions_resource-global-disabled_reason",
(indexReceiveGranted) ? "0" : (indexDistributeGranted ? "1" : "2"));
prop.put("searchoptions_resource-local", global ? "0" : "1");
prop.put("searchoptions_searchtime", time);
prop.put("searchoptions_time-1", (time == 1) ? "1" : "0");
prop.put("searchoptions_time-2", (time == 2) ? "1" : "0");
prop.put("searchoptions_time-3", (time == 3) ? "1" : "0");
prop.put("searchoptions_time-4", (time == 4) ? "1" : "0");
prop.put("searchoptions_time-6", (time == 6) ? "1" : "0");
prop.put("searchoptions_time-8", (time == 8) ? "1" : "0");
prop.put("searchoptions_time-10", (time == 10) ? "1" : "0");
prop.put("searchoptions_urlmaskoptions", "0");
prop.putHTML("searchoptions_urlmaskoptions_urlmaskfilter", urlmaskfilter);
prop.put("searchoptions_prefermaskoptions", "0");
prop.putHTML("searchoptions_prefermaskoptions_prefermaskfilter", prefermaskfilter);
prop.put("searchoptions_indexofChecked", "");
prop.put("searchoptions_publicSearchpage", (publicPage == true) ? "0" : "1");
prop.put("results", "");
prop.put("cat", cat);
prop.put("type", type);
prop.put("depth", "0");
prop.put("display", display);
prop.put("constraint", constraint);
prop.put("searchoptions_display", display);
prop.put("contentdomCheckText", (contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) ? "1" : "0");
prop.put("contentdomCheckAudio", (contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) ? "1" : "0");
prop.put("contentdomCheckVideo", (contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) ? "1" : "0");
prop.put("contentdomCheckImage", (contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) ? "1" : "0");
prop.put("contentdomCheckApp", (contentdom == plasmaSearchQuery.CONTENTDOM_APP) ? "1" : "0");
// online caution timing
sb.localSearchLastAccess = System.currentTimeMillis();
return prop;
}
}
| true | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
// access control
boolean publicPage = sb.getConfigBool("publicSearchpage", true);
boolean authorizedAccess = sb.verifyAuthentication(header, false);
if ((post != null) && (post.containsKey("publicPage"))) {
if (!authorizedAccess) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
publicPage = post.get("publicPage", "0").equals("1");
sb.setConfig("publicSearchpage", publicPage);
}
boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
final int searchoptions = (post == null) ? 0 : post.getInt("searchoptions", 0);
final String former = (post == null) ? "" : post.get("former", "");
final int count = Math.min(100, (post == null) ? 10 : post.getInt("count", 10));
final int time = Math.min(60, (post == null) ? (int) sb.getConfigLong("network.unit.search.time", 3) : post.getInt("time", (int) sb.getConfigLong("network.unit.search.time", 3)));
final String urlmaskfilter = (post == null) ? ".*" : post.get("urlmaskfilter", ".*");
final String prefermaskfilter = (post == null) ? "" : post.get("prefermaskfilter", "");
final String constraint = (post == null) ? null : post.get("constraint", null);
final String cat = (post == null) ? "href" : post.get("cat", "href");
final int type = (post == null) ? 0 : post.getInt("type", 0);
final boolean indexDistributeGranted = sb.getConfigBool(plasmaSwitchboard.INDEX_DIST_ALLOW, true);
final boolean indexReceiveGranted = sb.getConfigBool(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true);
global = global && indexDistributeGranted && indexReceiveGranted;
/*
final String referer = (String) header.get(httpHeader.REFERER);
if (referer != null) {
yacyURL url;
try {
url = new yacyURL(referer, null);
} catch (MalformedURLException e) {
url = null;
}
if ((url != null) && (!url.isLocal())) {
final HashMap referrerprop = new HashMap();
referrerprop.put("count", "1");
referrerprop.put("clientip", header.get(httpHeader.CONNECTION_PROP_CLIENTIP));
referrerprop.put("useragent", header.get(httpHeader.USER_AGENT));
referrerprop.put("date", (new serverDate()).toShortString(false));
if (sb.facilityDB != null) try {sb.facilityDB.update("backlinks", referer, referrerprop);} catch (IOException e) {}
}
}
*/
// search domain
int contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
String cds = (post == null) ? "text" : post.get("contentdom", "text");
if (cds.equals("text")) contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
if (cds.equals("audio")) contentdom = plasmaSearchQuery.CONTENTDOM_AUDIO;
if (cds.equals("video")) contentdom = plasmaSearchQuery.CONTENTDOM_VIDEO;
if (cds.equals("image")) contentdom = plasmaSearchQuery.CONTENTDOM_IMAGE;
if (cds.equals("app")) contentdom = plasmaSearchQuery.CONTENTDOM_APP;
//long mylinks = 0;
try {
prop.putNum("links", yacyCore.seedDB.mySeed().getLinkCount());
} catch (NumberFormatException e) { prop.putHTML("links", "0"); }
//prop.put("total-links", groupDigits(mylinks + yacyCore.seedDB.countActiveURL())); // extremely time-intensive!
// we create empty entries for template strings
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (env.getConfigBool("promoteSearchPageGreeting.useNetworkName", false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P WEB SEARCH";
prop.putHTML("promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.putHTML("former", former);
prop.put("num-results", "0");
prop.put("excluded", "0");
prop.put("combine", "0");
prop.put("resultbottomline", "0");
prop.put("searchoptions", searchoptions);
prop.put("searchoptions_count-10", (count == 10) ? "1" : "0");
prop.put("searchoptions_count-50", (count == 50) ? "1" : "0");
prop.put("searchoptions_count-100", (count == 100) ? "1" : "0");
prop.put("searchoptions_resource-global", global ? "1" : "0");
prop.put("searchoptions_resource-global-disabled", (indexReceiveGranted && indexDistributeGranted) ? "0" : "1");
prop.put("searchoptions_resource-global-disabled_reason",
(indexReceiveGranted) ? "0" : (indexDistributeGranted ? "1" : "2"));
prop.put("searchoptions_resource-local", global ? "0" : "1");
prop.put("searchoptions_searchtime", time);
prop.put("searchoptions_time-1", (time == 1) ? "1" : "0");
prop.put("searchoptions_time-2", (time == 2) ? "1" : "0");
prop.put("searchoptions_time-3", (time == 3) ? "1" : "0");
prop.put("searchoptions_time-4", (time == 4) ? "1" : "0");
prop.put("searchoptions_time-6", (time == 6) ? "1" : "0");
prop.put("searchoptions_time-8", (time == 8) ? "1" : "0");
prop.put("searchoptions_time-10", (time == 10) ? "1" : "0");
prop.put("searchoptions_urlmaskoptions", "0");
prop.putHTML("searchoptions_urlmaskoptions_urlmaskfilter", urlmaskfilter);
prop.put("searchoptions_prefermaskoptions", "0");
prop.putHTML("searchoptions_prefermaskoptions_prefermaskfilter", prefermaskfilter);
prop.put("searchoptions_indexofChecked", "");
prop.put("searchoptions_publicSearchpage", (publicPage == true) ? "0" : "1");
prop.put("results", "");
prop.put("cat", cat);
prop.put("type", type);
prop.put("depth", "0");
prop.put("display", display);
prop.put("constraint", constraint);
prop.put("searchoptions_display", display);
prop.put("contentdomCheckText", (contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) ? "1" : "0");
prop.put("contentdomCheckAudio", (contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) ? "1" : "0");
prop.put("contentdomCheckVideo", (contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) ? "1" : "0");
prop.put("contentdomCheckImage", (contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) ? "1" : "0");
prop.put("contentdomCheckApp", (contentdom == plasmaSearchQuery.CONTENTDOM_APP) ? "1" : "0");
// online caution timing
sb.localSearchLastAccess = System.currentTimeMillis();
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
// access control
boolean publicPage = sb.getConfigBool("publicSearchpage", true);
boolean authorizedAccess = sb.verifyAuthentication(header, false);
if ((post != null) && (post.containsKey("publicPage"))) {
if (!authorizedAccess) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
publicPage = post.get("publicPage", "0").equals("1");
sb.setConfig("publicSearchpage", publicPage);
}
boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
final int searchoptions = (post == null) ? 0 : post.getInt("searchoptions", 0);
final String former = (post == null) ? "" : post.get("former", "");
final int count = Math.min(100, (post == null) ? 10 : post.getInt("count", 10));
final int time = Math.min(60, (post == null) ? (int) sb.getConfigLong("network.unit.search.time", 3) : post.getInt("time", (int) sb.getConfigLong("network.unit.search.time", 3)));
final String urlmaskfilter = (post == null) ? ".*" : post.get("urlmaskfilter", ".*");
final String prefermaskfilter = (post == null) ? "" : post.get("prefermaskfilter", "");
final String constraint = (post == null) ? "" : post.get("constraint", "");
final String cat = (post == null) ? "href" : post.get("cat", "href");
final int type = (post == null) ? 0 : post.getInt("type", 0);
final boolean indexDistributeGranted = sb.getConfigBool(plasmaSwitchboard.INDEX_DIST_ALLOW, true);
final boolean indexReceiveGranted = sb.getConfigBool(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true);
global = global && indexDistributeGranted && indexReceiveGranted;
/*
final String referer = (String) header.get(httpHeader.REFERER);
if (referer != null) {
yacyURL url;
try {
url = new yacyURL(referer, null);
} catch (MalformedURLException e) {
url = null;
}
if ((url != null) && (!url.isLocal())) {
final HashMap referrerprop = new HashMap();
referrerprop.put("count", "1");
referrerprop.put("clientip", header.get(httpHeader.CONNECTION_PROP_CLIENTIP));
referrerprop.put("useragent", header.get(httpHeader.USER_AGENT));
referrerprop.put("date", (new serverDate()).toShortString(false));
if (sb.facilityDB != null) try {sb.facilityDB.update("backlinks", referer, referrerprop);} catch (IOException e) {}
}
}
*/
// search domain
int contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
String cds = (post == null) ? "text" : post.get("contentdom", "text");
if (cds.equals("text")) contentdom = plasmaSearchQuery.CONTENTDOM_TEXT;
if (cds.equals("audio")) contentdom = plasmaSearchQuery.CONTENTDOM_AUDIO;
if (cds.equals("video")) contentdom = plasmaSearchQuery.CONTENTDOM_VIDEO;
if (cds.equals("image")) contentdom = plasmaSearchQuery.CONTENTDOM_IMAGE;
if (cds.equals("app")) contentdom = plasmaSearchQuery.CONTENTDOM_APP;
//long mylinks = 0;
try {
prop.putNum("links", yacyCore.seedDB.mySeed().getLinkCount());
} catch (NumberFormatException e) { prop.putHTML("links", "0"); }
//prop.put("total-links", groupDigits(mylinks + yacyCore.seedDB.countActiveURL())); // extremely time-intensive!
// we create empty entries for template strings
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (env.getConfigBool("promoteSearchPageGreeting.useNetworkName", false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P WEB SEARCH";
prop.putHTML("promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.putHTML("former", former);
prop.put("num-results", "0");
prop.put("excluded", "0");
prop.put("combine", "0");
prop.put("resultbottomline", "0");
prop.put("searchoptions", searchoptions);
prop.put("searchoptions_count-10", (count == 10) ? "1" : "0");
prop.put("searchoptions_count-50", (count == 50) ? "1" : "0");
prop.put("searchoptions_count-100", (count == 100) ? "1" : "0");
prop.put("searchoptions_resource-global", global ? "1" : "0");
prop.put("searchoptions_resource-global-disabled", (indexReceiveGranted && indexDistributeGranted) ? "0" : "1");
prop.put("searchoptions_resource-global-disabled_reason",
(indexReceiveGranted) ? "0" : (indexDistributeGranted ? "1" : "2"));
prop.put("searchoptions_resource-local", global ? "0" : "1");
prop.put("searchoptions_searchtime", time);
prop.put("searchoptions_time-1", (time == 1) ? "1" : "0");
prop.put("searchoptions_time-2", (time == 2) ? "1" : "0");
prop.put("searchoptions_time-3", (time == 3) ? "1" : "0");
prop.put("searchoptions_time-4", (time == 4) ? "1" : "0");
prop.put("searchoptions_time-6", (time == 6) ? "1" : "0");
prop.put("searchoptions_time-8", (time == 8) ? "1" : "0");
prop.put("searchoptions_time-10", (time == 10) ? "1" : "0");
prop.put("searchoptions_urlmaskoptions", "0");
prop.putHTML("searchoptions_urlmaskoptions_urlmaskfilter", urlmaskfilter);
prop.put("searchoptions_prefermaskoptions", "0");
prop.putHTML("searchoptions_prefermaskoptions_prefermaskfilter", prefermaskfilter);
prop.put("searchoptions_indexofChecked", "");
prop.put("searchoptions_publicSearchpage", (publicPage == true) ? "0" : "1");
prop.put("results", "");
prop.put("cat", cat);
prop.put("type", type);
prop.put("depth", "0");
prop.put("display", display);
prop.put("constraint", constraint);
prop.put("searchoptions_display", display);
prop.put("contentdomCheckText", (contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) ? "1" : "0");
prop.put("contentdomCheckAudio", (contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) ? "1" : "0");
prop.put("contentdomCheckVideo", (contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) ? "1" : "0");
prop.put("contentdomCheckImage", (contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) ? "1" : "0");
prop.put("contentdomCheckApp", (contentdom == plasmaSearchQuery.CONTENTDOM_APP) ? "1" : "0");
// online caution timing
sb.localSearchLastAccess = System.currentTimeMillis();
return prop;
}
|
diff --git a/zendserver-sdk-java/org.zend.sdk.cli/sdkcli/org/zend/sdkcli/internal/commands/AddTargetCommand.java b/zendserver-sdk-java/org.zend.sdk.cli/sdkcli/org/zend/sdkcli/internal/commands/AddTargetCommand.java
index 0f350886..5a9be93d 100644
--- a/zendserver-sdk-java/org.zend.sdk.cli/sdkcli/org/zend/sdkcli/internal/commands/AddTargetCommand.java
+++ b/zendserver-sdk-java/org.zend.sdk.cli/sdkcli/org/zend/sdkcli/internal/commands/AddTargetCommand.java
@@ -1,197 +1,201 @@
/*******************************************************************************
* Copyright (c) May 18, 2011 Zend Technologies Ltd.
* 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
*******************************************************************************/
package org.zend.sdkcli.internal.commands;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
import org.zend.sdkcli.internal.options.Option;
import org.zend.sdklib.SdkException;
import org.zend.sdklib.internal.target.ZendDevCloud;
import org.zend.sdklib.manager.TargetsManager;
import org.zend.sdklib.target.IZendTarget;
/**
* Creating a new target
*
* @author Roy, 2011
*/
public class AddTargetCommand extends TargetAwareCommand {
// properties file keys
private static final String PROP_SECRETKEY = "secretkey";
private static final String PROP_KEY = "key";
// options
private static final String ID = "t";
private static final String KEY = "k";
private static final String SECRETKEY = "s";
private static final String HOST = "h";
private static final String PROPERTIES = "p";
private static final String DEVPASS = "d";
private Properties props;
@Option(opt = DEVPASS, required = false, description = "The DevPaas username and password concatenated by a colon", argName = "user:pass")
public String getDevPaas() {
return getValue(DEVPASS);
}
@Option(opt = ID, required = false, description = "id of the new target", argName = "id")
public String getId() {
return getValue(ID);
}
@Option(opt = KEY, required = false, description = "API key used by the new target", argName = PROP_KEY)
public String getKey() {
Properties p = getProperties();
if (p != null) {
return p.getProperty(PROP_KEY);
}
return getValue(KEY);
}
@Option(opt = SECRETKEY, required = false, description = "API secret key used by the new target", argName = "secret-key")
public String getSecretKey() {
Properties p = getProperties();
if (p != null) {
return p.getProperty(PROP_SECRETKEY);
}
return getValue(SECRETKEY);
}
@Option(opt = HOST, required = false, description = "Host URL of the new target", argName = "host")
public String getHost() {
return getValue(HOST);
}
@Option(opt = PROPERTIES, required = false, description = "Properties file specifies 'key' and 'secretkey' values", argName = "path-to-file")
public File getPropertiesFile() {
final String filename = getValue(PROPERTIES);
if (filename == null || filename.length() == 0) {
return null;
}
final File file = new File(filename);
return file;
}
@Override
public boolean doExecute() {
final String targetId = getId();
final String devPaas = getDevPaas();
String key = getKey();
String secretKey = getSecretKey();
String host = getHost();
// resolve devpaas account properties
if (devPaas != null) {
IZendTarget[] targets = resolveTarget(devPaas);
if (targets != null) {
final TargetsManager targetManager = getTargetManager();
String id = targetId != null ? targetId : targetManager
.createUniqueId(null);
int i = 0;
for (IZendTarget zendTarget : targets) {
key = zendTarget.getKey();
secretKey = zendTarget.getSecretKey();
host = zendTarget.getHost().toString();
IZendTarget target = targetManager.createTarget(id + "_"
+ i++, host, key, secretKey);
if (target == null) {
return false;
}
+ getLogger()
+ .info(MessageFormat
+ .format("Target {0} was added successfully, with id {1}",
+ host, target.getId()));
}
return true;
}
}
if (key == null && secretKey == null || host == null) {
getLogger().error(
"To create target it is required to provide hostname, key and secret key. "
+ "It can be provided through a properties file.");
return false;
}
final TargetsManager targetManager = getTargetManager();
IZendTarget target = targetId == null ? targetManager.createTarget(
host, key, secretKey) : targetManager.createTarget(targetId,
host, key, secretKey);
if (target == null) {
return false;
}
getLogger().info(
MessageFormat.format(
"Target {0} was added successfully, with id {1}", host,
target.getId()));
return true;
}
private IZendTarget[] resolveTarget(final String devPaas) {
final ZendDevCloud detect = new ZendDevCloud();
final String[] split = devPaas.split(":");
if (split.length != 2) {
final String message = "Error resolving devpaas account properties: "
+ devPaas
+ ". Argument should include both user and password concatenated by "
+ "colon, for example john.dohe:8hi8Rfe";
getLogger().error(message);
throw new IllegalStateException(message);
}
try {
final IZendTarget[] targets = detect.detectTarget(split[0],
split[1]);
if (targets != null && targets.length > 0) {
return targets;
}
} catch (SdkException e) {
getLogger().error(e);
} catch (IOException e) {
getLogger().error(e);
}
return null;
}
/**
* Reads properties files and return values
*
* @return Properties loaded object
*/
private Properties getProperties() {
if (props == null) {
final File file = getPropertiesFile();
if (file == null) {
return null;
}
try {
Properties p = new Properties();
p.load(new FileInputStream(file));
getLogger().info("Loading file " + file.getAbsolutePath());
props = p;
} catch (FileNotFoundException e) {
getLogger().error("File not found " + file.getAbsolutePath());
} catch (IOException e) {
getLogger().error("Error reading " + file.getAbsolutePath());
}
}
return props;
}
}
| true | true | public boolean doExecute() {
final String targetId = getId();
final String devPaas = getDevPaas();
String key = getKey();
String secretKey = getSecretKey();
String host = getHost();
// resolve devpaas account properties
if (devPaas != null) {
IZendTarget[] targets = resolveTarget(devPaas);
if (targets != null) {
final TargetsManager targetManager = getTargetManager();
String id = targetId != null ? targetId : targetManager
.createUniqueId(null);
int i = 0;
for (IZendTarget zendTarget : targets) {
key = zendTarget.getKey();
secretKey = zendTarget.getSecretKey();
host = zendTarget.getHost().toString();
IZendTarget target = targetManager.createTarget(id + "_"
+ i++, host, key, secretKey);
if (target == null) {
return false;
}
}
return true;
}
}
if (key == null && secretKey == null || host == null) {
getLogger().error(
"To create target it is required to provide hostname, key and secret key. "
+ "It can be provided through a properties file.");
return false;
}
final TargetsManager targetManager = getTargetManager();
IZendTarget target = targetId == null ? targetManager.createTarget(
host, key, secretKey) : targetManager.createTarget(targetId,
host, key, secretKey);
if (target == null) {
return false;
}
getLogger().info(
MessageFormat.format(
"Target {0} was added successfully, with id {1}", host,
target.getId()));
return true;
}
| public boolean doExecute() {
final String targetId = getId();
final String devPaas = getDevPaas();
String key = getKey();
String secretKey = getSecretKey();
String host = getHost();
// resolve devpaas account properties
if (devPaas != null) {
IZendTarget[] targets = resolveTarget(devPaas);
if (targets != null) {
final TargetsManager targetManager = getTargetManager();
String id = targetId != null ? targetId : targetManager
.createUniqueId(null);
int i = 0;
for (IZendTarget zendTarget : targets) {
key = zendTarget.getKey();
secretKey = zendTarget.getSecretKey();
host = zendTarget.getHost().toString();
IZendTarget target = targetManager.createTarget(id + "_"
+ i++, host, key, secretKey);
if (target == null) {
return false;
}
getLogger()
.info(MessageFormat
.format("Target {0} was added successfully, with id {1}",
host, target.getId()));
}
return true;
}
}
if (key == null && secretKey == null || host == null) {
getLogger().error(
"To create target it is required to provide hostname, key and secret key. "
+ "It can be provided through a properties file.");
return false;
}
final TargetsManager targetManager = getTargetManager();
IZendTarget target = targetId == null ? targetManager.createTarget(
host, key, secretKey) : targetManager.createTarget(targetId,
host, key, secretKey);
if (target == null) {
return false;
}
getLogger().info(
MessageFormat.format(
"Target {0} was added successfully, with id {1}", host,
target.getId()));
return true;
}
|
diff --git a/android/src/com/google/zxing/client/android/clipboard/ClipboardInterface.java b/android/src/com/google/zxing/client/android/clipboard/ClipboardInterface.java
index 08e063ac..809fcd90 100644
--- a/android/src/com/google/zxing/client/android/clipboard/ClipboardInterface.java
+++ b/android/src/com/google/zxing/client/android/clipboard/ClipboardInterface.java
@@ -1,58 +1,61 @@
/*
* Copyright (C) 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.clipboard;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.util.Log;
public final class ClipboardInterface {
private static final String TAG = ClipboardInterface.class.getSimpleName();
private ClipboardInterface() {
}
public static CharSequence getText(Context context) {
ClipboardManager clipboard = getManager(context);
ClipData clip = clipboard.getPrimaryClip();
return hasText(context) ? clip.getItemAt(0).coerceToText(context) : null;
}
public static void setText(CharSequence text, Context context) {
if (text != null) {
try {
getManager(context).setPrimaryClip(ClipData.newPlainText(null, text));
} catch (NullPointerException npe) {
// Have seen this in the wild, bizarrely
Log.w(TAG, "Clipboard bug", npe);
+ } catch (IllegalStateException ise) {
+ // java.lang.IllegalStateException: beginBroadcast() called while already in a broadcast
+ Log.w(TAG, "Clipboard bug", ise);
}
}
}
public static boolean hasText(Context context) {
ClipboardManager clipboard = getManager(context);
ClipData clip = clipboard.getPrimaryClip();
return clip != null && clip.getItemCount() > 0;
}
private static ClipboardManager getManager(Context context) {
return (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
}
}
| true | true | public static void setText(CharSequence text, Context context) {
if (text != null) {
try {
getManager(context).setPrimaryClip(ClipData.newPlainText(null, text));
} catch (NullPointerException npe) {
// Have seen this in the wild, bizarrely
Log.w(TAG, "Clipboard bug", npe);
}
}
}
| public static void setText(CharSequence text, Context context) {
if (text != null) {
try {
getManager(context).setPrimaryClip(ClipData.newPlainText(null, text));
} catch (NullPointerException npe) {
// Have seen this in the wild, bizarrely
Log.w(TAG, "Clipboard bug", npe);
} catch (IllegalStateException ise) {
// java.lang.IllegalStateException: beginBroadcast() called while already in a broadcast
Log.w(TAG, "Clipboard bug", ise);
}
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java
index cef410af..bd59bd23 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java
@@ -1,40 +1,40 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.User;
public class Commandtpaccept extends EssentialsCommand
{
public Commandtpaccept()
{
super("tpaccept");
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
User p = user.getTeleportRequest();
if (p == null)
{
throw new Exception("You do not have a pending request.");
}
if (user.isTeleportRequestHere())
{
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
user.getTeleport().teleport(p, this.getName());
}
else
{
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
- user.getTeleport().teleport(user, this.getName());
+ p.getTeleport().teleport(user, this.getName());
}
user.requestTeleport(null, false);
}
}
| true | true | public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
User p = user.getTeleportRequest();
if (p == null)
{
throw new Exception("You do not have a pending request.");
}
if (user.isTeleportRequestHere())
{
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
user.getTeleport().teleport(p, this.getName());
}
else
{
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
user.getTeleport().teleport(user, this.getName());
}
user.requestTeleport(null, false);
}
| public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
User p = user.getTeleportRequest();
if (p == null)
{
throw new Exception("You do not have a pending request.");
}
if (user.isTeleportRequestHere())
{
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
user.getTeleport().teleport(p, this.getName());
}
else
{
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
p.getTeleport().teleport(user, this.getName());
}
user.requestTeleport(null, false);
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/permission/FlatFilePermissions.java b/src/FE_SRC_COMMON/com/ForgeEssentials/permission/FlatFilePermissions.java
index cc271cb73..ac5840b89 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/permission/FlatFilePermissions.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/permission/FlatFilePermissions.java
@@ -1,89 +1,89 @@
package com.ForgeEssentials.permission;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import net.minecraftforge.common.ConfigCategory;
import net.minecraftforge.common.Configuration;
public class FlatFilePermissions
{
File file;
public FlatFilePermissions(File file)
{
this.file = new File(file, "permissions.txt");
}
public HashMap<String, ArrayList<PermissionHolder>> load()
{
ArrayList<PermissionHolder> group = new ArrayList<PermissionHolder>();
ArrayList<PermissionHolder> player = new ArrayList<PermissionHolder>();
// TODO: load
HashMap<String, ArrayList<PermissionHolder>> map = new HashMap<String, ArrayList<PermissionHolder>>();
map.put("player", player);
map.put("group", group);
return map;
}
public void save(ArrayList<PermissionHolder> players, ArrayList<PermissionHolder> groups)
{
// clear it.
if (file.exists())
file.delete();
Configuration config = new Configuration(file);
for (PermissionHolder holder : players)
{
- config.get(holder.zone + ".group." + holder.target, holder.name, holder.allowed);
+ config.get(holder.zone + ".player." + holder.target, holder.name, holder.allowed);
}
for (PermissionHolder holder : groups)
{
config.get(holder.zone + ".group." + holder.target, holder.name, holder.allowed);
}
config.addCustomCategoryComment("GLOBAL.group."+PermissionsAPI.DEFAULT.name, "The group used to as a placeholder for zone flags and such.");
config.save();
}
private ArrayList<String> getCategoryChildren(Configuration config, ConfigCategory category)
{
ArrayList<String> categories = new ArrayList<String>();
for (ConfigCategory cat : config.categories.values())
{
if (!cat.isChild())
{
continue;
}
if (cat.getQualifiedName().startsWith(category.getQualifiedName()))
{
categories.add(cat.getQualifiedName());
}
}
return categories;
}
private String getPlayerNameFromCategory(String qualifiedName)
{
String[] names = qualifiedName.split("\\" + Configuration.CATEGORY_SPLITTER);
if (names.length == 0)
{
return qualifiedName;
}
else
{
return names[names.length - 1];
}
}
}
| true | true | public void save(ArrayList<PermissionHolder> players, ArrayList<PermissionHolder> groups)
{
// clear it.
if (file.exists())
file.delete();
Configuration config = new Configuration(file);
for (PermissionHolder holder : players)
{
config.get(holder.zone + ".group." + holder.target, holder.name, holder.allowed);
}
for (PermissionHolder holder : groups)
{
config.get(holder.zone + ".group." + holder.target, holder.name, holder.allowed);
}
config.addCustomCategoryComment("GLOBAL.group."+PermissionsAPI.DEFAULT.name, "The group used to as a placeholder for zone flags and such.");
config.save();
}
| public void save(ArrayList<PermissionHolder> players, ArrayList<PermissionHolder> groups)
{
// clear it.
if (file.exists())
file.delete();
Configuration config = new Configuration(file);
for (PermissionHolder holder : players)
{
config.get(holder.zone + ".player." + holder.target, holder.name, holder.allowed);
}
for (PermissionHolder holder : groups)
{
config.get(holder.zone + ".group." + holder.target, holder.name, holder.allowed);
}
config.addCustomCategoryComment("GLOBAL.group."+PermissionsAPI.DEFAULT.name, "The group used to as a placeholder for zone flags and such.");
config.save();
}
|
diff --git a/test/org/siraya/rent/user/dao/TestIUserDAO.java b/test/org/siraya/rent/user/dao/TestIUserDAO.java
index c08ca09..649562a 100755
--- a/test/org/siraya/rent/user/dao/TestIUserDAO.java
+++ b/test/org/siraya/rent/user/dao/TestIUserDAO.java
@@ -1,45 +1,45 @@
package org.siraya.rent.user.dao;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.siraya.rent.user.dao.IUserDAO;
import org.siraya.rent.pojo.User;
@ContextConfiguration(locations = {"classpath*:/applicationContext.xml","classpath*:/applicationContext-mybatis.xml"})
public class TestIUserDAO extends AbstractJUnit4SpringContextTests{
@Autowired
private IUserDAO userDao;
@Before
public void setUp(){
}
@Test
public void testCRUD(){
User user=new User();
long time=java.util.Calendar.getInstance().getTimeInMillis();
String loginId="loginid"+time;
String mobilePhone=Long.toString(time/1000);
user.setId("id"+time);
- user.setLoginType(0);
+ user.setLoginType("xx");
user.setMobilePhone(mobilePhone);
user.setCreated(time/1000);
user.setStatus(0);
user.setLoginId(loginId);
user.setModified(time/1000);
userDao.newUser(user);
String email = "[email protected]";
user.setEmail(email);
userDao.updateUserEmail(user);
User user2 = userDao.getUserByLoginIdAndLoginType(loginId, 0);
User user3 = userDao.getUserByMobilePhone(mobilePhone);
Assert.assertEquals(user.getId(),user2.getId());
Assert.assertEquals(email,user2.getEmail());
Assert.assertEquals(email,user3.getEmail());
}
}
| true | true | public void testCRUD(){
User user=new User();
long time=java.util.Calendar.getInstance().getTimeInMillis();
String loginId="loginid"+time;
String mobilePhone=Long.toString(time/1000);
user.setId("id"+time);
user.setLoginType(0);
user.setMobilePhone(mobilePhone);
user.setCreated(time/1000);
user.setStatus(0);
user.setLoginId(loginId);
user.setModified(time/1000);
userDao.newUser(user);
String email = "[email protected]";
user.setEmail(email);
userDao.updateUserEmail(user);
User user2 = userDao.getUserByLoginIdAndLoginType(loginId, 0);
User user3 = userDao.getUserByMobilePhone(mobilePhone);
Assert.assertEquals(user.getId(),user2.getId());
Assert.assertEquals(email,user2.getEmail());
Assert.assertEquals(email,user3.getEmail());
}
| public void testCRUD(){
User user=new User();
long time=java.util.Calendar.getInstance().getTimeInMillis();
String loginId="loginid"+time;
String mobilePhone=Long.toString(time/1000);
user.setId("id"+time);
user.setLoginType("xx");
user.setMobilePhone(mobilePhone);
user.setCreated(time/1000);
user.setStatus(0);
user.setLoginId(loginId);
user.setModified(time/1000);
userDao.newUser(user);
String email = "[email protected]";
user.setEmail(email);
userDao.updateUserEmail(user);
User user2 = userDao.getUserByLoginIdAndLoginType(loginId, 0);
User user3 = userDao.getUserByMobilePhone(mobilePhone);
Assert.assertEquals(user.getId(),user2.getId());
Assert.assertEquals(email,user2.getEmail());
Assert.assertEquals(email,user3.getEmail());
}
|
diff --git a/ananya-reference-data-contact-center/src/main/java/org/motechproject/ananya/referencedata/contactCenter/validator/LocationWebRequestValidator.java b/ananya-reference-data-contact-center/src/main/java/org/motechproject/ananya/referencedata/contactCenter/validator/LocationWebRequestValidator.java
index 1d1d599..dfdf157 100644
--- a/ananya-reference-data-contact-center/src/main/java/org/motechproject/ananya/referencedata/contactCenter/validator/LocationWebRequestValidator.java
+++ b/ananya-reference-data-contact-center/src/main/java/org/motechproject/ananya/referencedata/contactCenter/validator/LocationWebRequestValidator.java
@@ -1,25 +1,25 @@
package org.motechproject.ananya.referencedata.contactCenter.validator;
import org.apache.commons.lang.StringUtils;
import org.motechproject.ananya.referencedata.flw.request.LocationRequest;
import org.motechproject.ananya.referencedata.flw.validators.Errors;
public class LocationWebRequestValidator {
public static Errors validate(LocationRequest locationRequest) {
Errors errors = new Errors();
if (locationRequest == null) {
errors.add("location field is blank");
return errors;
}
if (StringUtils.isEmpty(locationRequest.getDistrict()))
errors.add("district field is blank");
- if (StringUtils.isEmpty(locationRequest.getDistrict()))
+ if (StringUtils.isEmpty(locationRequest.getBlock()))
errors.add("block field is blank");
- if (StringUtils.isEmpty(locationRequest.getDistrict()))
+ if (StringUtils.isEmpty(locationRequest.getPanchayat()))
errors.add("panchayat field is blank");
return errors;
}
}
| false | true | public static Errors validate(LocationRequest locationRequest) {
Errors errors = new Errors();
if (locationRequest == null) {
errors.add("location field is blank");
return errors;
}
if (StringUtils.isEmpty(locationRequest.getDistrict()))
errors.add("district field is blank");
if (StringUtils.isEmpty(locationRequest.getDistrict()))
errors.add("block field is blank");
if (StringUtils.isEmpty(locationRequest.getDistrict()))
errors.add("panchayat field is blank");
return errors;
}
| public static Errors validate(LocationRequest locationRequest) {
Errors errors = new Errors();
if (locationRequest == null) {
errors.add("location field is blank");
return errors;
}
if (StringUtils.isEmpty(locationRequest.getDistrict()))
errors.add("district field is blank");
if (StringUtils.isEmpty(locationRequest.getBlock()))
errors.add("block field is blank");
if (StringUtils.isEmpty(locationRequest.getPanchayat()))
errors.add("panchayat field is blank");
return errors;
}
|
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java
index 034b13bc..7ed23c96 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/agentrestart/AutoRestartAgentDisabledTest.java
@@ -1,57 +1,57 @@
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon.agentrestart;
import java.util.concurrent.TimeUnit;
import iTests.framework.utils.LogUtils;
import iTests.framework.utils.MavenUtils;
import iTests.framework.utils.SSHUtils;
import org.cloudifysource.dsl.utils.IPUtils;
import org.openspaces.admin.pu.ProcessingUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class AutoRestartAgentDisabledTest extends AbstractAgentMaintenanceModeTest {
private static final String LIST_CRONTAB_TASKS = "crontab -l";
@BeforeClass(alwaysRun = true)
protected void bootstrap() throws Exception {
super.bootstrap();
}
@Test(timeOut = DEFAULT_TEST_TIMEOUT * 4, enabled = true)
public void testRestartAgentDisabled() throws Exception {
final ProcessingUnit pu = admin.getProcessingUnits()
.waitFor("rest", DEFAULT_WAIT_MINUTES, TimeUnit.MINUTES);
pu.waitFor(1);
final String hostName = pu.getInstances()[0].getMachine().getHostName();
final String ip = IPUtils.resolveHostNameToIp(hostName);
LogUtils.log("listing all crontab scheduled tasks");
- final String output = SSHUtils.runCommand(ip, DEFAULT_TEST_TIMEOUT / 2,
- LIST_CRONTAB_TASKS,
- MavenUtils.username,
- MavenUtils.password, true);
+ final String output = SSHUtils.runCommand(ip, DEFAULT_TEST_TIMEOUT / 2,
+ LIST_CRONTAB_TASKS,
+ MavenUtils.username,
+ MavenUtils.password);
LogUtils.log(output);
assertTrue("crontab contains auto restart agent task",
!output.contains("@reboot nohup /tmp/tgrid/gigaspaces/tools/cli/cloudify.sh start-management"));
}
@Override
protected void customizeCloud() throws Exception {
super.customizeCloud();
getService().setSudo(false);
getService().getProperties().put("keyFile", "testKey.pem");
getService().getAdditionalPropsToReplace().put("autoRestartAgent true", "autoRestartAgent false");
}
@Override
@AfterClass(alwaysRun = true)
protected void teardown() throws Exception {
uninstallServiceIfFound(SERVICE_NAME);
super.teardown();
}
}
| true | true | public void testRestartAgentDisabled() throws Exception {
final ProcessingUnit pu = admin.getProcessingUnits()
.waitFor("rest", DEFAULT_WAIT_MINUTES, TimeUnit.MINUTES);
pu.waitFor(1);
final String hostName = pu.getInstances()[0].getMachine().getHostName();
final String ip = IPUtils.resolveHostNameToIp(hostName);
LogUtils.log("listing all crontab scheduled tasks");
final String output = SSHUtils.runCommand(ip, DEFAULT_TEST_TIMEOUT / 2,
LIST_CRONTAB_TASKS,
MavenUtils.username,
MavenUtils.password, true);
LogUtils.log(output);
assertTrue("crontab contains auto restart agent task",
!output.contains("@reboot nohup /tmp/tgrid/gigaspaces/tools/cli/cloudify.sh start-management"));
}
| public void testRestartAgentDisabled() throws Exception {
final ProcessingUnit pu = admin.getProcessingUnits()
.waitFor("rest", DEFAULT_WAIT_MINUTES, TimeUnit.MINUTES);
pu.waitFor(1);
final String hostName = pu.getInstances()[0].getMachine().getHostName();
final String ip = IPUtils.resolveHostNameToIp(hostName);
LogUtils.log("listing all crontab scheduled tasks");
final String output = SSHUtils.runCommand(ip, DEFAULT_TEST_TIMEOUT / 2,
LIST_CRONTAB_TASKS,
MavenUtils.username,
MavenUtils.password);
LogUtils.log(output);
assertTrue("crontab contains auto restart agent task",
!output.contains("@reboot nohup /tmp/tgrid/gigaspaces/tools/cli/cloudify.sh start-management"));
}
|
diff --git a/remote/client/src/java/org/openqa/selenium/remote/ErrorHandler.java b/remote/client/src/java/org/openqa/selenium/remote/ErrorHandler.java
index 1bf81c5b5..f85f6b564 100644
--- a/remote/client/src/java/org/openqa/selenium/remote/ErrorHandler.java
+++ b/remote/client/src/java/org/openqa/selenium/remote/ErrorHandler.java
@@ -1,227 +1,227 @@
package org.openqa.selenium.remote;
import org.openqa.selenium.WebDriverException;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import static org.openqa.selenium.remote.ErrorCodes.SUCCESS;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
/**
* Maps exceptions to status codes for sending over the wire.
*
* @author [email protected] (Jason Leyba)
*/
public class ErrorHandler {
private static final String MESSAGE = "message";
private static final String SCREEN_SHOT = "screen";
private static final String CLASS = "class";
private static final String STACK_TRACE = "stackTrace";
private static final String LINE_NUMBER = "lineNumber";
private static final String METHOD_NAME = "methodName";
private static final String CLASS_NAME = "className";
private static final String FILE_NAME = "fileName";
private static final String UNKNOWN_CLASS = "<anonymous class>";
private static final String UNKNOWN_METHOD = "<anonymous method>";
private static final String UNKNOWN_FILE = "<unknown file>";
private final ErrorCodes errorCodes = new ErrorCodes();
private boolean includeServerErrors;
public ErrorHandler() {
this(false);
}
/**
* @param includeServerErrors Whether to include server-side details in thrown
* exceptions if the information is available.
*/
public ErrorHandler(boolean includeServerErrors) {
this.includeServerErrors = includeServerErrors;
}
public boolean isIncludeServerErrors() {
return includeServerErrors;
}
public void setIncludeServerErrors(boolean includeServerErrors) {
this.includeServerErrors = includeServerErrors;
}
@SuppressWarnings({"unchecked", "ThrowableInstanceNeverThrown"})
public Response throwIfResponseFailed(Response response) throws RuntimeException {
if (response.getStatus() == SUCCESS) {
return response;
}
Class<? extends RuntimeException> outerErrorType =
errorCodes.getExceptionType(response.getStatus());
Object value = response.getValue();
String message = null;
Throwable cause = null;
if (!(value instanceof Map)) {
message = value == null ? null : String.valueOf(value);
} else {
Map<String, Object> rawErrorData;
try {
rawErrorData = (Map<String, Object>) response.getValue();
message = (String) rawErrorData.get(MESSAGE);
if (includeServerErrors) {
cause = rebuildServerError(rawErrorData);
}
if (rawErrorData.containsKey(SCREEN_SHOT)) {
cause = new ScreenshotException((String) rawErrorData.get(SCREEN_SHOT), cause);
}
} catch (ClassCastException e) {
// Ok, try to recover gracefully
message = String.valueOf(value);
}
}
if (cause == null) {
// The stacktrace from the server was unavailable or could not be
// deserialized.
// In this case, the stacktrace will be pointless - it will point to the
// exception as generated from this class, which is technically correct
// but utterly useless. Let the user know that.
message = message + " (Note: The stack trace from the server side " +
- "is missing. The locally-generated stack trace is useless.)";
+ "is missing. The following stack trace is locally generated.)";
}
Throwable toThrow = null;
try {
Constructor<? extends Throwable> constructor =
outerErrorType.getConstructor(String.class, Throwable.class);
toThrow = constructor.newInstance(message, cause);
} catch (Exception e) {
// Fine. fall through
} catch (OutOfMemoryError error) {
// It can happen...
}
if (toThrow == null) {
try {
Constructor<? extends Throwable> constructor =
outerErrorType.getConstructor(String.class);
toThrow = constructor.newInstance(message);
} catch (Exception e) {
// Fine. fall through
} catch (OutOfMemoryError error) {
// It can happen...
}
}
if (toThrow == null) {
throw new WebDriverException(message, cause);
}
if (!(toThrow instanceof RuntimeException)) {
throw new RuntimeException(toThrow);
}
throw (RuntimeException) toThrow;
}
private Throwable rebuildServerError(Map<String, Object> rawErrorData) {
if (!rawErrorData.containsKey(CLASS) && !rawErrorData.containsKey(STACK_TRACE)) {
// Not enough information for us to try to rebuild an error.
return null;
}
Throwable toReturn = null;
String message = (String) rawErrorData.get(MESSAGE);
if (rawErrorData.containsKey(CLASS)) {
String className = (String) rawErrorData.get(CLASS);
try {
Class clazz = Class.forName(className);
if (Throwable.class.isAssignableFrom(clazz)) {
@SuppressWarnings({"unchecked"})
Class<? extends Throwable> throwableType = (Class<? extends Throwable>) clazz;
Constructor<? extends Throwable> constructor =
throwableType.getConstructor(String.class);
toReturn = constructor.newInstance(message);
}
} catch (ClassNotFoundException ignored) {
// Ok, fall-through
} catch (InvocationTargetException e) {
// Ok, fall-through
} catch (NoSuchMethodException e) {
// Ok, fall-through
} catch (InstantiationException e) {
// Ok, fall-through
} catch (IllegalAccessException e) {
// Ok, fall-through
}
}
if (toReturn == null) {
toReturn = new UnknownServerException(message);
}
StackTraceElement[] stackTrace = new StackTraceElement[0];
if (rawErrorData.containsKey(STACK_TRACE)) {
@SuppressWarnings({"unchecked"})
List<Map<String, Object>> stackTraceInfo =
(List<Map<String, Object>>) rawErrorData.get(STACK_TRACE);
Iterable<StackTraceElement> stackFrames =
Iterables.transform(stackTraceInfo, new FrameInfoToStackFrame());
stackFrames = Iterables.filter(stackFrames, Predicates.notNull());
stackTrace = Iterables.toArray(stackFrames, StackTraceElement.class);
}
toReturn.setStackTrace(stackTrace);
return toReturn;
}
/**
* Exception used as a place holder if the server returns an error without a
* stack trace.
*/
public static class UnknownServerException extends WebDriverException {
private UnknownServerException(String s) {
super(s);
}
}
/**
* Function that can rebuild a {@link StackTraceElement} from the frame info
* included with a WebDriver JSON response.
*/
private static class FrameInfoToStackFrame
implements Function<Map<String, Object>, StackTraceElement> {
public StackTraceElement apply(Map<String, Object> frameInfo) {
if (frameInfo == null) {
return null;
}
Number lineNumber = (Number) frameInfo.get(LINE_NUMBER);
if (lineNumber == null) {
return null;
}
// Gracefully handle remote servers that don't (or can't) send back
// complete stack trace info. At least some of this information should
// be included...
String className = frameInfo.containsKey(CLASS_NAME)
? String.valueOf(frameInfo.get(CLASS_NAME)) : UNKNOWN_CLASS;
String methodName = frameInfo.containsKey(METHOD_NAME)
? String.valueOf(frameInfo.get(METHOD_NAME)) : UNKNOWN_METHOD;
String fileName = frameInfo.containsKey(FILE_NAME)
? String.valueOf(frameInfo.get(FILE_NAME)) : UNKNOWN_FILE;
return new StackTraceElement(className, methodName, fileName,
lineNumber.intValue());
}
}
}
| true | true | public Response throwIfResponseFailed(Response response) throws RuntimeException {
if (response.getStatus() == SUCCESS) {
return response;
}
Class<? extends RuntimeException> outerErrorType =
errorCodes.getExceptionType(response.getStatus());
Object value = response.getValue();
String message = null;
Throwable cause = null;
if (!(value instanceof Map)) {
message = value == null ? null : String.valueOf(value);
} else {
Map<String, Object> rawErrorData;
try {
rawErrorData = (Map<String, Object>) response.getValue();
message = (String) rawErrorData.get(MESSAGE);
if (includeServerErrors) {
cause = rebuildServerError(rawErrorData);
}
if (rawErrorData.containsKey(SCREEN_SHOT)) {
cause = new ScreenshotException((String) rawErrorData.get(SCREEN_SHOT), cause);
}
} catch (ClassCastException e) {
// Ok, try to recover gracefully
message = String.valueOf(value);
}
}
if (cause == null) {
// The stacktrace from the server was unavailable or could not be
// deserialized.
// In this case, the stacktrace will be pointless - it will point to the
// exception as generated from this class, which is technically correct
// but utterly useless. Let the user know that.
message = message + " (Note: The stack trace from the server side " +
"is missing. The locally-generated stack trace is useless.)";
}
Throwable toThrow = null;
try {
Constructor<? extends Throwable> constructor =
outerErrorType.getConstructor(String.class, Throwable.class);
toThrow = constructor.newInstance(message, cause);
} catch (Exception e) {
// Fine. fall through
} catch (OutOfMemoryError error) {
// It can happen...
}
if (toThrow == null) {
try {
Constructor<? extends Throwable> constructor =
outerErrorType.getConstructor(String.class);
toThrow = constructor.newInstance(message);
} catch (Exception e) {
// Fine. fall through
} catch (OutOfMemoryError error) {
// It can happen...
}
}
if (toThrow == null) {
throw new WebDriverException(message, cause);
}
if (!(toThrow instanceof RuntimeException)) {
throw new RuntimeException(toThrow);
}
throw (RuntimeException) toThrow;
}
| public Response throwIfResponseFailed(Response response) throws RuntimeException {
if (response.getStatus() == SUCCESS) {
return response;
}
Class<? extends RuntimeException> outerErrorType =
errorCodes.getExceptionType(response.getStatus());
Object value = response.getValue();
String message = null;
Throwable cause = null;
if (!(value instanceof Map)) {
message = value == null ? null : String.valueOf(value);
} else {
Map<String, Object> rawErrorData;
try {
rawErrorData = (Map<String, Object>) response.getValue();
message = (String) rawErrorData.get(MESSAGE);
if (includeServerErrors) {
cause = rebuildServerError(rawErrorData);
}
if (rawErrorData.containsKey(SCREEN_SHOT)) {
cause = new ScreenshotException((String) rawErrorData.get(SCREEN_SHOT), cause);
}
} catch (ClassCastException e) {
// Ok, try to recover gracefully
message = String.valueOf(value);
}
}
if (cause == null) {
// The stacktrace from the server was unavailable or could not be
// deserialized.
// In this case, the stacktrace will be pointless - it will point to the
// exception as generated from this class, which is technically correct
// but utterly useless. Let the user know that.
message = message + " (Note: The stack trace from the server side " +
"is missing. The following stack trace is locally generated.)";
}
Throwable toThrow = null;
try {
Constructor<? extends Throwable> constructor =
outerErrorType.getConstructor(String.class, Throwable.class);
toThrow = constructor.newInstance(message, cause);
} catch (Exception e) {
// Fine. fall through
} catch (OutOfMemoryError error) {
// It can happen...
}
if (toThrow == null) {
try {
Constructor<? extends Throwable> constructor =
outerErrorType.getConstructor(String.class);
toThrow = constructor.newInstance(message);
} catch (Exception e) {
// Fine. fall through
} catch (OutOfMemoryError error) {
// It can happen...
}
}
if (toThrow == null) {
throw new WebDriverException(message, cause);
}
if (!(toThrow instanceof RuntimeException)) {
throw new RuntimeException(toThrow);
}
throw (RuntimeException) toThrow;
}
|
diff --git a/src/main/java/algorithm/cc150/chapter18/Question2.java b/src/main/java/algorithm/cc150/chapter18/Question2.java
index ae3a6d9..27129da 100644
--- a/src/main/java/algorithm/cc150/chapter18/Question2.java
+++ b/src/main/java/algorithm/cc150/chapter18/Question2.java
@@ -1,22 +1,22 @@
package algorithm.cc150.chapter18;
import java.util.Random;
/**
* Implement the perfect random shuffle of the (52) cards.
*
*/
public class Question2 {
public void perfectShuffle(int[] cards) {
// write implementation here
Random rnd = new Random();
- for (int i = 0; i < cards.length; ++i) {
- int idx = rnd.nextInt(i + 1);
+ for (int i = 1; i < cards.length; ++i) {
+ int idx = rnd.nextInt(i);
int tmp = cards[idx];
cards[idx] = cards[i];
cards[i] = tmp;
}
}
}
| true | true | public void perfectShuffle(int[] cards) {
// write implementation here
Random rnd = new Random();
for (int i = 0; i < cards.length; ++i) {
int idx = rnd.nextInt(i + 1);
int tmp = cards[idx];
cards[idx] = cards[i];
cards[i] = tmp;
}
}
| public void perfectShuffle(int[] cards) {
// write implementation here
Random rnd = new Random();
for (int i = 1; i < cards.length; ++i) {
int idx = rnd.nextInt(i);
int tmp = cards[idx];
cards[idx] = cards[i];
cards[i] = tmp;
}
}
|
diff --git a/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java b/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java
index bc9d9bd..3df9a53 100644
--- a/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java
+++ b/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java
@@ -1,144 +1,144 @@
package net.appositedesigns.fileexplorer.quickactions;
import java.io.File;
import net.appositedesigns.fileexplorer.FileExplorerMain;
import net.appositedesigns.fileexplorer.FileListEntry;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.util.FileActionsHelper;
import net.appositedesigns.fileexplorer.util.PreferenceUtil;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
public final class QuickActionHelper {
private FileExplorerMain mContext;
public QuickActionHelper(FileExplorerMain mContext) {
super();
this.mContext = mContext;
}
public void showQuickActions(final ImageView view, final FileListEntry entry) {
final File file = entry.getPath();
final QuickAction actions = new QuickAction(view);
int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext);
- if(new PreferenceUtil(mContext).getTheme() == android.R.style.Theme_Black_NoTitleBar_Fullscreen)
+ if(new PreferenceUtil(mContext).getTheme() == android.R.style.Theme_Black_NoTitleBar)
{
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions_glow));
}
else
{
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions_blu));
}
ActionItem action = null;
for(int i=0;i<availableActions.length;i++)
{
int a = availableActions[i];
action = null;
switch (a) {
case R.string.action_cut:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.cutFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_copy:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.copyFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_delete:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete));
action.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
actions.dismiss();
FileActionsHelper.deleteFile(file, mContext);
}
});
break;
case R.string.action_share:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
actions.dismiss();
FileActionsHelper.share(file, mContext);
}
});
break;
case R.string.action_zip:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_zip));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
actions.dismiss();
FileActionsHelper.zip(file, mContext);
}
});
break;
default:
break;
}
if(action!=null)
{
actions.addActionItem(action);
}
}
if(availableActions.length>0)
{
actions.setAnimStyle(QuickAction.ANIM_AUTO);
actions.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions));
}
});
actions.show();
}
}
}
| true | true | public void showQuickActions(final ImageView view, final FileListEntry entry) {
final File file = entry.getPath();
final QuickAction actions = new QuickAction(view);
int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext);
if(new PreferenceUtil(mContext).getTheme() == android.R.style.Theme_Black_NoTitleBar_Fullscreen)
{
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions_glow));
}
else
{
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions_blu));
}
ActionItem action = null;
for(int i=0;i<availableActions.length;i++)
{
int a = availableActions[i];
action = null;
switch (a) {
case R.string.action_cut:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.cutFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_copy:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.copyFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_delete:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete));
action.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
actions.dismiss();
FileActionsHelper.deleteFile(file, mContext);
}
});
break;
case R.string.action_share:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
actions.dismiss();
FileActionsHelper.share(file, mContext);
}
});
break;
case R.string.action_zip:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_zip));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
actions.dismiss();
FileActionsHelper.zip(file, mContext);
}
});
break;
default:
break;
}
if(action!=null)
{
actions.addActionItem(action);
}
}
if(availableActions.length>0)
{
actions.setAnimStyle(QuickAction.ANIM_AUTO);
actions.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions));
}
});
actions.show();
}
}
| public void showQuickActions(final ImageView view, final FileListEntry entry) {
final File file = entry.getPath();
final QuickAction actions = new QuickAction(view);
int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext);
if(new PreferenceUtil(mContext).getTheme() == android.R.style.Theme_Black_NoTitleBar)
{
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions_glow));
}
else
{
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions_blu));
}
ActionItem action = null;
for(int i=0;i<availableActions.length;i++)
{
int a = availableActions[i];
action = null;
switch (a) {
case R.string.action_cut:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.cutFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_copy:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.copyFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_delete:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete));
action.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
actions.dismiss();
FileActionsHelper.deleteFile(file, mContext);
}
});
break;
case R.string.action_share:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
actions.dismiss();
FileActionsHelper.share(file, mContext);
}
});
break;
case R.string.action_zip:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_zip));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
actions.dismiss();
FileActionsHelper.zip(file, mContext);
}
});
break;
default:
break;
}
if(action!=null)
{
actions.addActionItem(action);
}
}
if(availableActions.length>0)
{
actions.setAnimStyle(QuickAction.ANIM_AUTO);
actions.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
view.setImageDrawable(mContext.getResources().getDrawable(R.drawable.list_actions));
}
});
actions.show();
}
}
|
diff --git a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/config/AbstractGormMappingFactory.java b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/config/AbstractGormMappingFactory.java
index 5232b4a0..e070a97e 100644
--- a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/config/AbstractGormMappingFactory.java
+++ b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/config/AbstractGormMappingFactory.java
@@ -1,112 +1,112 @@
/* Copyright (C) 2010 SpringSource
*
* 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.grails.datastore.mapping.config;
import groovy.lang.Closure;
import java.util.HashMap;
import java.util.Map;
import org.grails.datastore.mapping.model.*;
import org.springframework.beans.BeanUtils;
import org.grails.datastore.mapping.config.groovy.MappingConfigurationBuilder;
import org.grails.datastore.mapping.model.config.GormProperties;
import org.grails.datastore.mapping.reflect.ClassPropertyFetcher;
/**
* Abstract GORM implementation that uses the GORM MappingConfigurationBuilder to configure entity mappings.
*
* @author Graeme Rocher
*/
public abstract class AbstractGormMappingFactory<R, T> extends MappingFactory<R, T> {
protected Map<PersistentEntity, Map<String, T>> entityToPropertyMap = new HashMap<PersistentEntity, Map<String, T>>();
private Closure defaultMapping;
@SuppressWarnings("unchecked")
@Override
public R createMappedForm(PersistentEntity entity) {
ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass());
R family = BeanUtils.instantiate(getEntityMappedFormType());
MappingConfigurationBuilder builder = new MappingConfigurationBuilder(family, getPropertyMappedFormType());
if(defaultMapping != null) {
builder.evaluate(defaultMapping);
}
Closure value = cpf.getStaticPropertyValue(GormProperties.MAPPING, Closure.class);
if (value != null) {
builder.evaluate(value);
}
value = cpf.getStaticPropertyValue(GormProperties.CONSTRAINTS, Closure.class);
if (value != null) {
builder.evaluate(value);
}
entityToPropertyMap.put(entity, builder.getProperties());
return family;
}
public void setDefaultMapping(Closure defaultMapping) {
this.defaultMapping = defaultMapping;
}
protected abstract Class<T> getPropertyMappedFormType();
protected abstract Class<R> getEntityMappedFormType();
@Override
public IdentityMapping createIdentityMapping(ClassMapping classMapping) {
Map<String, T> props = entityToPropertyMap.get(classMapping.getEntity());
if(props != null) {
T property = props.get(IDENTITY_PROPERTY);
IdentityMapping customIdentityMapping = getIdentityMappedForm(classMapping,property);
if(customIdentityMapping != null) {
return customIdentityMapping;
}
}
return super.createIdentityMapping(classMapping);
}
protected IdentityMapping getIdentityMappedForm(ClassMapping classMapping, T property) {
return null;
}
@Override
public T createMappedForm(@SuppressWarnings("rawtypes") PersistentProperty mpp) {
Map<String, T> properties = entityToPropertyMap.get(mpp.getOwner());
if (properties != null && properties.containsKey(mpp.getName())) {
return properties.get(mpp.getName());
}
else if(properties != null) {
Property property = (Property) properties.get(IDENTITY_PROPERTY);
if(property != null && mpp.getName().equals(property.getName())) {
return (T) property;
}
}
- T defaultMapping = properties.get("*");
+ T defaultMapping = properties != null ? properties.get("*") : null;
if(defaultMapping != null) {
try {
return (T)((Property)defaultMapping).clone();
} catch (CloneNotSupportedException e) {
return BeanUtils.instantiate(getPropertyMappedFormType());
}
}
else {
return BeanUtils.instantiate(getPropertyMappedFormType());
}
}
}
| true | true | public T createMappedForm(@SuppressWarnings("rawtypes") PersistentProperty mpp) {
Map<String, T> properties = entityToPropertyMap.get(mpp.getOwner());
if (properties != null && properties.containsKey(mpp.getName())) {
return properties.get(mpp.getName());
}
else if(properties != null) {
Property property = (Property) properties.get(IDENTITY_PROPERTY);
if(property != null && mpp.getName().equals(property.getName())) {
return (T) property;
}
}
T defaultMapping = properties.get("*");
if(defaultMapping != null) {
try {
return (T)((Property)defaultMapping).clone();
} catch (CloneNotSupportedException e) {
return BeanUtils.instantiate(getPropertyMappedFormType());
}
}
else {
return BeanUtils.instantiate(getPropertyMappedFormType());
}
}
| public T createMappedForm(@SuppressWarnings("rawtypes") PersistentProperty mpp) {
Map<String, T> properties = entityToPropertyMap.get(mpp.getOwner());
if (properties != null && properties.containsKey(mpp.getName())) {
return properties.get(mpp.getName());
}
else if(properties != null) {
Property property = (Property) properties.get(IDENTITY_PROPERTY);
if(property != null && mpp.getName().equals(property.getName())) {
return (T) property;
}
}
T defaultMapping = properties != null ? properties.get("*") : null;
if(defaultMapping != null) {
try {
return (T)((Property)defaultMapping).clone();
} catch (CloneNotSupportedException e) {
return BeanUtils.instantiate(getPropertyMappedFormType());
}
}
else {
return BeanUtils.instantiate(getPropertyMappedFormType());
}
}
|
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/DSBIngestMessageBean.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/DSBIngestMessageBean.java
index a85c2a68..0d80839e 100644
--- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/DSBIngestMessageBean.java
+++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/DSBIngestMessageBean.java
@@ -1,176 +1,175 @@
/*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
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.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
/*
* DSBIngestMessageBean.java
*
* Created on November 20, 2006, 6:07 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.iq.dvn.ingest.dsb;
import edu.harvard.iq.dvn.core.analysis.NetworkDataServiceLocal;
import edu.harvard.iq.dvn.core.ddi.DDIServiceLocal;
import edu.harvard.iq.dvn.core.index.IndexServiceLocal;
import edu.harvard.iq.dvn.core.mail.MailServiceLocal;
import edu.harvard.iq.dvn.core.study.DataTable;
import edu.harvard.iq.dvn.core.study.FileMetadata;
import edu.harvard.iq.dvn.core.study.NetworkDataFile;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyFileEditBean;
import edu.harvard.iq.dvn.core.study.StudyFileServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.study.TabularDataFile;
import edu.harvard.iq.dvn.core.study.DataVariable;
import edu.harvard.iq.dvn.core.study.StudyVersion;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
/**
*
* @author gdurand
*/
@MessageDriven(mappedName = "jms/DSBIngest", activationConfig = {@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")})
@EJB(name="networkData", beanInterface=edu.harvard.iq.dvn.core.analysis.NetworkDataServiceLocal.class)
public class DSBIngestMessageBean implements MessageListener {
@EJB DDIServiceLocal ddiService;
@EJB StudyServiceLocal studyService;
@EJB StudyFileServiceLocal studyFileService;
@EJB MailServiceLocal mailService;
@EJB IndexServiceLocal indexService;
NetworkDataServiceLocal networkDataService;
/**
* Creates a new instance of DSBIngestMessageBean
*/
public DSBIngestMessageBean() {
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void onMessage(Message message) {
DSBIngestMessage ingestMessage = null;
StudyVersion sv = null;
List successfulFiles = new ArrayList();
List problemFiles = new ArrayList();
try {
ObjectMessage om = (ObjectMessage) message;
ingestMessage = (DSBIngestMessage) om.getObject();
- sv = studyService.getStudyVersionById( ingestMessage.getStudyVersionId() );
String detail = "Ingest processing for " +ingestMessage.getFileBeans().size() + " file(s).";
Iterator iter = ingestMessage.getFileBeans().iterator();
while (iter.hasNext()) {
StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();
try {
if (fileBean.getStudyFile() instanceof NetworkDataFile ) {
// ELLEN TODO: move this logic into SDIOReader component
Context ctx = new InitialContext();
networkDataService = (NetworkDataServiceLocal) ctx.lookup("java:comp/env/networkData");
networkDataService.ingest(fileBean);
successfulFiles.add(fileBean);
} else {
parseXML( new DSBWrapper().ingest(fileBean) , fileBean.getFileMetadata() );
successfulFiles.add(fileBean);
}
} catch (Exception ex) {
ex.printStackTrace();
problemFiles.add(fileBean);
}
}
if (!successfulFiles.isEmpty()) {
studyFileService.addIngestedFiles(ingestMessage.getStudyId(), ingestMessage.getVersionNote(), successfulFiles, ingestMessage.getIngestUserId());
}
if ( ingestMessage.sendInfoMessage() || ( problemFiles.size() >= 0 && ingestMessage.sendErrorMessage() ) ) {
- mailService.sendIngestCompletedNotification(ingestMessage.getIngestEmail(), sv, successfulFiles, problemFiles);
+ mailService.sendIngestCompletedNotification(ingestMessage, successfulFiles, problemFiles);
}
} catch (JMSException ex) {
ex.printStackTrace(); // error in getting object from message; can't send e-mail
} catch (Exception ex) {
ex.printStackTrace();
// if a general exception is caught that means the entire upload failed
if (ingestMessage.sendErrorMessage()) {
- mailService.sendIngestCompletedNotification(ingestMessage.getIngestEmail(), sv, null, ingestMessage.getFileBeans());
+ mailService.sendIngestCompletedNotification(ingestMessage, null, ingestMessage.getFileBeans());
}
} finally {
// when we're done, go ahead and remove the lock
try {
studyService.removeStudyLock( ingestMessage.getStudyId() );
} catch (Exception ex) {
ex.printStackTrace(); // application was unable to remove the studyLock
}
}
}
private void parseXML(String xmlToParse, FileMetadata fileMetadata) {
// now map and get dummy dataTable
Study dummyStudy = new Study();
Map filesMap = ddiService.mapDDI(xmlToParse, dummyStudy.getLatestVersion());
Map variablesMap = ddiService.reMapDDI(xmlToParse, dummyStudy.getLatestVersion(), filesMap);
if (variablesMap != null) {
Object mapKey = variablesMap.keySet().iterator().next();
List<DataVariable> variablesMapEntry = (List<DataVariable>)variablesMap.get(mapKey);
if (variablesMapEntry != null) {
DataVariable dv = variablesMapEntry.get(0);
DataTable tmpDt = dv.getDataTable();
if (tmpDt != null) {
tmpDt.setDataVariables(variablesMapEntry);
TabularDataFile file = (TabularDataFile) fileMetadata.getStudyFile();
// set to actual file (and copy over the UNF)
file.setDataTable( tmpDt );
tmpDt.setStudyFile(file);
file.setUnf(tmpDt.getUnf());
}
}
}
}
}
| false | true | public void onMessage(Message message) {
DSBIngestMessage ingestMessage = null;
StudyVersion sv = null;
List successfulFiles = new ArrayList();
List problemFiles = new ArrayList();
try {
ObjectMessage om = (ObjectMessage) message;
ingestMessage = (DSBIngestMessage) om.getObject();
sv = studyService.getStudyVersionById( ingestMessage.getStudyVersionId() );
String detail = "Ingest processing for " +ingestMessage.getFileBeans().size() + " file(s).";
Iterator iter = ingestMessage.getFileBeans().iterator();
while (iter.hasNext()) {
StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();
try {
if (fileBean.getStudyFile() instanceof NetworkDataFile ) {
// ELLEN TODO: move this logic into SDIOReader component
Context ctx = new InitialContext();
networkDataService = (NetworkDataServiceLocal) ctx.lookup("java:comp/env/networkData");
networkDataService.ingest(fileBean);
successfulFiles.add(fileBean);
} else {
parseXML( new DSBWrapper().ingest(fileBean) , fileBean.getFileMetadata() );
successfulFiles.add(fileBean);
}
} catch (Exception ex) {
ex.printStackTrace();
problemFiles.add(fileBean);
}
}
if (!successfulFiles.isEmpty()) {
studyFileService.addIngestedFiles(ingestMessage.getStudyId(), ingestMessage.getVersionNote(), successfulFiles, ingestMessage.getIngestUserId());
}
if ( ingestMessage.sendInfoMessage() || ( problemFiles.size() >= 0 && ingestMessage.sendErrorMessage() ) ) {
mailService.sendIngestCompletedNotification(ingestMessage.getIngestEmail(), sv, successfulFiles, problemFiles);
}
} catch (JMSException ex) {
ex.printStackTrace(); // error in getting object from message; can't send e-mail
} catch (Exception ex) {
ex.printStackTrace();
// if a general exception is caught that means the entire upload failed
if (ingestMessage.sendErrorMessage()) {
mailService.sendIngestCompletedNotification(ingestMessage.getIngestEmail(), sv, null, ingestMessage.getFileBeans());
}
} finally {
// when we're done, go ahead and remove the lock
try {
studyService.removeStudyLock( ingestMessage.getStudyId() );
} catch (Exception ex) {
ex.printStackTrace(); // application was unable to remove the studyLock
}
}
}
| public void onMessage(Message message) {
DSBIngestMessage ingestMessage = null;
StudyVersion sv = null;
List successfulFiles = new ArrayList();
List problemFiles = new ArrayList();
try {
ObjectMessage om = (ObjectMessage) message;
ingestMessage = (DSBIngestMessage) om.getObject();
String detail = "Ingest processing for " +ingestMessage.getFileBeans().size() + " file(s).";
Iterator iter = ingestMessage.getFileBeans().iterator();
while (iter.hasNext()) {
StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();
try {
if (fileBean.getStudyFile() instanceof NetworkDataFile ) {
// ELLEN TODO: move this logic into SDIOReader component
Context ctx = new InitialContext();
networkDataService = (NetworkDataServiceLocal) ctx.lookup("java:comp/env/networkData");
networkDataService.ingest(fileBean);
successfulFiles.add(fileBean);
} else {
parseXML( new DSBWrapper().ingest(fileBean) , fileBean.getFileMetadata() );
successfulFiles.add(fileBean);
}
} catch (Exception ex) {
ex.printStackTrace();
problemFiles.add(fileBean);
}
}
if (!successfulFiles.isEmpty()) {
studyFileService.addIngestedFiles(ingestMessage.getStudyId(), ingestMessage.getVersionNote(), successfulFiles, ingestMessage.getIngestUserId());
}
if ( ingestMessage.sendInfoMessage() || ( problemFiles.size() >= 0 && ingestMessage.sendErrorMessage() ) ) {
mailService.sendIngestCompletedNotification(ingestMessage, successfulFiles, problemFiles);
}
} catch (JMSException ex) {
ex.printStackTrace(); // error in getting object from message; can't send e-mail
} catch (Exception ex) {
ex.printStackTrace();
// if a general exception is caught that means the entire upload failed
if (ingestMessage.sendErrorMessage()) {
mailService.sendIngestCompletedNotification(ingestMessage, null, ingestMessage.getFileBeans());
}
} finally {
// when we're done, go ahead and remove the lock
try {
studyService.removeStudyLock( ingestMessage.getStudyId() );
} catch (Exception ex) {
ex.printStackTrace(); // application was unable to remove the studyLock
}
}
}
|
diff --git a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
index bf8a000..aa9c991 100644
--- a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
+++ b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
@@ -1,853 +1,853 @@
/*
* Copyright © 2013, Pierre Marijon <[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 X be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* Software.
*/
package org.geekygoblin.nedetlesmaki.game.systems;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.Collections;
import com.artemis.Entity;
import com.artemis.utils.ImmutableBag;
import org.geekygoblin.nedetlesmaki.game.components.visual.Sprite;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Color;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Pushable;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Pusher;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Position;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Square;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Plate;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Stairs;
import org.geekygoblin.nedetlesmaki.game.manager.EntityIndexManager;
import org.geekygoblin.nedetlesmaki.game.utils.PosOperation;
import org.geekygoblin.nedetlesmaki.game.utils.Mouvement;
import org.geekygoblin.nedetlesmaki.game.constants.AnimationType;
import org.geekygoblin.nedetlesmaki.game.constants.ColorType;
/**
*
* @author natir
*/
@Singleton
public class GameSystem {
private final EntityIndexManager index;
public boolean end;
@Inject
public GameSystem(EntityIndexManager index) {
this.index = index;
this.end = false;
}
public ArrayList<Mouvement> moveEntity(Entity e, Position dirP, float baseBefore, boolean nedPush) {
Entity nedEntity = this.index.getNed();
Position oldP = this.index.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList();
float destroyBefore = baseBefore;
for (int i = 0; i != this.index.getMovable(e); i++) {
float animTime = this.calculateAnimationTime(0.6f, i);
Position newP = PosOperation.sum(oldP, dirP);
if (i > this.index.getBoost(e) - 1) {
e.getComponent(Pusher.class).setPusher(true);
}
if (this.index.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.addAll(this.runValideMove(dirP, e, false, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
if (this.index.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.addAll(runValideMove(dirP, e, false, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
baseBefore = 0;
}
} else {
- if (this.index.isStairs(newP)) {
+ if (this.index.isStairs(newP) && e.equals(nedEntity)) {
mouv.addAll(nedMoveOnStairs(dirP, e, animTime));
if (!mouv.isEmpty()) {
this.end = true;
}
}
if (this.index.isPusherEntity(e)) {
ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
if (!aNextE.isEmpty()) {
Entity nextE = aNextE.get(0);
if (this.index.isPushableEntity(nextE)) {
if (this.index.isDestroyer(e)) {
if (this.index.isDestroyable(nextE)) {
mouv.addAll(destroyMove(nextE, dirP, destroyBefore + this.beforeTime(0.6f, i), animTime));
mouv.addAll(runValideMove(dirP, e, false, this.beforeTime(0.6f, i), animTime, i, this.index.isBoosted(e), nedPush));
} else {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP, baseBefore + this.beforeTime(0.6f, i), e == nedEntity);
if (!recMouv.isEmpty()) {
mouv.addAll(recMouv);
mouv.addAll(runValideMove(dirP, e, true, this.beforeTime(0.6f, i), animTime, i, this.index.isBoosted(e), nedPush));
}
}
} else {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP, baseBefore + this.beforeTime(0.6f, i), e == nedEntity);
if (!recMouv.isEmpty()) {
mouv.addAll(recMouv);
if (!this.index.isCatchNed(nextE)) {
mouv.addAll(runValideMove(dirP, e, true, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
if (recMouv.size() > 2) {
mouv.add(new Mouvement(nedEntity).setAnimation(this.nedWaitBoostChoice(dirP)).saveMouvement());
}
}
}
}
}
}
}
if (this.index.isBoosted(e)) {
mouv.add(new Mouvement(e).setAnimation(this.getMakiAnimation(true, -1, dirP, ColorType.blue)).saveMouvement());
}
if (this.index.nedIsCatched(e) && nedPush) {
mouv.add(new Mouvement(nedEntity).setAnimation(this.getFlyAnimation(-1, dirP)).saveMouvement());
}
if (this.index.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
if (mouv.size() == 3 && this.isBeginFly(mouv.get(1).getAnimation(0)) && this.isEndFly(mouv.get(2).getAnimation(0))) {
mouv.remove(2);
mouv.remove(1);
mouv.add(new Mouvement(nedEntity).setPosition(dirP).setAnimation(this.getNedAnimation(dirP, 0, true, false)).setAnimationTime(this.calculateAnimationTime(0.6f, 0)).saveMouvement());
}
if (mouv.size() == 1 && this.isEndFly(mouv.get(0).getAnimation(0))) {
mouv.remove(0);
}
return mouv;
}
}
if (this.index.isBoosted(e)) {
mouv.add(new Mouvement(e).setAnimation(this.getMakiAnimation(true, -1, dirP, ColorType.blue)).saveMouvement());
}
if (this.index.nedIsCatched(e)) {
mouv.add(new Mouvement(this.index.getNed()).setAnimation(this.getFlyAnimation(-1, dirP)).setAnimationTime(this.calculateAnimationTime(baseBefore, 2)).saveMouvement());
}
if (mouv.size() == 3 && this.isBeginFly(mouv.get(1).getAnimation(0)) && this.isEndFly(mouv.get(2).getAnimation(0))) {
mouv.remove(2);
mouv.remove(1);
mouv.add(new Mouvement(nedEntity).setPosition(dirP).setAnimation(this.getNedAnimation(dirP, 0, true, false)).setAnimationTime(this.calculateAnimationTime(0.6f, 0)).saveMouvement());
}
if (mouv.size() == 1 && this.isEndFly(mouv.get(0).getAnimation(0))) {
mouv.remove(0);
}
return mouv;
}
private boolean isBeginFly(AnimationType a) {
return a.equals(AnimationType.fly_start_down) || a.equals(AnimationType.fly_start_left) || a.equals(AnimationType.fly_start_right) || a.equals(AnimationType.fly_start_up);
}
private boolean isEndFly(AnimationType a) {
return a.equals(AnimationType.fly_stop_down) || a.equals(AnimationType.fly_stop_left) || a.equals(AnimationType.fly_stop_right) || a.equals(AnimationType.fly_stop_up);
}
private ArrayList<Mouvement> runValideMove(Position diff, Entity e, boolean push, float bw, float aT, int pas, boolean boosted, boolean pusherIsNed) {
Position oldP = this.index.getPosition(e);
Position newP = PosOperation.sum(oldP, diff);
ArrayList<Mouvement> m = new ArrayList();
if (index.moveEntity(oldP.getX(), oldP.getY(), newP.getX(), newP.getY())) {
if (e == this.index.getNed()) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(this.getNedAnimation(diff, pas, push, boosted)).setBeforeWait(bw).setAnimationTime(aT).saveMouvement());
} else {
if (makiMoveOnePlate(newP, e)) {
if (actualIsColorPlate(oldP, e)) {
this.index.getSquare(oldP.getX(), oldP.getY()).getWith(Plate.class).get(0).getComponent(Plate.class).setMaki(false);
this.index.getSquare(newP.getX(), newP.getY()).getWith(Plate.class).get(0).getComponent(Plate.class).setMaki(true);
m.addAll(makiPlateMove(oldP, newP, e, true, aT, bw, true));
} else {
m.addAll(makiPlateMove(oldP, newP, e, true, aT, bw, false));
}
m.addAll(this.tryPlate());
} else if (makiMoveOutPlate(oldP, e)) {
m.addAll(makiPlateMove(oldP, newP, e, false, aT, bw, actualIsColorPlate(oldP, e)));
m.addAll(this.tryPlate());
} else {
m.add(new Mouvement(e).setPosition(diff).setAnimation(this.getMakiAnimation(boosted, pas, diff, this.index.getColorType(e))).setBeforeWait(bw).setAnimationTime(aT).saveMouvement());
}
Entity ned = this.index.getNed();
if (this.index.isCatchNed(e) && pusherIsNed) {
if (index.moveEntity(oldP.getX() - diff.getX(), oldP.getY() - diff.getY(), oldP.getX(), oldP.getY())) {
if (pusherIsNed) {
m.add(new Mouvement(ned).setPosition(diff).setAnimation(this.getFlyAnimation(pas, diff)).setBeforeWait(bw).setAnimationTime(aT).saveMouvement());
this.index.getCatchNed(e).nedCatched(true);
ned.getComponent(Position.class).setX(oldP.getX());
ned.getComponent(Position.class).setY(oldP.getY());
}
}
}
}
e.getComponent(Position.class).setX(newP.getX());
e.getComponent(Position.class).setY(newP.getY());
return m;
}
return m;
}
private AnimationType getNedAnimation(Position diff, int pas, boolean push, boolean boosted) {
if (diff.getX() > 0) {
if (push) {
return AnimationType.ned_push_right;
} else {
return AnimationType.ned_right;
}
} else if (diff.getX() < 0) {
if (push) {
return AnimationType.ned_push_left;
} else {
return AnimationType.ned_left;
}
} else if (diff.getY() > 0) {
if (push) {
return AnimationType.ned_push_down;
} else {
return AnimationType.ned_down;
}
} else if (diff.getY() < 0) {
if (push) {
return AnimationType.ned_push_up;
} else {
return AnimationType.ned_up;
}
} else {
return this.getMakiAnimation(boosted, pas, diff, ColorType.no);
}
}
private ArrayList<Mouvement> nedMoveOnStairs(Position diff, Entity e, float aT) {
Position newP = PosOperation.sum(this.index.getPosition(e), diff);
ArrayList<Mouvement> m = new ArrayList();
if (e == this.index.getNed()) {
if (diff.getX() > 0) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.ned_mount_stairs_right).setAnimationTime(aT).saveMouvement());
} else if (diff.getX() < 0) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.ned_mount_stairs_left).setAnimationTime(aT).saveMouvement());
} else if (diff.getY() > 0) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.ned_mount_stairs_down).setAnimationTime(aT).saveMouvement());
} else if (diff.getY() < 0) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.ned_mount_stairs_up).setAnimationTime(aT).saveMouvement());
} else {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.no).setAnimationTime(aT).saveMouvement());
}
} else {
if (m.isEmpty()) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.no).setAnimationTime(aT).saveMouvement());
}
}
e.getComponent(Position.class).setX(newP.getX());
e.getComponent(Position.class).setY(newP.getY());
return m;
}
private ArrayList<Mouvement> makiPlateMove(Position oldP, Position newP, Entity e, boolean getOne, float aT, float bT, boolean actualIsPlate) {
ArrayList<Mouvement> m = new ArrayList();
Position diff = PosOperation.deduction(newP, oldP);
Square obj;
if (getOne) {
obj = index.getSquare(newP.getX(), newP.getY());
} else {
obj = index.getSquare(oldP.getX(), oldP.getY());
}
if (obj == null) {
return m;
}
ArrayList<Entity> plates = obj.getWith(Plate.class);
if (plates.isEmpty()) {
return m;
}
Entity plate = plates.get(0);
Color plateC = this.index.getColor(plate);
Color makiC = this.index.getColor(e);
if (plateC.getColor() == makiC.getColor()) {
if (plateC.getColor() == ColorType.green) {
if (getOne && !actualIsPlate) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.maki_green_one).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
} else if (!getOne && actualIsPlate) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.maki_green_out).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
} else {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.no).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
}
} else if (plateC.getColor() == ColorType.orange) {
if (getOne && !actualIsPlate) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.maki_orange_one).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
} else if (!getOne && actualIsPlate) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.maki_orange_out).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
} else {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.no).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
}
} else if (plateC.getColor() == ColorType.blue) {
if (getOne && !actualIsPlate) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.maki_blue_one).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
} else if (!getOne && actualIsPlate) {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.maki_blue_out).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
} else {
m.add(new Mouvement(e).setPosition(diff).setAnimation(AnimationType.no).setAnimationTime(aT).setBeforeWait(bT).saveMouvement());
}
}
}
return m;
}
public ArrayList<Mouvement> destroyMove(Entity e, Position diff, float bT, float aT) {
ArrayList<Mouvement> preM = this.moveEntity(e, diff, bT, false);
if (preM.isEmpty()) {
preM.add(new Mouvement(e).setPosition(new Position(0, 0)).setAnimation(AnimationType.box_boom).setBeforeWait(bT).setAnimationTime(aT).saveMouvement());
} else {
preM.add(new Mouvement(e).setPosition(new Position(0, 0)).setAnimation(AnimationType.box_destroy).setBeforeWait(bT).setAnimationTime(aT).saveMouvement());
}
return preM;
}
private AnimationType getMakiAnimation(boolean boosted, int pas, Position diff, ColorType makiColor) {
if (boosted) {
if (diff.getX() > 0) {
if (pas < 0) {
return AnimationType.boost_stop_right;
} else if (pas == 3) {
return AnimationType.boost_start_right;
} else if (pas > 3) {
return AnimationType.boost_loop_right;
}
} else if (diff.getX() < 0) {
if (pas < 0) {
return AnimationType.boost_stop_left;
} else if (pas == 3) {
return AnimationType.boost_start_left;
} else if (pas > 3) {
return AnimationType.boost_loop_left;
}
} else if (diff.getY() > 0) {
if (pas < 0) {
return AnimationType.boost_stop_down;
} else if (pas == 3) {
return AnimationType.boost_start_down;
} else if (pas > 3) {
return AnimationType.boost_loop_down;
}
} else if (diff.getY() < 0) {
if (pas < 0) {
return AnimationType.boost_stop_up;
} else if (pas == 3) {
return AnimationType.boost_start_up;
} else if (pas > 3) {
return AnimationType.boost_loop_up;
}
}
}
if (makiColor == ColorType.orange) {
return AnimationType.maki_orange_no;
} else {
return AnimationType.no;
}
}
private AnimationType getFlyAnimation(int pas, Position diff) {
if (diff.getX() > 0) {
if (pas < 0) {
return AnimationType.fly_stop_right;
} else if (pas == 0) {
return AnimationType.fly_start_right;
} else if (pas > 0) {
return AnimationType.fly_loop_right;
}
} else if (diff.getX() < 0) {
if (pas < 0) {
return AnimationType.fly_stop_left;
} else if (pas == 0) {
return AnimationType.fly_start_left;
} else if (pas > 0) {
return AnimationType.fly_loop_left;
}
} else if (diff.getY() > 0) {
if (pas < 0) {
return AnimationType.fly_stop_down;
} else if (pas == 0) {
return AnimationType.fly_start_down;
} else if (pas > 0) {
return AnimationType.fly_loop_down;
}
} else if (diff.getY() < 0) {
if (pas < 0) {
return AnimationType.fly_stop_up;
} else if (pas == 0) {
return AnimationType.fly_start_up;
} else if (pas > 0) {
return AnimationType.fly_loop_up;
}
}
return AnimationType.no;
}
public boolean makiMoveOnePlate(Position newP, Entity e) {
Square s = this.index.getSquare(newP.getX(), newP.getY());
if (s == null) {
return false;
}
ArrayList<Entity> plates = s.getWith(Plate.class);
if (plates.isEmpty()) {
return false;
}
if (this.index.getColor(e) == null) {
return false;
}
if (this.index.getColorType(e) == this.index.getColorType(plates.get(0))) {
plates.get(0).getComponent(Plate.class).setMaki(true);
return true;
}
return false;
}
public boolean makiMoveOutPlate(Position oldP, Entity e) {
Square s = this.index.getSquare(oldP.getX(), oldP.getY());
if (s == null) {
return false;
}
ArrayList<Entity> plates = s.getWith(Plate.class);
if (plates.isEmpty()) {
return false;
}
if (this.index.getColor(e) == null) {
return false;
}
if (this.index.getColorType(e) == this.index.getColorType(plates.get(0))) {
plates.get(0).getComponent(Plate.class).setMaki(false);
return true;
}
return false;
}
private boolean actualIsColorPlate(Position nextnextP, Entity maki) {
Square s = this.index.getSquare(nextnextP.getX(), nextnextP.getY());
if (s == null) {
return false;
}
ArrayList<Entity> plates = s.getWith(Plate.class);
if (plates.isEmpty()) {
return false;
}
if (this.index.getColor(maki) == null) {
return false;
}
if (this.index.getColorType(maki) == this.index.getColorType(plates.get(0))) {
return true;
}
return false;
}
private boolean testStopOnPlate(Entity eMove, Square obj) {
if (obj == null) {
return false;
}
ArrayList<Entity> array = obj.getWith(Plate.class);
if (array.isEmpty()) {
return false;
}
Entity plate = obj.getWith(Plate.class).get(0);
Plate p = this.index.getPlate(plate);
boolean block = this.index.stopOnPlate(eMove);
if (!block) {
return false;
}
if (p.isPlate()) {
if (block) {
if (this.index.getColorType(plate) == this.index.getColorType(eMove) && this.index.getColorType(eMove) != ColorType.orange) {
return true;
}
}
}
return false;
}
private boolean testBlockedPlate(Entity eMove, Square obj) {
if (obj == null) {
return false;
}
ArrayList<Entity> array = obj.getWith(Plate.class);
if (array.isEmpty()) {
return false;
}
Entity plate = obj.getWith(Plate.class).get(0);
Plate p = plate.getComponent(Plate.class);
boolean block = this.index.isBlockOnPlate(eMove);
if (!block) {
return false;
}
if (p.isPlate()) {
if (block) {
return true;
}
}
return false;
}
private ArrayList<Mouvement> tryPlate() {
ImmutableBag<Entity> plateGroup = this.index.getAllPlate();
ImmutableBag<Entity> stairsGroup = this.index.getAllStairs();
Entity stairs = stairsGroup.get(0);
Stairs stairsS = this.index.getStairs(stairs);
for (int i = 0; i != plateGroup.size(); i++) {
Entity plateE = plateGroup.get(i);
Plate plate = this.index.getPlate(plateE);
if (!plate.haveMaki()) {
if (stairsS.isOpen()) {
stairsS.setStairs(false);
stairsAnimation(stairs, stairsS, false);
}
return new ArrayList<>();
}
}
if (stairsS.isOpen()) {
return new ArrayList<>();
}
stairsS.setStairs(true);
return stairsAnimation(stairs, stairsS, true);
}
private ArrayList<Mouvement> stairsAnimation(Entity stairs, Stairs stairsS, boolean open) {
ArrayList<Mouvement> tmpm = new ArrayList();
switch (stairsS.getDir()) {
case 1:
if (open) {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_open_up).setAnimationTime(0.6f).saveMouvement());
} else {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_close_up).setAnimationTime(0.6f).saveMouvement());
}
break;
case 2:
if (open) {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_open_down).setAnimationTime(0.6f).saveMouvement());
} else {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_close_down).setAnimationTime(0.6f).saveMouvement());
}
break;
case 3:
if (open) {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_open_left).setAnimationTime(0.6f).saveMouvement());
} else {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_close_left).setAnimationTime(0.6f).saveMouvement());
}
break;
case 4:
if (open) {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_open_right).setAnimationTime(0.6f).saveMouvement());
} else {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_close_right).setAnimationTime(0.6f).saveMouvement());
}
break;
default:
if (open) {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_open_up).setAnimationTime(0.6f).saveMouvement());
} else {
tmpm.add(new Mouvement(stairs).setAnimation(AnimationType.stairs_close_up).setAnimationTime(0.6f).saveMouvement());
}
}
return tmpm;
}
AnimationType nedWaitBoostChoice(Position diff) {
if (diff.getX() > 0) {
return AnimationType.ned_waits_boost_right;
} else if (diff.getX() < 0) {
return AnimationType.ned_waits_boost_left;
} else if (diff.getY() > 0) {
return AnimationType.ned_waits_boost_down;
} else if (diff.getY() < 0) {
return AnimationType.ned_waits_boost_up;
}
return AnimationType.no;
}
public boolean endOfLevel() {
ImmutableBag<Entity> stairsGroup = this.index.getAllStairs();
Entity ned = this.index.getNed();
Position nedP = this.index.getPosition(ned);
Sprite nedS = this.index.getSprite(ned);
Entity stairs = stairsGroup.get(0);
Position stairsP = this.index.getPosition(stairs);
Stairs stairsS = this.index.getStairs(stairs);
if (stairsS.isOpen() && PosOperation.equale(nedP, stairsP)) {
if (nedS.getPlay().getName().length() > 9) {
if (nedS.getPlay().getName().substring(0, 9).equals("ned_mount") && nedS.getPlay().isStopped()) {
return true;
}
}
}
return false;
}
public void removeMouv() {
boolean reCall = false;
ArrayList<Mouvement> head = this.index.pop();
Collections.reverse(head);
if (head == null) {
return;
}
ArrayList<Mouvement> rm = new ArrayList<>();
for (int i = 0; i != head.size(); i++) {
for (int j = 0; j != head.get(i).size(); j++) {
Position headP = head.get(i).getPosition(j);
if (headP == null) {
return;
}
Position diff = PosOperation.deduction(new Position(0, 0), headP);
Position current = this.index.getPosition(head.get(i).getEntity());
if (current == null) {
return;
}
AnimationType invertAnim = this.invertAnimation(head.get(i).getAnimation(j));
rm.add(new Mouvement(head.get(i).getEntity()).setAnimation(invertAnim).setPosition(diff).setAnimationTime(head.get(i).getAnimationTime(j)).saveMouvement());
if (invertAnim == AnimationType.maki_blue_out || invertAnim == AnimationType.maki_orange_out || invertAnim == AnimationType.maki_green_out) {
this.index.getSquare(current.getX(), current.getY()).getWith(Plate.class).get(0).getComponent(Plate.class).setMaki(false);
}
this.index.moveEntity(current.getX(), current.getY(), current.getX() + diff.getX(), current.getY() + diff.getY());
head.get(i).getEntity().getComponent(Position.class).setX(current.getX() + diff.getX());
head.get(i).getEntity().getComponent(Position.class).setY(current.getY() + diff.getY());
if (invertAnim == AnimationType.stairs_open_down || invertAnim == AnimationType.stairs_open_up || invertAnim == AnimationType.stairs_open_left || invertAnim == AnimationType.stairs_open_right) {
reCall = true;
}
}
}
Collections.reverse(rm);
this.index.setRemove(rm);
if (reCall) {
this.removeMouv();
}
this.tryPlate();
}
private AnimationType invertAnimation(AnimationType base) {
if (base == AnimationType.no) {
return AnimationType.no;
} else if (base == AnimationType.ned_right) {
return AnimationType.ned_right;
} else if (base == AnimationType.ned_left) {
return AnimationType.ned_left;
} else if (base == AnimationType.ned_down) {
return AnimationType.ned_down;
} else if (base == AnimationType.ned_up) {
return AnimationType.ned_up;
} else if (base == AnimationType.ned_push_right) {
return AnimationType.ned_push_right;
} else if (base == AnimationType.ned_push_left) {
return AnimationType.ned_push_left;
} else if (base == AnimationType.ned_push_down) {
return AnimationType.ned_push_down;
} else if (base == AnimationType.ned_push_up) {
return AnimationType.ned_push_up;
} else if (base == AnimationType.box_destroy) {
return AnimationType.box_create;
} else if (base == AnimationType.box_create) {
return AnimationType.box_destroy;
} else if (base == AnimationType.box_boom) {
return AnimationType.box_create;
} else if (base == AnimationType.maki_green_one) {
return AnimationType.maki_green_out;
} else if (base == AnimationType.maki_orange_one) {
return AnimationType.maki_orange_out;
} else if (base == AnimationType.maki_blue_one) {
return AnimationType.maki_blue_out;
} else if (base == AnimationType.maki_green_out) {
return AnimationType.maki_green_one;
} else if (base == AnimationType.maki_orange_out) {
return AnimationType.maki_orange_one;
} else if (base == AnimationType.maki_blue_out) {
return AnimationType.maki_blue_one;
} else if (base == AnimationType.disable_entity) {
return AnimationType.disable_entity;
} else if (base == AnimationType.stairs_close_up) {
return AnimationType.stairs_open_up;
} else if (base == AnimationType.stairs_close_down) {
return AnimationType.stairs_open_down;
} else if (base == AnimationType.stairs_close_left) {
return AnimationType.stairs_open_left;
} else if (base == AnimationType.stairs_close_right) {
return AnimationType.stairs_open_right;
} else if (base == AnimationType.stairs_open_up) {
return AnimationType.stairs_close_up;
} else if (base == AnimationType.stairs_open_down) {
return AnimationType.stairs_close_down;
} else if (base == AnimationType.stairs_open_left) {
return AnimationType.stairs_close_left;
} else if (base == AnimationType.stairs_open_right) {
return AnimationType.stairs_close_right;
} else if (base == AnimationType.boost_loop_up) {
return AnimationType.no;
} else if (base == AnimationType.boost_loop_down) {
return AnimationType.no;
} else if (base == AnimationType.boost_loop_left) {
return AnimationType.no;
} else if (base == AnimationType.boost_loop_right) {
return AnimationType.no;
} else if (base == AnimationType.boost_start_up) {
return AnimationType.no;
} else if (base == AnimationType.boost_start_down) {
return AnimationType.no;
} else if (base == AnimationType.boost_start_left) {
return AnimationType.no;
} else if (base == AnimationType.boost_start_right) {
return AnimationType.no;
} else if (base == AnimationType.boost_stop_up) {
return AnimationType.no;
} else if (base == AnimationType.boost_stop_down) {
return AnimationType.no;
} else if (base == AnimationType.boost_stop_left) {
return AnimationType.no;
}
return base;
}
float calculateAnimationTime(float base, int mul) {
if (mul > 0) {
return base / 3f;
} else {
return base;
}
}
float beforeTime(float base, int mul) {
float ret = 0;
for (int i = 0; i != mul; i++) {
ret += this.calculateAnimationTime(base, i);
}
return ret;
}
}
| true | true | public ArrayList<Mouvement> moveEntity(Entity e, Position dirP, float baseBefore, boolean nedPush) {
Entity nedEntity = this.index.getNed();
Position oldP = this.index.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList();
float destroyBefore = baseBefore;
for (int i = 0; i != this.index.getMovable(e); i++) {
float animTime = this.calculateAnimationTime(0.6f, i);
Position newP = PosOperation.sum(oldP, dirP);
if (i > this.index.getBoost(e) - 1) {
e.getComponent(Pusher.class).setPusher(true);
}
if (this.index.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.addAll(this.runValideMove(dirP, e, false, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
if (this.index.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.addAll(runValideMove(dirP, e, false, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
baseBefore = 0;
}
} else {
if (this.index.isStairs(newP)) {
mouv.addAll(nedMoveOnStairs(dirP, e, animTime));
if (!mouv.isEmpty()) {
this.end = true;
}
}
if (this.index.isPusherEntity(e)) {
ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
if (!aNextE.isEmpty()) {
Entity nextE = aNextE.get(0);
if (this.index.isPushableEntity(nextE)) {
if (this.index.isDestroyer(e)) {
if (this.index.isDestroyable(nextE)) {
mouv.addAll(destroyMove(nextE, dirP, destroyBefore + this.beforeTime(0.6f, i), animTime));
mouv.addAll(runValideMove(dirP, e, false, this.beforeTime(0.6f, i), animTime, i, this.index.isBoosted(e), nedPush));
} else {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP, baseBefore + this.beforeTime(0.6f, i), e == nedEntity);
if (!recMouv.isEmpty()) {
mouv.addAll(recMouv);
mouv.addAll(runValideMove(dirP, e, true, this.beforeTime(0.6f, i), animTime, i, this.index.isBoosted(e), nedPush));
}
}
} else {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP, baseBefore + this.beforeTime(0.6f, i), e == nedEntity);
if (!recMouv.isEmpty()) {
mouv.addAll(recMouv);
if (!this.index.isCatchNed(nextE)) {
mouv.addAll(runValideMove(dirP, e, true, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
if (recMouv.size() > 2) {
mouv.add(new Mouvement(nedEntity).setAnimation(this.nedWaitBoostChoice(dirP)).saveMouvement());
}
}
}
}
}
}
}
if (this.index.isBoosted(e)) {
mouv.add(new Mouvement(e).setAnimation(this.getMakiAnimation(true, -1, dirP, ColorType.blue)).saveMouvement());
}
if (this.index.nedIsCatched(e) && nedPush) {
mouv.add(new Mouvement(nedEntity).setAnimation(this.getFlyAnimation(-1, dirP)).saveMouvement());
}
if (this.index.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
if (mouv.size() == 3 && this.isBeginFly(mouv.get(1).getAnimation(0)) && this.isEndFly(mouv.get(2).getAnimation(0))) {
mouv.remove(2);
mouv.remove(1);
mouv.add(new Mouvement(nedEntity).setPosition(dirP).setAnimation(this.getNedAnimation(dirP, 0, true, false)).setAnimationTime(this.calculateAnimationTime(0.6f, 0)).saveMouvement());
}
if (mouv.size() == 1 && this.isEndFly(mouv.get(0).getAnimation(0))) {
mouv.remove(0);
}
return mouv;
}
}
if (this.index.isBoosted(e)) {
mouv.add(new Mouvement(e).setAnimation(this.getMakiAnimation(true, -1, dirP, ColorType.blue)).saveMouvement());
}
if (this.index.nedIsCatched(e)) {
mouv.add(new Mouvement(this.index.getNed()).setAnimation(this.getFlyAnimation(-1, dirP)).setAnimationTime(this.calculateAnimationTime(baseBefore, 2)).saveMouvement());
}
if (mouv.size() == 3 && this.isBeginFly(mouv.get(1).getAnimation(0)) && this.isEndFly(mouv.get(2).getAnimation(0))) {
mouv.remove(2);
mouv.remove(1);
mouv.add(new Mouvement(nedEntity).setPosition(dirP).setAnimation(this.getNedAnimation(dirP, 0, true, false)).setAnimationTime(this.calculateAnimationTime(0.6f, 0)).saveMouvement());
}
if (mouv.size() == 1 && this.isEndFly(mouv.get(0).getAnimation(0))) {
mouv.remove(0);
}
return mouv;
}
| public ArrayList<Mouvement> moveEntity(Entity e, Position dirP, float baseBefore, boolean nedPush) {
Entity nedEntity = this.index.getNed();
Position oldP = this.index.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList();
float destroyBefore = baseBefore;
for (int i = 0; i != this.index.getMovable(e); i++) {
float animTime = this.calculateAnimationTime(0.6f, i);
Position newP = PosOperation.sum(oldP, dirP);
if (i > this.index.getBoost(e) - 1) {
e.getComponent(Pusher.class).setPusher(true);
}
if (this.index.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.addAll(this.runValideMove(dirP, e, false, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
if (this.index.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.addAll(runValideMove(dirP, e, false, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
baseBefore = 0;
}
} else {
if (this.index.isStairs(newP) && e.equals(nedEntity)) {
mouv.addAll(nedMoveOnStairs(dirP, e, animTime));
if (!mouv.isEmpty()) {
this.end = true;
}
}
if (this.index.isPusherEntity(e)) {
ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
if (!aNextE.isEmpty()) {
Entity nextE = aNextE.get(0);
if (this.index.isPushableEntity(nextE)) {
if (this.index.isDestroyer(e)) {
if (this.index.isDestroyable(nextE)) {
mouv.addAll(destroyMove(nextE, dirP, destroyBefore + this.beforeTime(0.6f, i), animTime));
mouv.addAll(runValideMove(dirP, e, false, this.beforeTime(0.6f, i), animTime, i, this.index.isBoosted(e), nedPush));
} else {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP, baseBefore + this.beforeTime(0.6f, i), e == nedEntity);
if (!recMouv.isEmpty()) {
mouv.addAll(recMouv);
mouv.addAll(runValideMove(dirP, e, true, this.beforeTime(0.6f, i), animTime, i, this.index.isBoosted(e), nedPush));
}
}
} else {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP, baseBefore + this.beforeTime(0.6f, i), e == nedEntity);
if (!recMouv.isEmpty()) {
mouv.addAll(recMouv);
if (!this.index.isCatchNed(nextE)) {
mouv.addAll(runValideMove(dirP, e, true, baseBefore, animTime, i, this.index.isBoosted(e), nedPush));
if (recMouv.size() > 2) {
mouv.add(new Mouvement(nedEntity).setAnimation(this.nedWaitBoostChoice(dirP)).saveMouvement());
}
}
}
}
}
}
}
if (this.index.isBoosted(e)) {
mouv.add(new Mouvement(e).setAnimation(this.getMakiAnimation(true, -1, dirP, ColorType.blue)).saveMouvement());
}
if (this.index.nedIsCatched(e) && nedPush) {
mouv.add(new Mouvement(nedEntity).setAnimation(this.getFlyAnimation(-1, dirP)).saveMouvement());
}
if (this.index.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
if (mouv.size() == 3 && this.isBeginFly(mouv.get(1).getAnimation(0)) && this.isEndFly(mouv.get(2).getAnimation(0))) {
mouv.remove(2);
mouv.remove(1);
mouv.add(new Mouvement(nedEntity).setPosition(dirP).setAnimation(this.getNedAnimation(dirP, 0, true, false)).setAnimationTime(this.calculateAnimationTime(0.6f, 0)).saveMouvement());
}
if (mouv.size() == 1 && this.isEndFly(mouv.get(0).getAnimation(0))) {
mouv.remove(0);
}
return mouv;
}
}
if (this.index.isBoosted(e)) {
mouv.add(new Mouvement(e).setAnimation(this.getMakiAnimation(true, -1, dirP, ColorType.blue)).saveMouvement());
}
if (this.index.nedIsCatched(e)) {
mouv.add(new Mouvement(this.index.getNed()).setAnimation(this.getFlyAnimation(-1, dirP)).setAnimationTime(this.calculateAnimationTime(baseBefore, 2)).saveMouvement());
}
if (mouv.size() == 3 && this.isBeginFly(mouv.get(1).getAnimation(0)) && this.isEndFly(mouv.get(2).getAnimation(0))) {
mouv.remove(2);
mouv.remove(1);
mouv.add(new Mouvement(nedEntity).setPosition(dirP).setAnimation(this.getNedAnimation(dirP, 0, true, false)).setAnimationTime(this.calculateAnimationTime(0.6f, 0)).saveMouvement());
}
if (mouv.size() == 1 && this.isEndFly(mouv.get(0).getAnimation(0))) {
mouv.remove(0);
}
return mouv;
}
|
diff --git a/src/au/com/addstar/truehardcore/CommandTH.java b/src/au/com/addstar/truehardcore/CommandTH.java
index 679457f..8c74d52 100644
--- a/src/au/com/addstar/truehardcore/CommandTH.java
+++ b/src/au/com/addstar/truehardcore/CommandTH.java
@@ -1,164 +1,174 @@
package au.com.addstar.truehardcore;
/*
* TrueHardcore
* Copyright (C) 2013 add5tar <copyright at addstar dot com dot au>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import au.com.addstar.truehardcore.HardcorePlayers.HardcorePlayer;
public class CommandTH implements CommandExecutor {
private TrueHardcore plugin;
public CommandTH(TrueHardcore instance) {
plugin = instance;
}
/*
* Handle the /truehardcore command
*/
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String action = "";
if (args.length > 0) {
action = args[0].toUpperCase();
}
if (action.equals("PLAY")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.use")) { return true; }
}
if (args.length > 1) {
World world = plugin.getServer().getWorld(args[1]);
if (world == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown world!");
return true;
}
if (plugin.IsHardcoreWorld(world)) {
plugin.PlayGame(world.getName(), (Player) sender);
} else {
sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>");
}
}
else if (action.equals("LEAVE")) {
plugin.LeaveGame((Player) sender);
}
else if (action.equals("INFO")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
- hcp.updatePlayer(player);
+ if (hcp != null) {
+ hcp.updatePlayer(player);
+ } else {
+ sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
+ }
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (plugin.IsHardcoreWorld(player.getWorld())) {
hcp.updatePlayer(player);
+ } else {
+ sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
- Player player = (Player) plugin.getServer().getPlayer(args[2]);
- if (player != null) {
- if (plugin.IsHardcoreWorld(player.getWorld())) {
- if (args[1] == player.getWorld().getName()) {
- hcp.updatePlayer(player);
+ if (hcp != null) {
+ Player player = (Player) plugin.getServer().getPlayer(args[2]);
+ if (player != null) {
+ if (plugin.IsHardcoreWorld(player.getWorld())) {
+ if (args[1] == player.getWorld().getName()) {
+ hcp.updatePlayer(player);
+ }
}
}
+ } else {
+ sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
sender.sendMessage(ChatColor.GREEN + "Hardcore player information:");
sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore());
}
}
else if (action.equals("DUMP")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.dump")) { return true; }
}
for (String key : plugin.HCPlayers.AllRecords().keySet()) {
HardcorePlayer hcp = plugin.HCPlayers.Get(key);
sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState());
}
}
else if (action.endsWith("LIST")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.list")) { return true; }
}
for (String w : plugin.HardcoreWorlds) {
World world = plugin.getServer().getWorld(w);
if ((world != null) && (world.getPlayers().size() > 0)) {
ArrayList<String> players = new ArrayList<String>();
for (Player p : world.getPlayers()) {
players.add(p.getName());
}
sender.sendMessage(ChatColor.YELLOW + world.getName() + ": " + ChatColor.AQUA + StringUtils.join(players, ", "));
}
}
}
else if (action.equals("SAVE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.save")) { return true; }
}
plugin.SaveAllPlayers();
}
else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:");
sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game");
sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)");
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String action = "";
if (args.length > 0) {
action = args[0].toUpperCase();
}
if (action.equals("PLAY")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.use")) { return true; }
}
if (args.length > 1) {
World world = plugin.getServer().getWorld(args[1]);
if (world == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown world!");
return true;
}
if (plugin.IsHardcoreWorld(world)) {
plugin.PlayGame(world.getName(), (Player) sender);
} else {
sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>");
}
}
else if (action.equals("LEAVE")) {
plugin.LeaveGame((Player) sender);
}
else if (action.equals("INFO")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (plugin.IsHardcoreWorld(player.getWorld())) {
hcp.updatePlayer(player);
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
Player player = (Player) plugin.getServer().getPlayer(args[2]);
if (player != null) {
if (plugin.IsHardcoreWorld(player.getWorld())) {
if (args[1] == player.getWorld().getName()) {
hcp.updatePlayer(player);
}
}
}
}
if (hcp != null) {
sender.sendMessage(ChatColor.GREEN + "Hardcore player information:");
sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore());
}
}
else if (action.equals("DUMP")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.dump")) { return true; }
}
for (String key : plugin.HCPlayers.AllRecords().keySet()) {
HardcorePlayer hcp = plugin.HCPlayers.Get(key);
sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState());
}
}
else if (action.endsWith("LIST")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.list")) { return true; }
}
for (String w : plugin.HardcoreWorlds) {
World world = plugin.getServer().getWorld(w);
if ((world != null) && (world.getPlayers().size() > 0)) {
ArrayList<String> players = new ArrayList<String>();
for (Player p : world.getPlayers()) {
players.add(p.getName());
}
sender.sendMessage(ChatColor.YELLOW + world.getName() + ": " + ChatColor.AQUA + StringUtils.join(players, ", "));
}
}
}
else if (action.equals("SAVE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.save")) { return true; }
}
plugin.SaveAllPlayers();
}
else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:");
sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game");
sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)");
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String action = "";
if (args.length > 0) {
action = args[0].toUpperCase();
}
if (action.equals("PLAY")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.use")) { return true; }
}
if (args.length > 1) {
World world = plugin.getServer().getWorld(args[1]);
if (world == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown world!");
return true;
}
if (plugin.IsHardcoreWorld(world)) {
plugin.PlayGame(world.getName(), (Player) sender);
} else {
sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>");
}
}
else if (action.equals("LEAVE")) {
plugin.LeaveGame((Player) sender);
}
else if (action.equals("INFO")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
if (hcp != null) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (plugin.IsHardcoreWorld(player.getWorld())) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp != null) {
Player player = (Player) plugin.getServer().getPlayer(args[2]);
if (player != null) {
if (plugin.IsHardcoreWorld(player.getWorld())) {
if (args[1] == player.getWorld().getName()) {
hcp.updatePlayer(player);
}
}
}
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
sender.sendMessage(ChatColor.GREEN + "Hardcore player information:");
sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore());
}
}
else if (action.equals("DUMP")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.dump")) { return true; }
}
for (String key : plugin.HCPlayers.AllRecords().keySet()) {
HardcorePlayer hcp = plugin.HCPlayers.Get(key);
sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState());
}
}
else if (action.endsWith("LIST")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.list")) { return true; }
}
for (String w : plugin.HardcoreWorlds) {
World world = plugin.getServer().getWorld(w);
if ((world != null) && (world.getPlayers().size() > 0)) {
ArrayList<String> players = new ArrayList<String>();
for (Player p : world.getPlayers()) {
players.add(p.getName());
}
sender.sendMessage(ChatColor.YELLOW + world.getName() + ": " + ChatColor.AQUA + StringUtils.join(players, ", "));
}
}
}
else if (action.equals("SAVE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.save")) { return true; }
}
plugin.SaveAllPlayers();
}
else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:");
sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game");
sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)");
}
return true;
}
|
diff --git a/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java b/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java
index 87d38dd7..3dab374d 100644
--- a/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java
+++ b/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java
@@ -1,372 +1,372 @@
/*
* 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.ngrinder;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.spi.JoranException;
import com.beust.jcommander.JCommander;
import net.grinder.AgentControllerDaemon;
import net.grinder.util.VersionNumber;
import org.apache.commons.lang.StringUtils;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.ngrinder.common.constants.AgentConstants;
import org.ngrinder.common.constants.CommonConstants;
import org.ngrinder.infra.AgentConfig;
import org.ngrinder.infra.ArchLoaderInit;
import org.ngrinder.monitor.agent.MonitorServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FilenameFilter;
import static net.grinder.util.NetworkUtils.getIP;
import static org.ngrinder.common.constants.InternalConstants.PROP_INTERNAL_NGRINDER_VERSION;
import static org.ngrinder.common.util.NoOp.noOp;
/**
* Main class to start agent or monitor.
*
* @author Mavlarn
* @author JunHo Yoon
* @since 3.0
*/
public class NGrinderAgentStarter implements AgentConstants, CommonConstants {
private static final Logger LOG = LoggerFactory.getLogger(NGrinderAgentStarter.class);
private AgentConfig agentConfig;
private AgentControllerDaemon agentController;
/**
* Constructor.
*/
public NGrinderAgentStarter() {
}
public void init() {
// Check agent start mode
this.agentConfig = createAgentConfig();
try {
new ArchLoaderInit().init(agentConfig.getHome().getNativeDirectory());
} catch (Exception e) {
LOG.error("Error while expanding native lib", e);
}
// Configure log.
configureLogging();
}
protected AgentConfig createAgentConfig() {
AgentConfig agentConfig = new AgentConfig();
agentConfig.init();
return agentConfig;
}
private void configureLogging() {
Boolean verboseMode = agentConfig.getCommonProperties().getPropertyBoolean(PROP_COMMON_VERBOSE);
File logDirectory = agentConfig.getHome().getLogDirectory();
configureLogging(verboseMode, logDirectory);
}
/*
* Get the start mode, "agent" or "monitor". If it is not set in configuration, it will return "agent".
*/
public String getStartMode() {
return agentConfig.getCommonProperties().getProperty(PROP_COMMON_START_MODE);
}
/**
* Get agent version.
*
* @return version string
*/
public String getVersion() {
return agentConfig.getInternalProperties().getProperty(PROP_INTERNAL_NGRINDER_VERSION);
}
/**
* Start the performance monitor.
*/
public void startMonitor() {
printLog("***************************************************");
printLog("* Start nGrinder Monitor... ");
printLog("***************************************************");
try {
MonitorServer.getInstance().init(agentConfig);
MonitorServer.getInstance().start();
} catch (Exception e) {
LOG.error("ERROR: {}", e.getMessage());
printHelpAndExit("Error while starting Monitor", e);
}
}
/**
* Stop monitors.
*/
public void stopMonitor() {
MonitorServer.getInstance().stop();
}
/**
* Start ngrinder agent.
*
* @param directControllerIP controllerIp to connect directly;
*/
public void startAgent() {
printLog("***************************************************");
printLog(" Start nGrinder Agent ...");
printLog("***************************************************");
if (StringUtils.isEmpty(System.getenv("JAVA_HOME"))) {
printLog("Hey!! JAVA_HOME env var was not provided. "
+ "Please provide JAVA_HOME env var before running agent."
+ "Otherwise you can not execute the agent in the security mode.");
}
boolean serverMode = agentConfig.isServerMode();
if (!serverMode) {
printLog("JVM server mode is disabled.");
}
String controllerIP = getIP(agentConfig.getControllerIP());
int controllerPort = agentConfig.getControllerPort();
agentConfig.setControllerIP(controllerIP);
LOG.info("connecting to controller {}:{}", controllerIP, controllerPort);
try {
agentController = new AgentControllerDaemon(agentConfig);
agentController.run();
} catch (Exception e) {
LOG.error("Error while connecting to : {}:{}", controllerIP, controllerPort);
printHelpAndExit("Error while starting Agent", e);
}
}
private void printLog(String s, Object... args) {
if (!agentConfig.isSilentMode()) {
LOG.info(s, args);
}
}
/**
* Stop the ngrinder agent.
*/
public void stopAgent() {
LOG.info("Stop nGrinder agent!");
agentController.shutdown();
}
private void configureLogging(boolean verbose, File logDirectory) {
final Context context = (Context) LoggerFactory.getILoggerFactory();
final JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.putProperty("LOG_LEVEL", verbose ? "TRACE" : "INFO");
context.putProperty("LOG_DIRECTORY", logDirectory.getAbsolutePath());
try {
configurator.doConfigure(NGrinderAgentStarter.class.getResource("/logback-agent.xml"));
} catch (JoranException e) {
staticPrintHelpAndExit("Can not configure logger on " + logDirectory.getAbsolutePath()
+ ".\n Please check if it's writable.");
}
}
/**
* Print help and exit. This is provided for mocking.
*
* @param message message
*/
protected void printHelpAndExit(String message) {
staticPrintHelpAndExit(message);
}
/**
* print help and exit. This is provided for mocking.
*
* @param message message
* @param e exception
*/
protected void printHelpAndExit(String message, Exception e) {
staticPrintHelpAndExit(message, e);
}
public static JCommander commander;
/**
* Agent starter.
*
* @param args arguments
*/
public static void main(String[] args) {
NGrinderAgentStarter starter = new NGrinderAgentStarter();
final StarterParam param = new StarterParam();
checkJavaVersion();
commander = new JCommander(param);
commander.setProgramName("ngrinder-agent");
try {
commander.parse(args);
} catch (Exception e) {
System.err.println("[Configuration Error]");
System.err.println(e.getMessage());
commander.usage();
return;
}
if (param.help) {
commander.usage();
return;
}
if (param.controllerIP != null) {
System.setProperty(PROP_AGENT_CONTROLLER_IP, param.controllerIP);
}
if (param.controllerPort != null) {
System.setProperty(PROP_AGENT_CONTROLLER_PORT,
param.controllerPort.toString());
}
if (param.hostId != null) {
System.setProperty(PROP_AGENT_HOST_ID, param.hostId.toString());
}
if (param.region != null) {
System.setProperty(PROP_AGENT_REGION, param.region);
}
if (param.agentHome != null) {
System.setProperty("ngrinder.agent.home", param.agentHome);
}
if (param.overwriteConfig) {
System.setProperty("ngrinder.overwrite.config", "true");
}
System.getProperties().putAll(param.params);
starter.init();
System.out.println("nGrinder v" + starter.getVersion());
String startMode = (param.mode == null) ? starter.getStartMode() : param.mode;
if ("stop".equalsIgnoreCase(param.command)) {
starter.stopProcess(startMode);
- staticPrintHelpAndExit("Stop the " + param.mode);
+ System.out.println("Stop the " + startMode);
return;
}
starter.checkDuplicatedRun(startMode);
if (startMode.equalsIgnoreCase("agent")) {
starter.startAgent();
} else if (startMode.equalsIgnoreCase("monitor")) {
starter.startMonitor();
} else {
staticPrintHelpAndExit("Invalid agent.conf, '-mode' must be set as 'monitor' or 'agent'.");
}
}
static void checkJavaVersion() {
String curJavaVersion = System.getProperty("java.version", "1.6");
checkJavaVersion(curJavaVersion);
}
static void checkJavaVersion(String curJavaVersion) {
if (new VersionNumber(curJavaVersion).compareTo(new VersionNumber("1.6")) < 0) {
LOG.info("- Current java version {} is less than 1.6. nGrinder Agent might not work well", curJavaVersion);
}
}
/**
* Stop process.
*
* @param mode agent or monitor.
*/
protected void stopProcess(String mode) {
String pid = agentConfig.getAgentPidProperties(mode);
try {
if (StringUtils.isNotBlank(pid)) {
new Sigar().kill(pid, 15);
}
agentConfig.updateAgentPidProperties(mode);
} catch (SigarException e) {
printHelpAndExit(String.format("Error occurred while terminating %s process.\n"
+ "It can be already stopped or you may not have the permission.\n"
+ "If everything is OK. Please stop it manually.", mode), e);
}
}
/**
* Check if the process is already running in this env.
*
* @param startMode monitor or agent
*/
public void checkDuplicatedRun(String startMode) {
Sigar sigar = new Sigar();
String existingPid = this.agentConfig.getAgentPidProperties(startMode);
if (StringUtils.isNotEmpty(existingPid)) {
try {
ProcState procState = sigar.getProcState(existingPid);
if (procState.getState() == ProcState.RUN || procState.getState() == ProcState.IDLE
|| procState.getState() == ProcState.SLEEP) {
printHelpAndExit("Currently " + startMode + " is running with pid " + existingPid
+ ". Please stop it before run");
}
agentConfig.updateAgentPidProperties(startMode);
} catch (SigarException e) {
noOp();
}
}
this.agentConfig.saveAgentPidProperties(String.valueOf(sigar.getPid()), startMode);
}
/**
* Check the current directory is valid or not.
* <p/>
* ngrinder agent should run in the folder agent exists.
*
* @return true if it's valid
*/
boolean isValidCurrentDirectory() {
File currentFolder = new File(System.getProperty("user.dir"));
String[] list = currentFolder.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return (name.startsWith("run_agent") && (name.endsWith(".sh") || name.endsWith(".bat")));
}
});
return (list != null && list.length != 0);
}
private static void staticPrintHelpAndExit(String message) {
staticPrintHelpAndExit(message, null);
}
private static void staticPrintHelpAndExit(String message, Exception e) {
if (e == null) {
LOG.error(message);
} else {
LOG.error(message, e);
}
if (commander != null) {
commander.usage();
}
System.exit(-1);
}
}
| true | true | public static void main(String[] args) {
NGrinderAgentStarter starter = new NGrinderAgentStarter();
final StarterParam param = new StarterParam();
checkJavaVersion();
commander = new JCommander(param);
commander.setProgramName("ngrinder-agent");
try {
commander.parse(args);
} catch (Exception e) {
System.err.println("[Configuration Error]");
System.err.println(e.getMessage());
commander.usage();
return;
}
if (param.help) {
commander.usage();
return;
}
if (param.controllerIP != null) {
System.setProperty(PROP_AGENT_CONTROLLER_IP, param.controllerIP);
}
if (param.controllerPort != null) {
System.setProperty(PROP_AGENT_CONTROLLER_PORT,
param.controllerPort.toString());
}
if (param.hostId != null) {
System.setProperty(PROP_AGENT_HOST_ID, param.hostId.toString());
}
if (param.region != null) {
System.setProperty(PROP_AGENT_REGION, param.region);
}
if (param.agentHome != null) {
System.setProperty("ngrinder.agent.home", param.agentHome);
}
if (param.overwriteConfig) {
System.setProperty("ngrinder.overwrite.config", "true");
}
System.getProperties().putAll(param.params);
starter.init();
System.out.println("nGrinder v" + starter.getVersion());
String startMode = (param.mode == null) ? starter.getStartMode() : param.mode;
if ("stop".equalsIgnoreCase(param.command)) {
starter.stopProcess(startMode);
staticPrintHelpAndExit("Stop the " + param.mode);
return;
}
starter.checkDuplicatedRun(startMode);
if (startMode.equalsIgnoreCase("agent")) {
starter.startAgent();
} else if (startMode.equalsIgnoreCase("monitor")) {
starter.startMonitor();
} else {
staticPrintHelpAndExit("Invalid agent.conf, '-mode' must be set as 'monitor' or 'agent'.");
}
}
| public static void main(String[] args) {
NGrinderAgentStarter starter = new NGrinderAgentStarter();
final StarterParam param = new StarterParam();
checkJavaVersion();
commander = new JCommander(param);
commander.setProgramName("ngrinder-agent");
try {
commander.parse(args);
} catch (Exception e) {
System.err.println("[Configuration Error]");
System.err.println(e.getMessage());
commander.usage();
return;
}
if (param.help) {
commander.usage();
return;
}
if (param.controllerIP != null) {
System.setProperty(PROP_AGENT_CONTROLLER_IP, param.controllerIP);
}
if (param.controllerPort != null) {
System.setProperty(PROP_AGENT_CONTROLLER_PORT,
param.controllerPort.toString());
}
if (param.hostId != null) {
System.setProperty(PROP_AGENT_HOST_ID, param.hostId.toString());
}
if (param.region != null) {
System.setProperty(PROP_AGENT_REGION, param.region);
}
if (param.agentHome != null) {
System.setProperty("ngrinder.agent.home", param.agentHome);
}
if (param.overwriteConfig) {
System.setProperty("ngrinder.overwrite.config", "true");
}
System.getProperties().putAll(param.params);
starter.init();
System.out.println("nGrinder v" + starter.getVersion());
String startMode = (param.mode == null) ? starter.getStartMode() : param.mode;
if ("stop".equalsIgnoreCase(param.command)) {
starter.stopProcess(startMode);
System.out.println("Stop the " + startMode);
return;
}
starter.checkDuplicatedRun(startMode);
if (startMode.equalsIgnoreCase("agent")) {
starter.startAgent();
} else if (startMode.equalsIgnoreCase("monitor")) {
starter.startMonitor();
} else {
staticPrintHelpAndExit("Invalid agent.conf, '-mode' must be set as 'monitor' or 'agent'.");
}
}
|
diff --git a/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/DefaultAnnotatedList.java b/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/DefaultAnnotatedList.java
index 7b9bfd7b9..7e19d6640 100644
--- a/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/DefaultAnnotatedList.java
+++ b/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/DefaultAnnotatedList.java
@@ -1,79 +1,80 @@
package com.tinkerpop.blueprints.util;
import com.tinkerpop.blueprints.AnnotatedList;
import com.tinkerpop.blueprints.Annotations;
import com.tinkerpop.blueprints.query.AnnotatedListQuery;
import com.tinkerpop.blueprints.query.util.DefaultAnnotatedListQuery;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class DefaultAnnotatedList<V> implements AnnotatedList<V>, Serializable {
final List<AnnotatedValue<V>> annotatedValues = new ArrayList<>();
public AnnotatedValue<V> addValue(final V value, final Object... keyValues) {
final Annotations annotation = new DefaultAnnotations();
// TODO: Module 2 check
for (int i = 0; i < keyValues.length; i = i + 2) {
annotation.set((String) keyValues[i], keyValues[i + 1]);
}
final AnnotatedValue<V> annotatedValue = new DefaultAnnotatedValue<>(value, annotation);
this.annotatedValues.add(annotatedValue);
return annotatedValue;
}
public AnnotatedListQuery<V> query() {
return new DefaultAnnotatedListQuery<V>(this) {
@Override
public Iterable<AnnotatedValue<V>> annotatedValues() {
return (Iterable) StreamFactory.stream(annotatedValues.iterator())
.filter(p -> HasContainer.testAllOfAnnotatedValue((AnnotatedValue) p, this.hasContainers))
+ .limit(this.limit)
.collect(Collectors.toList());
}
@Override
public Iterable<V> values() {
return (Iterable) StreamFactory.stream(this.annotatedValues()).map(a -> a.getValue()).collect(Collectors.toList());
}
};
}
public String toString() {
return StringFactory.annotatedListString(this);
}
public class DefaultAnnotatedValue<V> implements AnnotatedValue<V> {
private final V value;
private final Annotations annotations;
public DefaultAnnotatedValue(final V value, final Annotations annotations) {
this.value = value;
this.annotations = new DefaultAnnotations();
annotations.getKeys().forEach(k -> this.annotations.set(k, annotations.get(k).get()));
}
public V getValue() {
return this.value;
}
public Annotations getAnnotations() {
return this.annotations;
}
public void remove() {
annotatedValues.remove(this);
}
public String toString() {
return "[" + this.value + ":" + this.annotations + "]";
}
}
}
| true | true | public AnnotatedListQuery<V> query() {
return new DefaultAnnotatedListQuery<V>(this) {
@Override
public Iterable<AnnotatedValue<V>> annotatedValues() {
return (Iterable) StreamFactory.stream(annotatedValues.iterator())
.filter(p -> HasContainer.testAllOfAnnotatedValue((AnnotatedValue) p, this.hasContainers))
.collect(Collectors.toList());
}
@Override
public Iterable<V> values() {
return (Iterable) StreamFactory.stream(this.annotatedValues()).map(a -> a.getValue()).collect(Collectors.toList());
}
};
}
| public AnnotatedListQuery<V> query() {
return new DefaultAnnotatedListQuery<V>(this) {
@Override
public Iterable<AnnotatedValue<V>> annotatedValues() {
return (Iterable) StreamFactory.stream(annotatedValues.iterator())
.filter(p -> HasContainer.testAllOfAnnotatedValue((AnnotatedValue) p, this.hasContainers))
.limit(this.limit)
.collect(Collectors.toList());
}
@Override
public Iterable<V> values() {
return (Iterable) StreamFactory.stream(this.annotatedValues()).map(a -> a.getValue()).collect(Collectors.toList());
}
};
}
|
diff --git a/cadpage/src/net/anei/cadpage/SmsReceiver.java b/cadpage/src/net/anei/cadpage/SmsReceiver.java
index e3f74a415..5ec24c834 100644
--- a/cadpage/src/net/anei/cadpage/SmsReceiver.java
+++ b/cadpage/src/net/anei/cadpage/SmsReceiver.java
@@ -1,52 +1,55 @@
package net.anei.cadpage;
import net.anei.cadpage.ManagePreferences.Defaults;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Log.DEBUG) Log.v("SMSReceiver: onReceive()");
intent.setClass(context, SmsReceiverService.class);
intent.putExtra("result", getResultCode());
/*
* This service will process the activity and show the popup (+ play notifications)
* after it's work is done the service will be stopped.
*/
if (CadPageCall(context,intent)==true){
SmsReceiverService.beginStartingService(context, intent);
}
}
// We need to determine if this message is for us. If so then stop further alerting to the default sms app.
// We have the priority for sms receive set at 100 in the manifest so if we abort the broadcast other apps will not get the message
public boolean CadPageCall(Context context,Intent intent){
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMessage[] messages = SmsPopupUtils.getMessagesFromIntent(intent);
SmsMmsMessage message = new SmsMmsMessage(context, messages,System.currentTimeMillis() );
String strMessage = message.getMessageFull();
// First look at from Filter.
ManagePreferences mPrefs = new ManagePreferences(context, message.getContactId());
- String sfilter = mPrefs.getString(R.string.pref_filter,Defaults.PREFS_FILTER);
- if (sfilter.length() ==1 || sfilter.matches(message.getAddress())){
+ String sfilter = mPrefs.getString(R.string.pref_filter_key,Defaults.PREFS_FILTER);
+ String sAddress = message.getAddress();
+ if (sfilter.length() ==1 || sfilter.matches(sAddress.toString())){
+ if (Log.DEBUG) Log.v("SMSReceiver/CadPageCall: Filter Matches checking call Location -" + sfilter);
if (strMessage.contains("Call:")==true){
this.abortBroadcast();
return true;
} else if (strMessage.contains("TYPE:")==true){
this.abortBroadcast();
return true;
}
}
+ if (Log.DEBUG) Log.v("SMSReceiver/CadPageCall: Filter Did not Match S=" + sfilter + " A="+ sAddress);
}
return false;
}
}
| false | true | public boolean CadPageCall(Context context,Intent intent){
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMessage[] messages = SmsPopupUtils.getMessagesFromIntent(intent);
SmsMmsMessage message = new SmsMmsMessage(context, messages,System.currentTimeMillis() );
String strMessage = message.getMessageFull();
// First look at from Filter.
ManagePreferences mPrefs = new ManagePreferences(context, message.getContactId());
String sfilter = mPrefs.getString(R.string.pref_filter,Defaults.PREFS_FILTER);
if (sfilter.length() ==1 || sfilter.matches(message.getAddress())){
if (strMessage.contains("Call:")==true){
this.abortBroadcast();
return true;
} else if (strMessage.contains("TYPE:")==true){
this.abortBroadcast();
return true;
}
}
}
return false;
}
| public boolean CadPageCall(Context context,Intent intent){
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMessage[] messages = SmsPopupUtils.getMessagesFromIntent(intent);
SmsMmsMessage message = new SmsMmsMessage(context, messages,System.currentTimeMillis() );
String strMessage = message.getMessageFull();
// First look at from Filter.
ManagePreferences mPrefs = new ManagePreferences(context, message.getContactId());
String sfilter = mPrefs.getString(R.string.pref_filter_key,Defaults.PREFS_FILTER);
String sAddress = message.getAddress();
if (sfilter.length() ==1 || sfilter.matches(sAddress.toString())){
if (Log.DEBUG) Log.v("SMSReceiver/CadPageCall: Filter Matches checking call Location -" + sfilter);
if (strMessage.contains("Call:")==true){
this.abortBroadcast();
return true;
} else if (strMessage.contains("TYPE:")==true){
this.abortBroadcast();
return true;
}
}
if (Log.DEBUG) Log.v("SMSReceiver/CadPageCall: Filter Did not Match S=" + sfilter + " A="+ sAddress);
}
return false;
}
|
diff --git a/src/main/java/com/mpower/util/ModifyReportJRXML.java b/src/main/java/com/mpower/util/ModifyReportJRXML.java
index d707daa..27d1ba9 100644
--- a/src/main/java/com/mpower/util/ModifyReportJRXML.java
+++ b/src/main/java/com/mpower/util/ModifyReportJRXML.java
@@ -1,1313 +1,1326 @@
/**
*
*/
package com.mpower.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import ar.com.fdvs.dj.domain.DJChart;
import com.mpower.domain.ReportChartSettings;
import com.mpower.domain.ReportChartSettingsSeries;
import com.mpower.domain.ReportField;
import com.mpower.domain.ReportSelectedField;
import com.mpower.domain.ReportWizard;
import com.mpower.service.ReportFieldService;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
/**
* @author egreen
* <p>
* Object to modify the jrxml document used by jasperserver to generate the report.
*
*/
public class ModifyReportJRXML {
protected final Log logger = LogFactory.getLog(getClass());
private ReportWizard reportWizard;
private ReportFieldService reportFieldService;
/**
* Constructor for the <tt>XMLModifier</tt>.
* @param reportWizard ReportWizard that contains the various report options.
*
*/
public ModifyReportJRXML(ReportWizard reportWizard, ReportFieldService reportFieldService) {
this.setReportWizard(reportWizard);
this.setReportFieldService(reportFieldService);
}
/**
* Removes the scripletHandling class that Dynamic Jasper adds in
* v 3.0.4, JasperServer is not aware of this class and it causes
* an error:
* java.lang.ClassNotFoundException: ar.com.fdvs.dj.core.DJDefaultScriptlet
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*
*/
public void removeDJDefaultScriptlet(String fileName) throws ParserConfigurationException, SAXException, IOException{
Document document = loadXMLDocument(fileName);
Node variable;
Element jasperReport = (Element) document.getElementsByTagName("jasperReport").item(0);
jasperReport.removeAttribute("scriptletClass");
saveXMLtoFile(fileName, document);
}
/**
* Adds the grand totals to the report.
*
* @param fileName The name and path of the jrxml file.
*/
public void AddReportSummaryInfo(String fileName) throws IOException, SAXException, ParserConfigurationException {
Document document = loadXMLDocument(fileName);
Node variable;
NodeList nodeList = document.getElementsByTagName("field");
Node node = nodeList.item(nodeList.getLength()-1).getNextSibling();
Node bkgNode = document.getElementsByTagName("background").item(0);
Node jasperReport = document.getElementsByTagName("jasperReport").item(0);
HashMap<String, Integer> fieldProperties = getColumnStartingPositions(document);
HashMap<String, Integer> fieldWidth = getColumnWidths(document);
//add the "groupElem" node before the background node
Element groupElem = createGroup(document, fieldProperties, fieldWidth, "global_column_0");
if(document.getElementsByTagName("group").item(0) != null)
jasperReport.insertBefore(groupElem, document.getElementsByTagName("group").item(0));
else
jasperReport.insertBefore(groupElem, bkgNode);
//iterate thru the fields to find the summary fields and create the variables
Iterator<?> itFields = getSelectedReportFields().iterator();
Integer columnIndex = 0;
while (itFields.hasNext()){
ReportField f = (ReportField) itFields.next();
if (f.getIsSummarized()){
if (f.getPerformSummary()){
variable = buildVariableNode(f, "Sum", "global_column_0", document, columnIndex);
jasperReport.insertBefore(variable, node);
}
if (f.getAverage()){
variable = buildVariableNode(f, "Average", "global_column_0", document, columnIndex);
jasperReport.insertBefore(variable, node);
}
if (f.getLargestValue()){
variable = buildVariableNode(f, "Highest", "global_column_0", document, columnIndex);
jasperReport.insertBefore(variable, node);
}
if (f.getSmallestValue()){
variable = buildVariableNode(f, "Lowest", "global_column_0", document, columnIndex);
jasperReport.insertBefore(variable, node);
}
if (f.getRecordCount()){
variable = buildVariableNode(f, "Count", "global_column_0", document, columnIndex);
jasperReport.insertBefore(variable, node);
}
}
columnIndex++;
}
saveXMLtoFile(fileName, document);
}
/**
* Add totals to the groups in the report.
*
* @param fileName The name and path of the jrxml file.
*/
public void AddGroupSummaryInfo(String fileName) throws IOException, SAXException, ParserConfigurationException {
Document document = loadXMLDocument(fileName);
NodeList groups = document.getElementsByTagName("group");
NodeList groupFooterNodes = document.getElementsByTagName("groupFooter");
String groupName = null;
Node variable;
Node node = document.getElementsByTagName("group").item(0);
Node jasperReport = document.getElementsByTagName("jasperReport").item(0);
HashMap<String, Integer> fieldProperties = getColumnStartingPositions(document);
HashMap<String, Integer> fieldWidth = getColumnWidths(document);
Integer groupsCount = groups.getLength();
Integer groupFootersCount = groupFooterNodes.getLength();
//remove the groupFooter empty band before adding the new ones
for (int i=0;i<groupFootersCount;i++){
Node groupFooterNode = groupFooterNodes.item(i);
int groupFooterChildrenCount = groupFooterNode.getChildNodes().getLength();
for (int childIndex=groupFooterChildrenCount-1;childIndex>=0;childIndex--){
groupFooterNode.removeChild(groupFooterNode.getChildNodes().item(childIndex));
}
}
//iterate thru the fields to find the summary fields and add the variables and footers
Iterator<?> itFields = getSelectedReportFields().iterator();
boolean addGroup = false;
List<String> groupsToAdd = new ArrayList<String>();
Integer columnIndex = 0;
while (itFields.hasNext()){
ReportField f = (ReportField) itFields.next();
if (f.getIsSummarized()){
for (int i=0;i<groupsCount;i++){
//get the group name
Element group = (Element) groups.item(i);
if (group != null){
groupName = group.getAttribute("name");
if (groupName != null && groupName != ""){
Node groupFooterNode = groupFooterNodes.item(i);
if (f.getPerformSummary()){
variable = buildVariableNode(f, "Sum", groupName, document, columnIndex);
jasperReport.insertBefore(variable, node);
addGroup = true;
}
if (f.getAverage()){
variable = buildVariableNode(f, "Average", groupName, document, columnIndex);
jasperReport.insertBefore(variable, node);
addGroup = true;
}
if (f.getLargestValue()){
variable = buildVariableNode(f, "Highest", groupName, document, columnIndex);
jasperReport.insertBefore(variable, node);
addGroup = true;
}
if (f.getSmallestValue()){
variable = buildVariableNode(f, "Lowest", groupName, document, columnIndex);
jasperReport.insertBefore(variable, node);
addGroup = true;
}
if (f.getRecordCount()){
variable = buildVariableNode(f, "Count", groupName, document, columnIndex);
jasperReport.insertBefore(variable, node);
addGroup = true;
}
if (addGroup)
groupsToAdd.add(groupName);
}
}
}
}
columnIndex++;
}
for (int i=0;i<groupsCount;i++){
//get the group name
Element group = (Element) groups.item(i);
if (group != null){
groupName = group.getAttribute("name");
if (groupName != null && groupName != ""){
Node groupFooterNode = groupFooterNodes.item(i);
groupFooterNode.appendChild(createGroupFooterBand(document, fieldProperties, fieldWidth, groupName));
}
}
}
saveXMLtoFile(fileName, document);
}
/**
* Normalizes and saves the modified XML document.
* @param fileName
* @param document
* @throws IOException
*/
private void saveXMLtoFile(String fileName, Document document)
throws IOException {
document.normalize();
XMLSerializer serializer = new XMLSerializer();
serializer.setOutputCharStream(new java.io.FileWriter(fileName));
serializer.serialize(document);
}
/**
* Parses the XML document and returns a HashMap with the columnName and x starting position.
*
* @param document
* @return HashMap
*/
private HashMap<String, Integer> getColumnStartingPositions(
Document document) {
//
//get the detail node
Node detailNode = document.getElementsByTagName("columnHeader").item(0);
HashMap<String, Integer> fieldProperties = new HashMap<String, Integer>();
//HashMap<String, Integer> fieldWidth = new HashMap<String, Integer>();
//inside the detail node -> textField -> get the textFieldExpression, and the reportelement attr x
NodeList detailChildList = detailNode.getChildNodes();
for (int detailChildIndex=0; detailChildIndex<detailChildList.getLength(); detailChildIndex++) {
if (detailChildList.item(detailChildIndex).getNodeName().equals("band")) {
NodeList textFieldList = detailChildList.item(detailChildIndex).getChildNodes();
for (int textFieldIndex=0; textFieldIndex<textFieldList.getLength(); textFieldIndex++) {
NodeList textFieldProperties = textFieldList.item(textFieldIndex).getChildNodes();
int x = -1;
int width = -1;
String fieldName = null;
for (int textFieldPropertiesIndex=0; textFieldPropertiesIndex<textFieldProperties.getLength(); textFieldPropertiesIndex++) {
if (textFieldProperties.item(textFieldPropertiesIndex).getNodeName().equals("reportElement")) {
x = Integer.parseInt(textFieldProperties.item(textFieldPropertiesIndex).getAttributes().getNamedItem("x").getNodeValue());
width = Integer.parseInt(textFieldProperties.item(textFieldPropertiesIndex).getAttributes().getNamedItem("width").getNodeValue());
} else if (textFieldProperties.item(textFieldPropertiesIndex).getNodeName().equals("textFieldExpression")) {
String cdata = textFieldProperties.item(textFieldPropertiesIndex).getTextContent();
fieldName =cdata.substring(1, cdata.length() - 1);
}
}
if (fieldName != null && x != -1)
fieldProperties.put(fieldName, x);
//fieldWidth.put(fieldName, width );
}
}
}
return fieldProperties;
}
/**
* Parses the XML document and returns a HashMap with the columnName and field width of x.
*
* @param document
* @return HashMap
*/
private HashMap<String, Integer> getColumnWidths(
Document document) {
//parse the document and create a hashmap of the (columnName, x-value)
//get the detail node
Node detailNode = document.getElementsByTagName("columnHeader").item(0);
//HashMap<String, Integer> fieldProperties = new HashMap<String, Integer>();
HashMap<String, Integer> fieldWidth = new HashMap<String, Integer>();
//inside the detail node -> textField -> get the textFieldExpression, and the reportelement attr x
NodeList detailChildList = detailNode.getChildNodes();
for (int detailChildIndex=0; detailChildIndex<detailChildList.getLength(); detailChildIndex++) {
if (detailChildList.item(detailChildIndex).getNodeName().equals("band")) {
NodeList textFieldList = detailChildList.item(detailChildIndex).getChildNodes();
for (int textFieldIndex=0; textFieldIndex<textFieldList.getLength(); textFieldIndex++) {
NodeList textFieldProperties = textFieldList.item(textFieldIndex).getChildNodes();
int x = -1;
int width = -1;
String fieldName = null;
for (int textFieldPropertiesIndex=0; textFieldPropertiesIndex<textFieldProperties.getLength(); textFieldPropertiesIndex++) {
if (textFieldProperties.item(textFieldPropertiesIndex).getNodeName().equals("reportElement")) {
x = Integer.parseInt(textFieldProperties.item(textFieldPropertiesIndex).getAttributes().getNamedItem("x").getNodeValue());
width = Integer.parseInt(textFieldProperties.item(textFieldPropertiesIndex).getAttributes().getNamedItem("width").getNodeValue());
} else if (textFieldProperties.item(textFieldPropertiesIndex).getNodeName().equals("textFieldExpression")) {
String cdata = textFieldProperties.item(textFieldPropertiesIndex).getTextContent();
fieldName = cdata.substring(1, cdata.length() - 1);
}
}
if (fieldName != null && x != -1)
//fieldProperties.put(fieldName, x);
fieldWidth.put(fieldName, width );
}
}
}
return fieldWidth;
}
/**
* Loads the XML document.
* @param fileName
* @return
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
private Document loadXMLDocument(String fileName)
throws ParserConfigurationException, SAXException, IOException {
// Load the report xml document
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
String localDTDFile = getLocalDirName() + "jasperreport.dtd";
LocalDTDResolver LocalDTDResolver
= new LocalDTDResolver(
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd",
new File(localDTDFile)
);
documentBuilder.setEntityResolver( LocalDTDResolver );
Document document = documentBuilder.parse(new File(fileName));
return document;
}
private String getClassName()
{
String thisClassName;
//Build a string with executing class's name
thisClassName = this.getClass().getName();
thisClassName = thisClassName.substring(thisClassName.lastIndexOf(".") + 1,thisClassName.length());
thisClassName += ".class"; //this is the name of the bytecode file that is executing
return thisClassName;
}
private String getLocalDirName()
{
String localDirName;
//Use that name to get a URL to the directory we are executing in
java.net.URL myURL = this.getClass().getResource(getClassName()); //Open a URL to the our .class file
//Clean up the URL and make a String with absolute path name
localDirName = myURL.getPath(); //Strip path to URL object out
localDirName = myURL.getPath().replaceAll("%20", " "); //change %20 chars to spaces
//Get the current execution directory
localDirName = localDirName.substring(0,localDirName.lastIndexOf("classes")); //clean off the file name
localDirName += "lib/";
if ( ! localDirName.startsWith("file:/")) {
localDirName = "file:/" + localDirName;
}
return localDirName;
}
private Element createGroup(Document document,
HashMap<String, Integer> fieldProperties,
HashMap<String, Integer> fieldWidth,
String resetGroup) {
//create the "group" element
Element group = document.createElement("group");
group.setAttribute("name", resetGroup);
//create child "groupExpression" of the "group" element with a CDATA section
Element groupExp = document.createElement("groupExpression");
groupExp.appendChild(document.createCDATASection("\"Total\""));
group.appendChild(groupExp);
//create child "groupHeader" of the "group" element
Element groupHeader = document.createElement("groupHeader");
group.appendChild(groupHeader);
//create child "headerBand" of the "groupHeader" element
Element headerBand = document.createElement("band");
groupHeader.appendChild(headerBand);
//create groupFooter
group.appendChild(createGroupFooter(document, fieldProperties, fieldWidth, resetGroup));
return group;
}
/**
* Adds a groupFooter to the Jasper Report. <br/>
* Groups can be nested.<br/><br/>
*
* Example:<br/>
* {@code} group.appendChild(createGroupFooter(document, fieldProperties, fieldWidth, resetGroup));
*
* @param document XML Document.
* @param fieldProperties Hashmap that contains the columnName and the x-starting position of the column.
* @param fieldWidth Hashmap that contains the columnName and the width of the column.
* @param resetGroup Name of the Group.
* @return Element
*/
private Element createGroupFooter(Document document,
HashMap<String, Integer> fieldProperties,
HashMap<String, Integer> fieldWidth,
String resetGroup) {
//create child "groupFooter" of the "group" element
Element groupFooter = document.createElement("groupFooter");
//create child "band" of "groupfooter" with attr
Element band = document.createElement("band");
band.setAttribute("height", "150");
groupFooter.appendChild(createGroupFooterBand(document, fieldProperties, fieldWidth, resetGroup));
return groupFooter;
}
/**
* Adds a groupFooter Band to the Jasper Report. <br/>
* Groups can be nested.<br/><br/>
*
* Example:<br/>
* {@code} group.appendChild(createGroupFooter(document, fieldProperties, fieldWidth, resetGroup));
*
* @param document XML Document.
* @param fieldProperties Hashmap that contains the columnName and the x-starting position of the column.
* @param fieldWidth Hashmap that contains the columnName and the width of the column.
* @param resetGroup Name of the Group.
* @return Element
*/
private Element createGroupFooterBand(Document document,
HashMap<String, Integer> fieldProperties,
HashMap<String, Integer> fieldWidth,
String resetGroup) {
//
//Variables
Integer bandTotalHeight = 0;
Integer rowHeight = 16;
int y = 0;
int x = 0;
int width = 0;
int xCalc = 0;
int widthCalc = 0;
int totalWidth = 0;
int columnIndex= 0;
//get the total width
Iterator<?> itTotalFieldWidth = getSelectedReportFields().iterator();
while (itTotalFieldWidth.hasNext()){
ReportField fWidth = (ReportField) itTotalFieldWidth.next();
int lastColumnX = fieldProperties.get(fWidth.getDisplayName());
int lastColumnWidth = fieldWidth.get(fWidth.getDisplayName());
totalWidth = lastColumnX + lastColumnWidth;
}
//create child "band" of "groupfooter" with attr
Element band = document.createElement("band");
Element frame = document.createElement("frame");
Element rptElementFrame = document.createElement("reportElement");
frame.appendChild(rptElementFrame);
Element box = document.createElement("box");
frame.appendChild(box);
Element rectangle = document.createElement("rectangle");
frame.appendChild(rectangle);
Element rptElementRectangle = document.createElement("reportElement");
rectangle.appendChild(rptElementRectangle);
Element graphicElement = document.createElement("graphicElement");
rectangle.appendChild(graphicElement);
Element pen = document.createElement("pen");
graphicElement.appendChild(pen);
//Add the group Label to the footer section
if (resetGroup.compareToIgnoreCase("global_column_0") == 0){
x = 0;
width = totalWidth;
frame.appendChild(buildSummaryLabel("Grand Totals", document, 0, 0, width, rowHeight, false, null, 0));
frame.appendChild(addLine(document, 1, rowHeight+1, totalWidth));
y += rowHeight*2+2;
}
else{
Iterator<?> itFieldsGroupLabel = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsGroupLabel.hasNext()){
ReportField fLabel = (ReportField) itFieldsGroupLabel.next();
if (fLabel.getGroupBy()){//(reportWizard.IsFieldGroupByField(fLabel.getId())){
x = fieldProperties.get(fLabel.getDisplayName());
width = fieldWidth.get(fLabel.getDisplayName());
String groupColumn = resetGroup.substring(resetGroup.indexOf("-") + 1);
if (fLabel.getDisplayName().compareToIgnoreCase(groupColumn) == 0){
frame.appendChild(buildSummaryLabel(null, document, x, y, totalWidth - x, rowHeight, true, fLabel, columnIndex));
frame.appendChild(addLine(document, 1, y+rowHeight+1, totalWidth));
y += rowHeight*2+2;
break;
}
}
columnIndex++;
}
}
//Add the sum/total to the footer section
Boolean yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsSum = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsSum.hasNext()){
ReportField f = (ReportField) itFieldsSum.next();
if (f.getIsSummarized()){
if (f.getPerformSummary()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Sum", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Sum", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the average to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsAvg = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsAvg.hasNext()){
ReportField f = (ReportField) itFieldsAvg.next();
if (f.getIsSummarized()){
if (f.getAverage()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Average", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Avg", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the max to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsMax = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsMax.hasNext()){
ReportField f = (ReportField) itFieldsMax.next();
if (f.getIsSummarized()){
if (f.getLargestValue()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Highest", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Max", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the min to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsMin = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsMin.hasNext()){
ReportField f = (ReportField) itFieldsMin.next();
if (f.getIsSummarized()){
if (f.getSmallestValue()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Lowest", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Min", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add count to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsCount = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsCount.hasNext()){
ReportField f = (ReportField) itFieldsCount.next();
if (f.getIsSummarized()){
if (f.getRecordCount()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Count", resetGroup, document, xCalc, widthCalc, y+1, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));//(xCalc + widthCalc)-x)
frame.appendChild(buildSummaryLabel("Count", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
bandTotalHeight = y - rowHeight + 4;
Integer frameHeight = bandTotalHeight;
rptElementFrame.setAttribute("stretchType", "RelativeToBandHeight");
rptElementFrame.setAttribute("mode", "Opaque");
rptElementFrame.setAttribute("x", "0"); //Integer.toString(x)
rptElementFrame.setAttribute("y", "0");
int frameWidth = 0;
frameWidth = (totalWidth + 4);
rptElementFrame.setAttribute("width", Integer.toString(frameWidth));
rptElementFrame.setAttribute("height", frameHeight.toString());
rptElementFrame.setAttribute("backcolor", "#EEEFEF");
box.setAttribute("topPadding", "1");
box.setAttribute("leftPadding", "1");
box.setAttribute("bottomPadding", "1");
box.setAttribute("rightPadding", "1");
//rectangle
rectangle.setAttribute("radius", "10");
rptElementRectangle.setAttribute("mode", "Transparent");
rptElementRectangle.setAttribute("x", "0"); //Integer.toString(x)
rptElementRectangle.setAttribute("y", "0");
rptElementRectangle.setAttribute("width", Integer.toString(frameWidth - 2));
rptElementRectangle.setAttribute("height", Integer.toString(frameHeight - 2));
rptElementRectangle.setAttribute("forecolor", "#666666");
rptElementRectangle.setAttribute("backcolor", "#666666");
pen.setAttribute("lineStyle", "Double");
band.appendChild(frame);
band.setAttribute("height", bandTotalHeight.toString());
return band;
}
/**
* @param document
* @param frame
*/
private Node addLine(Document document, int x, int y, int width) {
Element line = document.createElement("line");
//frame.appendChild(line);
Element rptElementLine = document.createElement("reportElement");
line.appendChild(rptElementLine);
rptElementLine.setAttribute("x", Integer.toString(x));
rptElementLine.setAttribute("y", Integer.toString(y));
rptElementLine.setAttribute("width", Integer.toString(width));
rptElementLine.setAttribute("height", "1");
rptElementLine.setAttribute("forecolor", "#999999");
return line;
}
/**
* create child "textField" of "band" with attributes
*/
private Node buildSummaryNodes(ReportField f, String calc, String resetGroup, Document document, int x, int width, int y, int height, int columnIndex) {
String varName = null;
String valueClassName = null;
String pattern = null;
String columnName = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
columnName = f.getColumnName() + "_" + columnIndex;
else
columnName = f.getAliasName() + "_" + columnIndex;
//set the field data type
if (calc.compareToIgnoreCase("count") == 0){
valueClassName = Long.class.getName();
pattern ="";
}else{
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); pattern =""; break;
case STRING: valueClassName = String.class.getName(); pattern =""; break;
case INTEGER: valueClassName = Long.class.getName(); pattern =""; break;
case DOUBLE: valueClassName = Double.class.getName(); pattern =""; break;
case DATE: valueClassName = Date.class.getName(); pattern ="MM/dd/yyyy"; break;
case MONEY: valueClassName = Float.class.getName(); pattern ="$ 0.00"; break;
case BOOLEAN: valueClassName = Boolean.class.getName();pattern ="";
}
}
if (resetGroup.compareToIgnoreCase("global_column_0") == 0)
varName = "variable-footer_global_" + columnName + "_" + calc;
else
varName = "variable-footer_" + resetGroup + "_" + columnName + "_" + calc;
Element textField = document.createElement("textField");
textField.setAttribute("isStretchWithOverflow", "true");
textField.setAttribute("evaluationTime", "Group");
textField.setAttribute("evaluationGroup", resetGroup);
textField.setAttribute("pattern", pattern);
//band.appendChild(textField);
//create child "reportElement" of "textField" with attr
Element reportElement = document.createElement("reportElement");
reportElement.setAttribute("key", varName);
//reportElement.setAttribute("style", "dj_style_1");
reportElement.setAttribute("positionType", "Float");
reportElement.setAttribute("stretchType", "RelativeToTallestObject");
reportElement.setAttribute("x", Integer.toString(x));
reportElement.setAttribute("y", Integer.toString(y));
reportElement.setAttribute("width", Integer.toString(width));
reportElement.setAttribute("height", Integer.toString(height));
// reportElement.setAttribute("style", "SummaryStyle");
textField.appendChild(reportElement);
//create child "textElement" of "textField" (it's empty)
Element textElement = document.createElement("textElement");
textField.appendChild(textElement);
////create child "textFieldExpression" of "textField" with attr
Element textFieldExpression = document.createElement("textFieldExpression");
textFieldExpression.setAttribute("class", valueClassName);
textFieldExpression.appendChild(document.createCDATASection("$V{" + varName + "}"));
textField.appendChild(textFieldExpression);
return textField;
}
/**
* Adds the static text labels to the report.
*/
private Node buildSummaryLabel(String calc, Document document, int x, int y, int width, int height, Boolean groupHeaderFlag, ReportField f, int columnIndex) {
Element textField2 = document.createElement("textField");
Element reportElement2 = document.createElement("reportElement");
reportElement2.setAttribute("key", "global_legend_footer_" + calc);
//reportElement2.setAttribute("style", "dj_style_2");
reportElement2.setAttribute("x", Integer.toString(x));
reportElement2.setAttribute("y", Integer.toString(y));
reportElement2.setAttribute("width", Integer.toString(width));
reportElement2.setAttribute("height", Integer.toString(height));
textField2.appendChild(reportElement2);
//create child "textElement" of "textField" (it's empty)
Element textElement2 = document.createElement("textElement");
textField2.appendChild(textElement2);
////create child "textFieldExpression" of "textField" with attr
Element textFieldExpression2 = document.createElement("textFieldExpression");
String valueClassName = String.class.getName();
if (groupHeaderFlag){
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); break;
case STRING: valueClassName = String.class.getName(); break;
case INTEGER: valueClassName = Long.class.getName(); break;
case DOUBLE: valueClassName = Double.class.getName(); break;
case DATE: valueClassName = Date.class.getName(); break;
case MONEY: valueClassName = Float.class.getName(); break;
case BOOLEAN: valueClassName = Boolean.class.getName();
}
String groupColumn = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
groupColumn = f.getColumnName() + "_" + columnIndex;
else
groupColumn = f.getAliasName() + "_" + columnIndex;
textFieldExpression2.appendChild(document.createCDATASection("$F{" + groupColumn + "}"));
//reportElement2.setAttribute("style", "SummaryStyle");
}
else{
textFieldExpression2.appendChild(document.createCDATASection("\"" + calc + "\""));
//reportElement2.setAttribute("style", "SummaryStyleBlue");
}
textFieldExpression2.setAttribute("class", valueClassName);
textField2.appendChild(textFieldExpression2);
return textField2;
}
/**
* Adds a variable to the JRXML/Jasper Report to store the specified calculation.
*
* @param columnName Used in the variable name.
* @param calc Calculation to be performed.
* @param resetGroup Name of the group that the calculation will be performed on.
* @param document XML document.
* @return Element
*/
private Node buildVariableNode(ReportField f, String calc, String resetGroup, Document document, Integer columnIndex ) {
String varName = null;
String columnName = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
columnName = f.getColumnName() + "_" + columnIndex;
else
columnName = f.getAliasName() + "_" + columnIndex;
String valueClassName = null;
String initialize = "()";
//set the field data type
if (calc.compareToIgnoreCase("count") == 0){
valueClassName = Long.class.getName();
initialize = "(\"0\")";
}else{
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); break;
case STRING: valueClassName = String.class.getName(); break;
case INTEGER: valueClassName = Long.class.getName(); initialize = "(\"0\")"; break;
case DOUBLE: valueClassName = Double.class.getName(); initialize = "(\"0\")"; break;
case DATE: valueClassName = Date.class.getName(); break;
case MONEY: valueClassName = Float.class.getName(); initialize = "(\"0\")"; break;
case BOOLEAN: valueClassName = Boolean.class.getName();
}
}
int test1 = new Integer(3);
long test = new Long(0);
if (resetGroup.compareToIgnoreCase("global_column_0") == 0)
varName = "variable-footer_global_" + columnName + "_" + calc;
else
varName = "variable-footer_" + resetGroup + "_" + columnName + "_" + calc;
Element variable = document.createElement("variable");
variable.setAttribute("name", varName);
variable.setAttribute("class", valueClassName);
variable.setAttribute("resetType", "Group");
variable.setAttribute("resetGroup", resetGroup);
variable.setAttribute("calculation", calc);
Element variableExpression = document.createElement("variableExpression");
variableExpression.appendChild(document.createCDATASection("$F{" + columnName + "}"));
variable.appendChild(variableExpression);
Element initialValueExpression = document.createElement("initialValueExpression");
initialValueExpression.appendChild(document.createCDATASection("new " + valueClassName + initialize));
variable.appendChild(initialValueExpression);
return variable;
}
/**
* Fixes the "category series is null" and "key is null" for the pie and bar charts
*
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param document The jrxml document.
*/
public void correctNullDataInChart(String chartType, Document document, List<ReportChartSettings> rcsList){
//TODO: right now we just allow one chart per report but when we change for multiple charts this will need to be refactored
//to iterate thru the list
ReportChartSettings rcs = rcsList.get(0);
if (!chartType.toLowerCase().contains("pie")){
//get the categoryExpression node
Node categoryExp = null;
if (chartType.equalsIgnoreCase("timeSeries") || chartType.equalsIgnoreCase("scatter") || chartType.toLowerCase().startsWith("xy")){
correctChartVariableForCountOperation(chartType, document, rcs);
addChartLabels(chartType, document, rcs);
return;
//You can not have null dates in the group by field
//so for now you need to add criteria in the guru to exclude null dates
//when using timeSeries, scatter or xy charts
//categoryExp = document.getElementsByTagName("timePeriodExpression").item(0);
}else {
categoryExp = document.getElementsByTagName("categoryExpression").item(0);
}
//String categoryExpField = categoryExp.getTextContent();
//String newcategoryExp = "(( " + categoryExpField + " != null) ? " + categoryExpField + ".toString() : \"null\" )";
categoryExp.setTextContent(correctNullDataField(categoryExp.getTextContent(), "null"));
//get the seriesExpression node
NodeList seriesNodes = document.getElementsByTagName("seriesExpression");
for (int i = 0; i < seriesNodes.getLength(); i++){
Node seriesExp = document.getElementsByTagName("seriesExpression").item(i);
//String seriesExpField = seriesExp.getTextContent();
//String newseriesExp = "(( " + seriesExpField + " != null) ? " + seriesExpField + ".toString() : \"null\" )";
seriesExp.setTextContent(correctNullDataField(seriesExp.getTextContent(), "null"));
}
//set the label expression
Node labelExp = document.getElementsByTagName("labelExpression").item(0);
String labelExpField = labelExp.getTextContent();
String newlabelExp = labelExpField + ".toString()";
labelExp.setTextContent(newlabelExp);
}else if (chartType.toLowerCase().contains("pie")){
//get the keyExpression node
Node keyExp = document.getElementsByTagName("keyExpression").item(0);
//String keyExpField = keyExp.getTextContent();
//String newkeyExp = "(( " + keyExpField + " != null) ? " + keyExpField + ".toString() : \"null\" )";
keyExp.setTextContent(correctNullDataField(keyExp.getTextContent(), "null"));
}
correctChartVariableForCountOperation(chartType, document, rcs);
addChartLabels(chartType, document, rcs);
}
public void correctChartVariableForCountOperation(String chartType, Document document, ReportChartSettings rcs){
for (ReportChartSettingsSeries thisRcs : rcs.getReportChartSettingsSeries()){
if (thisRcs.getOperation() != null && thisRcs.getOperation().equals("RecordCount") ){
NodeList variableNodeList = document.getElementsByTagName("variable");
for (int index = 0; index < variableNodeList.getLength(); index++) {
Node variableNode = variableNodeList.item(index);
String nodeName = variableNode.getAttributes().getNamedItem("name").getNodeValue();
if (nodeName.contains("CHART")
&& nodeName.contains(thisRcs.getSeriesColumn().getTitle())
&& nodeName.contains(rcs.getCategory().getName())) {
variableNode.getAttributes().getNamedItem("class").setNodeValue("java.lang.Number");
}
}
}
}
}
public void addChartLabels(String chartType, Document document, ReportChartSettings rcs){
//set title expression
if (rcs.getChartTitle() != null && !rcs.getChartTitle().isEmpty()){
Node titleExp = document.getElementsByTagName("titleExpression").item(0);
if (titleExp == null){
titleExp = document.createElement("titleExpression");
titleExp.setTextContent("\"" + rcs.getChartTitle() + "\"");
Node subTitleNodeParent = document.getElementsByTagName("chartTitle").item(0);
subTitleNodeParent.appendChild(titleExp);
}else {
titleExp.setTextContent("\"" + rcs.getChartTitle() + "\"");
}
}
//set subtitle expression
if (rcs.getChartSubTitle() != null && !rcs.getChartSubTitle().isEmpty()){
Node subTitleExp = document.getElementsByTagName("subtitleExpression").item(0);
if (subTitleExp == null){
subTitleExp = document.createElement("subtitleExpression");
subTitleExp.setTextContent("\"" + rcs.getChartSubTitle() + "\"");
Node subTitleNodeParent = document.getElementsByTagName("chartSubtitle").item(0);
subTitleNodeParent.appendChild(subTitleExp);
}else {
subTitleExp.setTextContent("\"" + rcs.getChartSubTitle() + "\"");
}
}
- if (!chartType.toLowerCase().contains("pie")){
- //set categoryAxisLabelExpression
- if (rcs.getCategoryAxisLabel() != null && !rcs.getCategoryAxisLabel().isEmpty()){
+ if ((!chartType.toLowerCase().contains("pie")) && (rcs.getCategoryAxisLabel() != null && !rcs.getCategoryAxisLabel().isEmpty())){
+ if (chartType.equalsIgnoreCase("timeSeries")){
+ Node timeAxisLabelExpression = document.getElementsByTagName("timeAxisLabelExpression").item(0);
+ if (timeAxisLabelExpression == null){
+ //add the node as it is not there
+ //it goes before timeAxisFormat node
+ Node timeAxisFormatNode = document.getElementsByTagName("timeAxisFormat").item(0);
+ timeAxisLabelExpression = document.createElement("timeAxisLabelExpression");
+ timeAxisLabelExpression.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
+ Node categoryAxisFormatNodeParent = document.getElementsByTagName(timeAxisFormatNode.getParentNode().getNodeName()).item(0);
+ categoryAxisFormatNodeParent.insertBefore(timeAxisLabelExpression, timeAxisFormatNode);
+ }else{
+ timeAxisLabelExpression.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
+ }
+ }else {
+ //set categoryAxisLabelExpression
Node categoryAxisLabelExp = document.getElementsByTagName("categoryAxisLabelExpression").item(0);
if (categoryAxisLabelExp == null){
//add the node as it is not there
//it goes before categoryAxisFormat node
Node categoryAxisFormatNode = document.getElementsByTagName("categoryAxisFormat").item(0);
categoryAxisLabelExp = document.createElement("categoryAxisLabelExpression");
categoryAxisLabelExp.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
Node categoryAxisFormatNodeParent = document.getElementsByTagName(categoryAxisFormatNode.getParentNode().getNodeName()).item(0);
categoryAxisFormatNodeParent.insertBefore(categoryAxisLabelExp, categoryAxisFormatNode);
}else{
categoryAxisLabelExp.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
}
}
//set valueAxisLabelExpression
if (rcs.getValueAxisLabel() != null && !rcs.getValueAxisLabel().isEmpty()){
Node valueAxisLabelExp = document.getElementsByTagName("valueAxisLabelExpression").item(0);
if (valueAxisLabelExp == null){
//add the node as it is not there
//it goes before valueAxisFormat node
Node valueAxisFormatNode = document.getElementsByTagName("valueAxisFormat").item(0);
valueAxisLabelExp = document.createElement("valueAxisLabelExpression");
valueAxisLabelExp.setTextContent("\"" + rcs.getValueAxisLabel() + "\"");
Node valueAxisFormatNodeParent = document.getElementsByTagName(valueAxisFormatNode.getParentNode().getNodeName()).item(0);
valueAxisFormatNodeParent.insertBefore(valueAxisLabelExp, valueAxisFormatNode);
}else{
valueAxisLabelExp.setTextContent("\"" + rcs.getValueAxisLabel() + "\"");
}
}
}
}
public String correctNullDataField(String infield, String replaceNullWith){
return "(( " + infield + " != null) ? " + infield + ".toString() : \" "+ replaceNullWith +"\" )";
}
/**
* Fixes a bug with pie charts only showing the first group. This bug
* was a result of the upgrade to Jasperserver 3.5 and will hopefully go
* away when we upgrade dyamic jasper.
*
* @param chartType The type of chart.
* @param document The jrxml document.
*/
public void correctPieChartEvaluationTime(String chartType, Document document){
if (chartType.toLowerCase().contains("pie")){
//get the chart node
Element chartElement = (Element)document.getElementsByTagName("chart").item(0);
//change the attribute evaluationTime from "Group" to "Report"
chartElement.getAttributeNode("evaluationTime").setValue("Report");
}
}
/**
* Removes the chart from the group created by dynamic jasper and
* puts it in the title or lastPageFooter section of the report.
*
* @param fileName file name of the XML document
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param location The location you want to put the chart. (header or footer)
*/
public void moveChartFromGroup(String fileName, String chartType, String location, List<ReportChartSettings> rcsList) throws ParserConfigurationException, SAXException, IOException{
//Find the chart node copy it
String chart = getChartNodeName(chartType);
if (chart != null){
Document document = loadXMLDocument(fileName);
//correct the "category series is null" and "key is null" errors
//before moving chart
correctNullDataInChart(chartType, document, rcsList);
//correct bug with pie chart due to upgrade to JS 3.5
if (chart.toLowerCase().contains("pie"))
correctPieChartEvaluationTime(chartType, document);
Node chartNode = document.getElementsByTagName(chart).item(0);
if (chartNode != null){
Element chartElement = (Element) chartNode;
Element chartRptElement = (Element) chartElement.getElementsByTagName("reportElement").item(0);
//Add the printwhenexpression to the chart report element if it goes in the header
if (location.compareToIgnoreCase("header") == 0){
Element printWhenExpression = document.createElement("printWhenExpression");
printWhenExpression.appendChild(document.createCDATASection("new java.lang.Boolean(((Number)$V{PAGE_NUMBER}).doubleValue() == 1)"));
chartRptElement.appendChild(printWhenExpression);
}
//change the band height back to 0
Element band = (Element) chartElement.getParentNode();
Integer bandHeight = Integer.decode(band.getAttribute("height"));
band.setAttribute("height", "0");
//remove the group footer band node from the group added for the chart
Element chartGroup = (Element) band.getParentNode().getParentNode();
Node groupFooter = (Element) chartGroup.getElementsByTagName("groupFooter").item(0);
Node groupFooterBand = (Element) ((Element) groupFooter).getElementsByTagName("band").item(0);
groupFooter.replaceChild((Node) document.createElement("band"), groupFooterBand);
//remove the chart node
removeAll(document, Node.ELEMENT_NODE, chart);
//add the copied chart node to the title band or the last page footer
String position = null;
if (location.compareTo("header") == 0)
position = "title";
else
position = "lastPageFooter";
Element positionNode = (Element) document.getElementsByTagName(position).item(0);
Element positionBandNode = (Element) positionNode.getElementsByTagName("band").item(0);
Integer positionBandHeight = Integer.decode(positionBandNode.getAttribute("height"));
// set the y value on the chart depends on the position of the chart
//set the new band height to allow room for the chart
if (position.compareTo("title") == 0){
chartRptElement.setAttribute("y", positionBandHeight.toString());
Integer newpositionNodeBandHeight = positionBandHeight + bandHeight;
positionBandNode.setAttribute("height", newpositionNodeBandHeight.toString());
}
else{
//change the y for the other elements in the last page footer so the chart is above them
NodeList rptElementsInLastPgFt = positionBandNode.getElementsByTagName("reportElement");
Integer newpositionNodeBandHeight = positionBandHeight + bandHeight;
Integer numberOfRptElements = rptElementsInLastPgFt.getLength();
for (int i = 0; i < numberOfRptElements; i++){
Integer yRptElement = Integer.decode(((Element) rptElementsInLastPgFt.item(i)).getAttribute("y"));
Integer yForOtherElements = yRptElement + bandHeight;
((Element) rptElementsInLastPgFt.item(i)).setAttribute("y", yForOtherElements.toString());
}
chartRptElement.setAttribute("y", "0");
positionBandNode.setAttribute("height", newpositionNodeBandHeight.toString());
}
positionBandNode.appendChild(chartNode);
saveXMLtoFile(fileName, document);
}
}
}
private String getChartNodeName(String chartType) {
String chart;
if (chartType.compareToIgnoreCase("area") == 0)
chart = "areaChart";
else if (chartType.compareToIgnoreCase("bar") == 0)
chart = "barChart";
else if (chartType.compareToIgnoreCase("bar3d") == 0)
chart = "bar3DChart";
else if (chartType.compareToIgnoreCase("line") == 0)
chart = "lineChart";
else if (chartType.compareToIgnoreCase("pie") == 0)
chart = "pieChart";
else if (chartType.compareToIgnoreCase("pie3d") == 0)
chart = "pie3DChart";
else if (chartType.compareToIgnoreCase("scatter") == 0)
chart = "scatterChart";
else if (chartType.compareToIgnoreCase("stackedarea") == 0)
chart = "stackedAreaChart";
else if (chartType.compareToIgnoreCase("stackedbar") == 0)
chart = "stackedBarChart";
else if (chartType.compareToIgnoreCase("stackedbar3d") == 0)
chart = "stackedBar3DChart";
else if (chartType.compareToIgnoreCase("timeseries") == 0)
chart = "timeSeriesChart";
else if (chartType.compareToIgnoreCase("xyarea") == 0)
chart = "xyAreaChart";
else if (chartType.compareToIgnoreCase("xybar") == 0)
chart = "xyBarChart";
else if (chartType.compareToIgnoreCase("xyline") == 0)
chart = "xyLineChart";
else
chart = null;
return chart;
}
/**
* Removes all elements from the report except the chart and
* places the chart in the summary section of the report.
*
* @param fileName file name of the XML document
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param location The location you want to put the chart. (header or footer)
*/
public void modifyChartOnlyReport(String fileName, String chartType, String location) throws ParserConfigurationException, SAXException, IOException{
String chart = getChartNodeName(chartType);
if (chart != null){
Document document = loadXMLDocument(fileName);
//copy the chart element
Node chartNode = document.getElementsByTagName(chart).item(0);
Element chartElement = (Element) chartNode;
//remove all unneeded elements
removeAll(document, Node.ELEMENT_NODE, "style");
removeAll(document, Node.ELEMENT_NODE, "groupHeader");
removeAll(document, Node.ELEMENT_NODE, "groupFooter");
removeAll(document, Node.ELEMENT_NODE, "background");
removeAll(document, Node.ELEMENT_NODE, "title");
removeAll(document, Node.ELEMENT_NODE, "pageHeader");
removeAll(document, Node.ELEMENT_NODE, "columnHeader");
removeAll(document, Node.ELEMENT_NODE, "detail");
removeAll(document, Node.ELEMENT_NODE, "columnFooter");
removeAll(document, Node.ELEMENT_NODE, "pageFooter");
removeAll(document, Node.ELEMENT_NODE, "lastPageFooter");
removeAll(document, Node.ELEMENT_NODE, "summary");
//set the size of the chart to width="330" height="220" (this size is defined by the OL dashboard)
String height = "220";
String width = "330";
Element chartNodeElement = (Element) chartElement.getElementsByTagName("chart").item(0);
Element chartReportElement = (Element) chartNodeElement.getElementsByTagName("reportElement").item(0);
if (chartReportElement != null){
chartReportElement.setAttribute("width", width);
chartReportElement.setAttribute("height", height);
}
//create a new summary node
Element summaryNode = document.createElement("summary");
Element summaryBand = document.createElement("band");
summaryBand.setAttribute("height", height);
//add the copied chart to the summary band
summaryBand.appendChild(chartElement);
//add the summaryBand to the summary node
summaryNode.appendChild(summaryBand);
//add the new summary node that contains the chart (this will replace the existing summary node)
Node jasperReport = document.getElementsByTagName("jasperReport").item(0);
jasperReport.appendChild(summaryNode);
saveXMLtoFile(fileName, document);
}
}
/*
*
*/
public void removeCrossTabDataSubset(String fileName) throws ParserConfigurationException, SAXException, IOException {
Document document = loadXMLDocument(fileName);
// Remove datasetRun element from the report xml
removeAll(document, Node.ELEMENT_NODE, "datasetRun");
// Remove detail element from the report xml
removeAll(document, Node.ELEMENT_NODE, "detail");
// Remove detail element from the report xml
removeAll(document, Node.ELEMENT_NODE, "columnHeader");
saveXMLtoFile(fileName, document);
}
public static void removeAll(Node node, short nodeType, String name) {
if (node.getNodeType() == nodeType &&
(name == null || node.getNodeName().equals(name))) {
node.getParentNode().removeChild(node);
} else {
// Visit the children
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
removeAll(list.item(i), nodeType, name);
}
}
}
private List<ReportField> getSelectedReportFields() {
Iterator<ReportSelectedField> itReportSelectedFields = reportWizard.getReportSelectedFields().iterator();
List<ReportField> selectedReportFieldsList = new LinkedList<ReportField>();
Integer columnIndex = 0;
while (itReportSelectedFields.hasNext()){
ReportSelectedField reportSelectedField = (ReportSelectedField) itReportSelectedFields.next();
if (reportSelectedField == null) continue;
ReportField f = reportFieldService.find(reportSelectedField.getFieldId());
if (f == null || f.getId() == -1) continue;
ReportField newField = new ReportField();
newField.setId(f.getId());
newField.setAliasName(f.getAliasName());
newField.setCanBeSummarized(f.getCanBeSummarized());
newField.setColumnName(f.getColumnName());
newField.setDisplayName(f.getDisplayName());
newField.setFieldType(f.getFieldType());
newField.setIsDefault(f.getIsDefault());
newField.setPrimaryKeys(f.getPrimaryKeys());
newField.setAverage(reportSelectedField.getAverage());
newField.setIsSummarized(reportSelectedField.getIsSummarized());
newField.setLargestValue(reportSelectedField.getMax());
newField.setSmallestValue(reportSelectedField.getMin());
newField.setPerformSummary(reportSelectedField.getSum());
newField.setRecordCount(reportSelectedField.getCount());
newField.setGroupBy(reportSelectedField.getGroupBy());
newField.setSelected(true);
//f.setDynamicColumnName(f.getColumnName() + "_" + columnIndex.toString());
//columnIndex++;
selectedReportFieldsList.add(newField);
}
return selectedReportFieldsList;
}
/**
* Sets the ReportWizard that contains the various report options.
* @param reportWizard
*/
public void setReportWizard(ReportWizard reportWizard) {
this.reportWizard = reportWizard;
}
/**
* Returns the ReportWizard that contains the various report options.
* @return
*/
public ReportWizard getReportWizard() {
return reportWizard;
}
public void setReportFieldService(ReportFieldService reportFieldService) {
this.reportFieldService = reportFieldService;
}
public ReportFieldService getReportFieldService() {
return reportFieldService;
}
}
| true | true | private Element createGroupFooterBand(Document document,
HashMap<String, Integer> fieldProperties,
HashMap<String, Integer> fieldWidth,
String resetGroup) {
//
//Variables
Integer bandTotalHeight = 0;
Integer rowHeight = 16;
int y = 0;
int x = 0;
int width = 0;
int xCalc = 0;
int widthCalc = 0;
int totalWidth = 0;
int columnIndex= 0;
//get the total width
Iterator<?> itTotalFieldWidth = getSelectedReportFields().iterator();
while (itTotalFieldWidth.hasNext()){
ReportField fWidth = (ReportField) itTotalFieldWidth.next();
int lastColumnX = fieldProperties.get(fWidth.getDisplayName());
int lastColumnWidth = fieldWidth.get(fWidth.getDisplayName());
totalWidth = lastColumnX + lastColumnWidth;
}
//create child "band" of "groupfooter" with attr
Element band = document.createElement("band");
Element frame = document.createElement("frame");
Element rptElementFrame = document.createElement("reportElement");
frame.appendChild(rptElementFrame);
Element box = document.createElement("box");
frame.appendChild(box);
Element rectangle = document.createElement("rectangle");
frame.appendChild(rectangle);
Element rptElementRectangle = document.createElement("reportElement");
rectangle.appendChild(rptElementRectangle);
Element graphicElement = document.createElement("graphicElement");
rectangle.appendChild(graphicElement);
Element pen = document.createElement("pen");
graphicElement.appendChild(pen);
//Add the group Label to the footer section
if (resetGroup.compareToIgnoreCase("global_column_0") == 0){
x = 0;
width = totalWidth;
frame.appendChild(buildSummaryLabel("Grand Totals", document, 0, 0, width, rowHeight, false, null, 0));
frame.appendChild(addLine(document, 1, rowHeight+1, totalWidth));
y += rowHeight*2+2;
}
else{
Iterator<?> itFieldsGroupLabel = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsGroupLabel.hasNext()){
ReportField fLabel = (ReportField) itFieldsGroupLabel.next();
if (fLabel.getGroupBy()){//(reportWizard.IsFieldGroupByField(fLabel.getId())){
x = fieldProperties.get(fLabel.getDisplayName());
width = fieldWidth.get(fLabel.getDisplayName());
String groupColumn = resetGroup.substring(resetGroup.indexOf("-") + 1);
if (fLabel.getDisplayName().compareToIgnoreCase(groupColumn) == 0){
frame.appendChild(buildSummaryLabel(null, document, x, y, totalWidth - x, rowHeight, true, fLabel, columnIndex));
frame.appendChild(addLine(document, 1, y+rowHeight+1, totalWidth));
y += rowHeight*2+2;
break;
}
}
columnIndex++;
}
}
//Add the sum/total to the footer section
Boolean yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsSum = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsSum.hasNext()){
ReportField f = (ReportField) itFieldsSum.next();
if (f.getIsSummarized()){
if (f.getPerformSummary()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Sum", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Sum", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the average to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsAvg = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsAvg.hasNext()){
ReportField f = (ReportField) itFieldsAvg.next();
if (f.getIsSummarized()){
if (f.getAverage()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Average", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Avg", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the max to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsMax = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsMax.hasNext()){
ReportField f = (ReportField) itFieldsMax.next();
if (f.getIsSummarized()){
if (f.getLargestValue()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Highest", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Max", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the min to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsMin = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsMin.hasNext()){
ReportField f = (ReportField) itFieldsMin.next();
if (f.getIsSummarized()){
if (f.getSmallestValue()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Lowest", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Min", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add count to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsCount = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsCount.hasNext()){
ReportField f = (ReportField) itFieldsCount.next();
if (f.getIsSummarized()){
if (f.getRecordCount()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Count", resetGroup, document, xCalc, widthCalc, y+1, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));//(xCalc + widthCalc)-x)
frame.appendChild(buildSummaryLabel("Count", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
bandTotalHeight = y - rowHeight + 4;
Integer frameHeight = bandTotalHeight;
rptElementFrame.setAttribute("stretchType", "RelativeToBandHeight");
rptElementFrame.setAttribute("mode", "Opaque");
rptElementFrame.setAttribute("x", "0"); //Integer.toString(x)
rptElementFrame.setAttribute("y", "0");
int frameWidth = 0;
frameWidth = (totalWidth + 4);
rptElementFrame.setAttribute("width", Integer.toString(frameWidth));
rptElementFrame.setAttribute("height", frameHeight.toString());
rptElementFrame.setAttribute("backcolor", "#EEEFEF");
box.setAttribute("topPadding", "1");
box.setAttribute("leftPadding", "1");
box.setAttribute("bottomPadding", "1");
box.setAttribute("rightPadding", "1");
//rectangle
rectangle.setAttribute("radius", "10");
rptElementRectangle.setAttribute("mode", "Transparent");
rptElementRectangle.setAttribute("x", "0"); //Integer.toString(x)
rptElementRectangle.setAttribute("y", "0");
rptElementRectangle.setAttribute("width", Integer.toString(frameWidth - 2));
rptElementRectangle.setAttribute("height", Integer.toString(frameHeight - 2));
rptElementRectangle.setAttribute("forecolor", "#666666");
rptElementRectangle.setAttribute("backcolor", "#666666");
pen.setAttribute("lineStyle", "Double");
band.appendChild(frame);
band.setAttribute("height", bandTotalHeight.toString());
return band;
}
/**
* @param document
* @param frame
*/
private Node addLine(Document document, int x, int y, int width) {
Element line = document.createElement("line");
//frame.appendChild(line);
Element rptElementLine = document.createElement("reportElement");
line.appendChild(rptElementLine);
rptElementLine.setAttribute("x", Integer.toString(x));
rptElementLine.setAttribute("y", Integer.toString(y));
rptElementLine.setAttribute("width", Integer.toString(width));
rptElementLine.setAttribute("height", "1");
rptElementLine.setAttribute("forecolor", "#999999");
return line;
}
/**
* create child "textField" of "band" with attributes
*/
private Node buildSummaryNodes(ReportField f, String calc, String resetGroup, Document document, int x, int width, int y, int height, int columnIndex) {
String varName = null;
String valueClassName = null;
String pattern = null;
String columnName = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
columnName = f.getColumnName() + "_" + columnIndex;
else
columnName = f.getAliasName() + "_" + columnIndex;
//set the field data type
if (calc.compareToIgnoreCase("count") == 0){
valueClassName = Long.class.getName();
pattern ="";
}else{
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); pattern =""; break;
case STRING: valueClassName = String.class.getName(); pattern =""; break;
case INTEGER: valueClassName = Long.class.getName(); pattern =""; break;
case DOUBLE: valueClassName = Double.class.getName(); pattern =""; break;
case DATE: valueClassName = Date.class.getName(); pattern ="MM/dd/yyyy"; break;
case MONEY: valueClassName = Float.class.getName(); pattern ="$ 0.00"; break;
case BOOLEAN: valueClassName = Boolean.class.getName();pattern ="";
}
}
if (resetGroup.compareToIgnoreCase("global_column_0") == 0)
varName = "variable-footer_global_" + columnName + "_" + calc;
else
varName = "variable-footer_" + resetGroup + "_" + columnName + "_" + calc;
Element textField = document.createElement("textField");
textField.setAttribute("isStretchWithOverflow", "true");
textField.setAttribute("evaluationTime", "Group");
textField.setAttribute("evaluationGroup", resetGroup);
textField.setAttribute("pattern", pattern);
//band.appendChild(textField);
//create child "reportElement" of "textField" with attr
Element reportElement = document.createElement("reportElement");
reportElement.setAttribute("key", varName);
//reportElement.setAttribute("style", "dj_style_1");
reportElement.setAttribute("positionType", "Float");
reportElement.setAttribute("stretchType", "RelativeToTallestObject");
reportElement.setAttribute("x", Integer.toString(x));
reportElement.setAttribute("y", Integer.toString(y));
reportElement.setAttribute("width", Integer.toString(width));
reportElement.setAttribute("height", Integer.toString(height));
// reportElement.setAttribute("style", "SummaryStyle");
textField.appendChild(reportElement);
//create child "textElement" of "textField" (it's empty)
Element textElement = document.createElement("textElement");
textField.appendChild(textElement);
////create child "textFieldExpression" of "textField" with attr
Element textFieldExpression = document.createElement("textFieldExpression");
textFieldExpression.setAttribute("class", valueClassName);
textFieldExpression.appendChild(document.createCDATASection("$V{" + varName + "}"));
textField.appendChild(textFieldExpression);
return textField;
}
/**
* Adds the static text labels to the report.
*/
private Node buildSummaryLabel(String calc, Document document, int x, int y, int width, int height, Boolean groupHeaderFlag, ReportField f, int columnIndex) {
Element textField2 = document.createElement("textField");
Element reportElement2 = document.createElement("reportElement");
reportElement2.setAttribute("key", "global_legend_footer_" + calc);
//reportElement2.setAttribute("style", "dj_style_2");
reportElement2.setAttribute("x", Integer.toString(x));
reportElement2.setAttribute("y", Integer.toString(y));
reportElement2.setAttribute("width", Integer.toString(width));
reportElement2.setAttribute("height", Integer.toString(height));
textField2.appendChild(reportElement2);
//create child "textElement" of "textField" (it's empty)
Element textElement2 = document.createElement("textElement");
textField2.appendChild(textElement2);
////create child "textFieldExpression" of "textField" with attr
Element textFieldExpression2 = document.createElement("textFieldExpression");
String valueClassName = String.class.getName();
if (groupHeaderFlag){
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); break;
case STRING: valueClassName = String.class.getName(); break;
case INTEGER: valueClassName = Long.class.getName(); break;
case DOUBLE: valueClassName = Double.class.getName(); break;
case DATE: valueClassName = Date.class.getName(); break;
case MONEY: valueClassName = Float.class.getName(); break;
case BOOLEAN: valueClassName = Boolean.class.getName();
}
String groupColumn = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
groupColumn = f.getColumnName() + "_" + columnIndex;
else
groupColumn = f.getAliasName() + "_" + columnIndex;
textFieldExpression2.appendChild(document.createCDATASection("$F{" + groupColumn + "}"));
//reportElement2.setAttribute("style", "SummaryStyle");
}
else{
textFieldExpression2.appendChild(document.createCDATASection("\"" + calc + "\""));
//reportElement2.setAttribute("style", "SummaryStyleBlue");
}
textFieldExpression2.setAttribute("class", valueClassName);
textField2.appendChild(textFieldExpression2);
return textField2;
}
/**
* Adds a variable to the JRXML/Jasper Report to store the specified calculation.
*
* @param columnName Used in the variable name.
* @param calc Calculation to be performed.
* @param resetGroup Name of the group that the calculation will be performed on.
* @param document XML document.
* @return Element
*/
private Node buildVariableNode(ReportField f, String calc, String resetGroup, Document document, Integer columnIndex ) {
String varName = null;
String columnName = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
columnName = f.getColumnName() + "_" + columnIndex;
else
columnName = f.getAliasName() + "_" + columnIndex;
String valueClassName = null;
String initialize = "()";
//set the field data type
if (calc.compareToIgnoreCase("count") == 0){
valueClassName = Long.class.getName();
initialize = "(\"0\")";
}else{
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); break;
case STRING: valueClassName = String.class.getName(); break;
case INTEGER: valueClassName = Long.class.getName(); initialize = "(\"0\")"; break;
case DOUBLE: valueClassName = Double.class.getName(); initialize = "(\"0\")"; break;
case DATE: valueClassName = Date.class.getName(); break;
case MONEY: valueClassName = Float.class.getName(); initialize = "(\"0\")"; break;
case BOOLEAN: valueClassName = Boolean.class.getName();
}
}
int test1 = new Integer(3);
long test = new Long(0);
if (resetGroup.compareToIgnoreCase("global_column_0") == 0)
varName = "variable-footer_global_" + columnName + "_" + calc;
else
varName = "variable-footer_" + resetGroup + "_" + columnName + "_" + calc;
Element variable = document.createElement("variable");
variable.setAttribute("name", varName);
variable.setAttribute("class", valueClassName);
variable.setAttribute("resetType", "Group");
variable.setAttribute("resetGroup", resetGroup);
variable.setAttribute("calculation", calc);
Element variableExpression = document.createElement("variableExpression");
variableExpression.appendChild(document.createCDATASection("$F{" + columnName + "}"));
variable.appendChild(variableExpression);
Element initialValueExpression = document.createElement("initialValueExpression");
initialValueExpression.appendChild(document.createCDATASection("new " + valueClassName + initialize));
variable.appendChild(initialValueExpression);
return variable;
}
/**
* Fixes the "category series is null" and "key is null" for the pie and bar charts
*
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param document The jrxml document.
*/
public void correctNullDataInChart(String chartType, Document document, List<ReportChartSettings> rcsList){
//TODO: right now we just allow one chart per report but when we change for multiple charts this will need to be refactored
//to iterate thru the list
ReportChartSettings rcs = rcsList.get(0);
if (!chartType.toLowerCase().contains("pie")){
//get the categoryExpression node
Node categoryExp = null;
if (chartType.equalsIgnoreCase("timeSeries") || chartType.equalsIgnoreCase("scatter") || chartType.toLowerCase().startsWith("xy")){
correctChartVariableForCountOperation(chartType, document, rcs);
addChartLabels(chartType, document, rcs);
return;
//You can not have null dates in the group by field
//so for now you need to add criteria in the guru to exclude null dates
//when using timeSeries, scatter or xy charts
//categoryExp = document.getElementsByTagName("timePeriodExpression").item(0);
}else {
categoryExp = document.getElementsByTagName("categoryExpression").item(0);
}
//String categoryExpField = categoryExp.getTextContent();
//String newcategoryExp = "(( " + categoryExpField + " != null) ? " + categoryExpField + ".toString() : \"null\" )";
categoryExp.setTextContent(correctNullDataField(categoryExp.getTextContent(), "null"));
//get the seriesExpression node
NodeList seriesNodes = document.getElementsByTagName("seriesExpression");
for (int i = 0; i < seriesNodes.getLength(); i++){
Node seriesExp = document.getElementsByTagName("seriesExpression").item(i);
//String seriesExpField = seriesExp.getTextContent();
//String newseriesExp = "(( " + seriesExpField + " != null) ? " + seriesExpField + ".toString() : \"null\" )";
seriesExp.setTextContent(correctNullDataField(seriesExp.getTextContent(), "null"));
}
//set the label expression
Node labelExp = document.getElementsByTagName("labelExpression").item(0);
String labelExpField = labelExp.getTextContent();
String newlabelExp = labelExpField + ".toString()";
labelExp.setTextContent(newlabelExp);
}else if (chartType.toLowerCase().contains("pie")){
//get the keyExpression node
Node keyExp = document.getElementsByTagName("keyExpression").item(0);
//String keyExpField = keyExp.getTextContent();
//String newkeyExp = "(( " + keyExpField + " != null) ? " + keyExpField + ".toString() : \"null\" )";
keyExp.setTextContent(correctNullDataField(keyExp.getTextContent(), "null"));
}
correctChartVariableForCountOperation(chartType, document, rcs);
addChartLabels(chartType, document, rcs);
}
public void correctChartVariableForCountOperation(String chartType, Document document, ReportChartSettings rcs){
for (ReportChartSettingsSeries thisRcs : rcs.getReportChartSettingsSeries()){
if (thisRcs.getOperation() != null && thisRcs.getOperation().equals("RecordCount") ){
NodeList variableNodeList = document.getElementsByTagName("variable");
for (int index = 0; index < variableNodeList.getLength(); index++) {
Node variableNode = variableNodeList.item(index);
String nodeName = variableNode.getAttributes().getNamedItem("name").getNodeValue();
if (nodeName.contains("CHART")
&& nodeName.contains(thisRcs.getSeriesColumn().getTitle())
&& nodeName.contains(rcs.getCategory().getName())) {
variableNode.getAttributes().getNamedItem("class").setNodeValue("java.lang.Number");
}
}
}
}
}
public void addChartLabels(String chartType, Document document, ReportChartSettings rcs){
//set title expression
if (rcs.getChartTitle() != null && !rcs.getChartTitle().isEmpty()){
Node titleExp = document.getElementsByTagName("titleExpression").item(0);
if (titleExp == null){
titleExp = document.createElement("titleExpression");
titleExp.setTextContent("\"" + rcs.getChartTitle() + "\"");
Node subTitleNodeParent = document.getElementsByTagName("chartTitle").item(0);
subTitleNodeParent.appendChild(titleExp);
}else {
titleExp.setTextContent("\"" + rcs.getChartTitle() + "\"");
}
}
//set subtitle expression
if (rcs.getChartSubTitle() != null && !rcs.getChartSubTitle().isEmpty()){
Node subTitleExp = document.getElementsByTagName("subtitleExpression").item(0);
if (subTitleExp == null){
subTitleExp = document.createElement("subtitleExpression");
subTitleExp.setTextContent("\"" + rcs.getChartSubTitle() + "\"");
Node subTitleNodeParent = document.getElementsByTagName("chartSubtitle").item(0);
subTitleNodeParent.appendChild(subTitleExp);
}else {
subTitleExp.setTextContent("\"" + rcs.getChartSubTitle() + "\"");
}
}
if (!chartType.toLowerCase().contains("pie")){
//set categoryAxisLabelExpression
if (rcs.getCategoryAxisLabel() != null && !rcs.getCategoryAxisLabel().isEmpty()){
Node categoryAxisLabelExp = document.getElementsByTagName("categoryAxisLabelExpression").item(0);
if (categoryAxisLabelExp == null){
//add the node as it is not there
//it goes before categoryAxisFormat node
Node categoryAxisFormatNode = document.getElementsByTagName("categoryAxisFormat").item(0);
categoryAxisLabelExp = document.createElement("categoryAxisLabelExpression");
categoryAxisLabelExp.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
Node categoryAxisFormatNodeParent = document.getElementsByTagName(categoryAxisFormatNode.getParentNode().getNodeName()).item(0);
categoryAxisFormatNodeParent.insertBefore(categoryAxisLabelExp, categoryAxisFormatNode);
}else{
categoryAxisLabelExp.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
}
}
//set valueAxisLabelExpression
if (rcs.getValueAxisLabel() != null && !rcs.getValueAxisLabel().isEmpty()){
Node valueAxisLabelExp = document.getElementsByTagName("valueAxisLabelExpression").item(0);
if (valueAxisLabelExp == null){
//add the node as it is not there
//it goes before valueAxisFormat node
Node valueAxisFormatNode = document.getElementsByTagName("valueAxisFormat").item(0);
valueAxisLabelExp = document.createElement("valueAxisLabelExpression");
valueAxisLabelExp.setTextContent("\"" + rcs.getValueAxisLabel() + "\"");
Node valueAxisFormatNodeParent = document.getElementsByTagName(valueAxisFormatNode.getParentNode().getNodeName()).item(0);
valueAxisFormatNodeParent.insertBefore(valueAxisLabelExp, valueAxisFormatNode);
}else{
valueAxisLabelExp.setTextContent("\"" + rcs.getValueAxisLabel() + "\"");
}
}
}
}
public String correctNullDataField(String infield, String replaceNullWith){
return "(( " + infield + " != null) ? " + infield + ".toString() : \" "+ replaceNullWith +"\" )";
}
/**
* Fixes a bug with pie charts only showing the first group. This bug
* was a result of the upgrade to Jasperserver 3.5 and will hopefully go
* away when we upgrade dyamic jasper.
*
* @param chartType The type of chart.
* @param document The jrxml document.
*/
public void correctPieChartEvaluationTime(String chartType, Document document){
if (chartType.toLowerCase().contains("pie")){
//get the chart node
Element chartElement = (Element)document.getElementsByTagName("chart").item(0);
//change the attribute evaluationTime from "Group" to "Report"
chartElement.getAttributeNode("evaluationTime").setValue("Report");
}
}
/**
* Removes the chart from the group created by dynamic jasper and
* puts it in the title or lastPageFooter section of the report.
*
* @param fileName file name of the XML document
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param location The location you want to put the chart. (header or footer)
*/
public void moveChartFromGroup(String fileName, String chartType, String location, List<ReportChartSettings> rcsList) throws ParserConfigurationException, SAXException, IOException{
//Find the chart node copy it
String chart = getChartNodeName(chartType);
if (chart != null){
Document document = loadXMLDocument(fileName);
//correct the "category series is null" and "key is null" errors
//before moving chart
correctNullDataInChart(chartType, document, rcsList);
//correct bug with pie chart due to upgrade to JS 3.5
if (chart.toLowerCase().contains("pie"))
correctPieChartEvaluationTime(chartType, document);
Node chartNode = document.getElementsByTagName(chart).item(0);
if (chartNode != null){
Element chartElement = (Element) chartNode;
Element chartRptElement = (Element) chartElement.getElementsByTagName("reportElement").item(0);
//Add the printwhenexpression to the chart report element if it goes in the header
if (location.compareToIgnoreCase("header") == 0){
Element printWhenExpression = document.createElement("printWhenExpression");
printWhenExpression.appendChild(document.createCDATASection("new java.lang.Boolean(((Number)$V{PAGE_NUMBER}).doubleValue() == 1)"));
chartRptElement.appendChild(printWhenExpression);
}
//change the band height back to 0
Element band = (Element) chartElement.getParentNode();
Integer bandHeight = Integer.decode(band.getAttribute("height"));
band.setAttribute("height", "0");
//remove the group footer band node from the group added for the chart
Element chartGroup = (Element) band.getParentNode().getParentNode();
Node groupFooter = (Element) chartGroup.getElementsByTagName("groupFooter").item(0);
Node groupFooterBand = (Element) ((Element) groupFooter).getElementsByTagName("band").item(0);
groupFooter.replaceChild((Node) document.createElement("band"), groupFooterBand);
//remove the chart node
removeAll(document, Node.ELEMENT_NODE, chart);
//add the copied chart node to the title band or the last page footer
String position = null;
if (location.compareTo("header") == 0)
position = "title";
else
position = "lastPageFooter";
Element positionNode = (Element) document.getElementsByTagName(position).item(0);
Element positionBandNode = (Element) positionNode.getElementsByTagName("band").item(0);
Integer positionBandHeight = Integer.decode(positionBandNode.getAttribute("height"));
// set the y value on the chart depends on the position of the chart
//set the new band height to allow room for the chart
if (position.compareTo("title") == 0){
chartRptElement.setAttribute("y", positionBandHeight.toString());
Integer newpositionNodeBandHeight = positionBandHeight + bandHeight;
positionBandNode.setAttribute("height", newpositionNodeBandHeight.toString());
}
else{
//change the y for the other elements in the last page footer so the chart is above them
NodeList rptElementsInLastPgFt = positionBandNode.getElementsByTagName("reportElement");
Integer newpositionNodeBandHeight = positionBandHeight + bandHeight;
Integer numberOfRptElements = rptElementsInLastPgFt.getLength();
for (int i = 0; i < numberOfRptElements; i++){
Integer yRptElement = Integer.decode(((Element) rptElementsInLastPgFt.item(i)).getAttribute("y"));
Integer yForOtherElements = yRptElement + bandHeight;
((Element) rptElementsInLastPgFt.item(i)).setAttribute("y", yForOtherElements.toString());
}
chartRptElement.setAttribute("y", "0");
positionBandNode.setAttribute("height", newpositionNodeBandHeight.toString());
}
positionBandNode.appendChild(chartNode);
saveXMLtoFile(fileName, document);
}
}
}
private String getChartNodeName(String chartType) {
String chart;
if (chartType.compareToIgnoreCase("area") == 0)
chart = "areaChart";
else if (chartType.compareToIgnoreCase("bar") == 0)
chart = "barChart";
else if (chartType.compareToIgnoreCase("bar3d") == 0)
chart = "bar3DChart";
else if (chartType.compareToIgnoreCase("line") == 0)
chart = "lineChart";
else if (chartType.compareToIgnoreCase("pie") == 0)
chart = "pieChart";
else if (chartType.compareToIgnoreCase("pie3d") == 0)
chart = "pie3DChart";
else if (chartType.compareToIgnoreCase("scatter") == 0)
chart = "scatterChart";
else if (chartType.compareToIgnoreCase("stackedarea") == 0)
chart = "stackedAreaChart";
else if (chartType.compareToIgnoreCase("stackedbar") == 0)
chart = "stackedBarChart";
else if (chartType.compareToIgnoreCase("stackedbar3d") == 0)
chart = "stackedBar3DChart";
else if (chartType.compareToIgnoreCase("timeseries") == 0)
chart = "timeSeriesChart";
else if (chartType.compareToIgnoreCase("xyarea") == 0)
chart = "xyAreaChart";
else if (chartType.compareToIgnoreCase("xybar") == 0)
chart = "xyBarChart";
else if (chartType.compareToIgnoreCase("xyline") == 0)
chart = "xyLineChart";
else
chart = null;
return chart;
}
/**
* Removes all elements from the report except the chart and
* places the chart in the summary section of the report.
*
* @param fileName file name of the XML document
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param location The location you want to put the chart. (header or footer)
*/
public void modifyChartOnlyReport(String fileName, String chartType, String location) throws ParserConfigurationException, SAXException, IOException{
String chart = getChartNodeName(chartType);
if (chart != null){
Document document = loadXMLDocument(fileName);
//copy the chart element
Node chartNode = document.getElementsByTagName(chart).item(0);
Element chartElement = (Element) chartNode;
//remove all unneeded elements
removeAll(document, Node.ELEMENT_NODE, "style");
removeAll(document, Node.ELEMENT_NODE, "groupHeader");
removeAll(document, Node.ELEMENT_NODE, "groupFooter");
removeAll(document, Node.ELEMENT_NODE, "background");
removeAll(document, Node.ELEMENT_NODE, "title");
removeAll(document, Node.ELEMENT_NODE, "pageHeader");
removeAll(document, Node.ELEMENT_NODE, "columnHeader");
removeAll(document, Node.ELEMENT_NODE, "detail");
removeAll(document, Node.ELEMENT_NODE, "columnFooter");
removeAll(document, Node.ELEMENT_NODE, "pageFooter");
removeAll(document, Node.ELEMENT_NODE, "lastPageFooter");
removeAll(document, Node.ELEMENT_NODE, "summary");
//set the size of the chart to width="330" height="220" (this size is defined by the OL dashboard)
String height = "220";
String width = "330";
Element chartNodeElement = (Element) chartElement.getElementsByTagName("chart").item(0);
Element chartReportElement = (Element) chartNodeElement.getElementsByTagName("reportElement").item(0);
if (chartReportElement != null){
chartReportElement.setAttribute("width", width);
chartReportElement.setAttribute("height", height);
}
//create a new summary node
Element summaryNode = document.createElement("summary");
Element summaryBand = document.createElement("band");
summaryBand.setAttribute("height", height);
//add the copied chart to the summary band
summaryBand.appendChild(chartElement);
//add the summaryBand to the summary node
summaryNode.appendChild(summaryBand);
//add the new summary node that contains the chart (this will replace the existing summary node)
Node jasperReport = document.getElementsByTagName("jasperReport").item(0);
jasperReport.appendChild(summaryNode);
saveXMLtoFile(fileName, document);
}
}
/*
*
*/
public void removeCrossTabDataSubset(String fileName) throws ParserConfigurationException, SAXException, IOException {
Document document = loadXMLDocument(fileName);
// Remove datasetRun element from the report xml
removeAll(document, Node.ELEMENT_NODE, "datasetRun");
// Remove detail element from the report xml
removeAll(document, Node.ELEMENT_NODE, "detail");
// Remove detail element from the report xml
removeAll(document, Node.ELEMENT_NODE, "columnHeader");
saveXMLtoFile(fileName, document);
}
public static void removeAll(Node node, short nodeType, String name) {
if (node.getNodeType() == nodeType &&
(name == null || node.getNodeName().equals(name))) {
node.getParentNode().removeChild(node);
} else {
// Visit the children
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
removeAll(list.item(i), nodeType, name);
}
}
}
private List<ReportField> getSelectedReportFields() {
Iterator<ReportSelectedField> itReportSelectedFields = reportWizard.getReportSelectedFields().iterator();
List<ReportField> selectedReportFieldsList = new LinkedList<ReportField>();
Integer columnIndex = 0;
while (itReportSelectedFields.hasNext()){
ReportSelectedField reportSelectedField = (ReportSelectedField) itReportSelectedFields.next();
if (reportSelectedField == null) continue;
ReportField f = reportFieldService.find(reportSelectedField.getFieldId());
if (f == null || f.getId() == -1) continue;
ReportField newField = new ReportField();
newField.setId(f.getId());
newField.setAliasName(f.getAliasName());
newField.setCanBeSummarized(f.getCanBeSummarized());
newField.setColumnName(f.getColumnName());
newField.setDisplayName(f.getDisplayName());
newField.setFieldType(f.getFieldType());
newField.setIsDefault(f.getIsDefault());
newField.setPrimaryKeys(f.getPrimaryKeys());
newField.setAverage(reportSelectedField.getAverage());
newField.setIsSummarized(reportSelectedField.getIsSummarized());
newField.setLargestValue(reportSelectedField.getMax());
newField.setSmallestValue(reportSelectedField.getMin());
newField.setPerformSummary(reportSelectedField.getSum());
newField.setRecordCount(reportSelectedField.getCount());
newField.setGroupBy(reportSelectedField.getGroupBy());
newField.setSelected(true);
//f.setDynamicColumnName(f.getColumnName() + "_" + columnIndex.toString());
//columnIndex++;
selectedReportFieldsList.add(newField);
}
return selectedReportFieldsList;
}
/**
* Sets the ReportWizard that contains the various report options.
* @param reportWizard
*/
public void setReportWizard(ReportWizard reportWizard) {
this.reportWizard = reportWizard;
}
/**
* Returns the ReportWizard that contains the various report options.
* @return
*/
public ReportWizard getReportWizard() {
return reportWizard;
}
public void setReportFieldService(ReportFieldService reportFieldService) {
this.reportFieldService = reportFieldService;
}
public ReportFieldService getReportFieldService() {
return reportFieldService;
}
}
| private Element createGroupFooterBand(Document document,
HashMap<String, Integer> fieldProperties,
HashMap<String, Integer> fieldWidth,
String resetGroup) {
//
//Variables
Integer bandTotalHeight = 0;
Integer rowHeight = 16;
int y = 0;
int x = 0;
int width = 0;
int xCalc = 0;
int widthCalc = 0;
int totalWidth = 0;
int columnIndex= 0;
//get the total width
Iterator<?> itTotalFieldWidth = getSelectedReportFields().iterator();
while (itTotalFieldWidth.hasNext()){
ReportField fWidth = (ReportField) itTotalFieldWidth.next();
int lastColumnX = fieldProperties.get(fWidth.getDisplayName());
int lastColumnWidth = fieldWidth.get(fWidth.getDisplayName());
totalWidth = lastColumnX + lastColumnWidth;
}
//create child "band" of "groupfooter" with attr
Element band = document.createElement("band");
Element frame = document.createElement("frame");
Element rptElementFrame = document.createElement("reportElement");
frame.appendChild(rptElementFrame);
Element box = document.createElement("box");
frame.appendChild(box);
Element rectangle = document.createElement("rectangle");
frame.appendChild(rectangle);
Element rptElementRectangle = document.createElement("reportElement");
rectangle.appendChild(rptElementRectangle);
Element graphicElement = document.createElement("graphicElement");
rectangle.appendChild(graphicElement);
Element pen = document.createElement("pen");
graphicElement.appendChild(pen);
//Add the group Label to the footer section
if (resetGroup.compareToIgnoreCase("global_column_0") == 0){
x = 0;
width = totalWidth;
frame.appendChild(buildSummaryLabel("Grand Totals", document, 0, 0, width, rowHeight, false, null, 0));
frame.appendChild(addLine(document, 1, rowHeight+1, totalWidth));
y += rowHeight*2+2;
}
else{
Iterator<?> itFieldsGroupLabel = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsGroupLabel.hasNext()){
ReportField fLabel = (ReportField) itFieldsGroupLabel.next();
if (fLabel.getGroupBy()){//(reportWizard.IsFieldGroupByField(fLabel.getId())){
x = fieldProperties.get(fLabel.getDisplayName());
width = fieldWidth.get(fLabel.getDisplayName());
String groupColumn = resetGroup.substring(resetGroup.indexOf("-") + 1);
if (fLabel.getDisplayName().compareToIgnoreCase(groupColumn) == 0){
frame.appendChild(buildSummaryLabel(null, document, x, y, totalWidth - x, rowHeight, true, fLabel, columnIndex));
frame.appendChild(addLine(document, 1, y+rowHeight+1, totalWidth));
y += rowHeight*2+2;
break;
}
}
columnIndex++;
}
}
//Add the sum/total to the footer section
Boolean yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsSum = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsSum.hasNext()){
ReportField f = (ReportField) itFieldsSum.next();
if (f.getIsSummarized()){
if (f.getPerformSummary()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Sum", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Sum", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the average to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsAvg = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsAvg.hasNext()){
ReportField f = (ReportField) itFieldsAvg.next();
if (f.getIsSummarized()){
if (f.getAverage()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Average", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Avg", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the max to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsMax = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsMax.hasNext()){
ReportField f = (ReportField) itFieldsMax.next();
if (f.getIsSummarized()){
if (f.getLargestValue()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Highest", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Max", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add the min to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsMin = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsMin.hasNext()){
ReportField f = (ReportField) itFieldsMin.next();
if (f.getIsSummarized()){
if (f.getSmallestValue()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Lowest", resetGroup, document, xCalc, widthCalc, y, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));
frame.appendChild(buildSummaryLabel("Min", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
//Add count to the footer section
yFound = false;
xCalc = 0;
widthCalc = 0;
Iterator<?> itFieldsCount = getSelectedReportFields().iterator();
columnIndex = 0;
while (itFieldsCount.hasNext()){
ReportField f = (ReportField) itFieldsCount.next();
if (f.getIsSummarized()){
if (f.getRecordCount()){
xCalc = fieldProperties.get(f.getDisplayName());
widthCalc = fieldWidth.get(f.getDisplayName());
frame.appendChild(buildSummaryNodes(f, "Count", resetGroup, document, xCalc, widthCalc, y+1, rowHeight, columnIndex));
yFound = true;
}
}
columnIndex++;
}
if (yFound){
frame.appendChild(addLine(document, x, y-1, totalWidth - x));//(xCalc + widthCalc)-x)
frame.appendChild(buildSummaryLabel("Count", document, x, y-rowHeight-2, totalWidth - x, rowHeight, false, null, columnIndex));
y += rowHeight*2+2;
}
bandTotalHeight = y - rowHeight + 4;
Integer frameHeight = bandTotalHeight;
rptElementFrame.setAttribute("stretchType", "RelativeToBandHeight");
rptElementFrame.setAttribute("mode", "Opaque");
rptElementFrame.setAttribute("x", "0"); //Integer.toString(x)
rptElementFrame.setAttribute("y", "0");
int frameWidth = 0;
frameWidth = (totalWidth + 4);
rptElementFrame.setAttribute("width", Integer.toString(frameWidth));
rptElementFrame.setAttribute("height", frameHeight.toString());
rptElementFrame.setAttribute("backcolor", "#EEEFEF");
box.setAttribute("topPadding", "1");
box.setAttribute("leftPadding", "1");
box.setAttribute("bottomPadding", "1");
box.setAttribute("rightPadding", "1");
//rectangle
rectangle.setAttribute("radius", "10");
rptElementRectangle.setAttribute("mode", "Transparent");
rptElementRectangle.setAttribute("x", "0"); //Integer.toString(x)
rptElementRectangle.setAttribute("y", "0");
rptElementRectangle.setAttribute("width", Integer.toString(frameWidth - 2));
rptElementRectangle.setAttribute("height", Integer.toString(frameHeight - 2));
rptElementRectangle.setAttribute("forecolor", "#666666");
rptElementRectangle.setAttribute("backcolor", "#666666");
pen.setAttribute("lineStyle", "Double");
band.appendChild(frame);
band.setAttribute("height", bandTotalHeight.toString());
return band;
}
/**
* @param document
* @param frame
*/
private Node addLine(Document document, int x, int y, int width) {
Element line = document.createElement("line");
//frame.appendChild(line);
Element rptElementLine = document.createElement("reportElement");
line.appendChild(rptElementLine);
rptElementLine.setAttribute("x", Integer.toString(x));
rptElementLine.setAttribute("y", Integer.toString(y));
rptElementLine.setAttribute("width", Integer.toString(width));
rptElementLine.setAttribute("height", "1");
rptElementLine.setAttribute("forecolor", "#999999");
return line;
}
/**
* create child "textField" of "band" with attributes
*/
private Node buildSummaryNodes(ReportField f, String calc, String resetGroup, Document document, int x, int width, int y, int height, int columnIndex) {
String varName = null;
String valueClassName = null;
String pattern = null;
String columnName = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
columnName = f.getColumnName() + "_" + columnIndex;
else
columnName = f.getAliasName() + "_" + columnIndex;
//set the field data type
if (calc.compareToIgnoreCase("count") == 0){
valueClassName = Long.class.getName();
pattern ="";
}else{
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); pattern =""; break;
case STRING: valueClassName = String.class.getName(); pattern =""; break;
case INTEGER: valueClassName = Long.class.getName(); pattern =""; break;
case DOUBLE: valueClassName = Double.class.getName(); pattern =""; break;
case DATE: valueClassName = Date.class.getName(); pattern ="MM/dd/yyyy"; break;
case MONEY: valueClassName = Float.class.getName(); pattern ="$ 0.00"; break;
case BOOLEAN: valueClassName = Boolean.class.getName();pattern ="";
}
}
if (resetGroup.compareToIgnoreCase("global_column_0") == 0)
varName = "variable-footer_global_" + columnName + "_" + calc;
else
varName = "variable-footer_" + resetGroup + "_" + columnName + "_" + calc;
Element textField = document.createElement("textField");
textField.setAttribute("isStretchWithOverflow", "true");
textField.setAttribute("evaluationTime", "Group");
textField.setAttribute("evaluationGroup", resetGroup);
textField.setAttribute("pattern", pattern);
//band.appendChild(textField);
//create child "reportElement" of "textField" with attr
Element reportElement = document.createElement("reportElement");
reportElement.setAttribute("key", varName);
//reportElement.setAttribute("style", "dj_style_1");
reportElement.setAttribute("positionType", "Float");
reportElement.setAttribute("stretchType", "RelativeToTallestObject");
reportElement.setAttribute("x", Integer.toString(x));
reportElement.setAttribute("y", Integer.toString(y));
reportElement.setAttribute("width", Integer.toString(width));
reportElement.setAttribute("height", Integer.toString(height));
// reportElement.setAttribute("style", "SummaryStyle");
textField.appendChild(reportElement);
//create child "textElement" of "textField" (it's empty)
Element textElement = document.createElement("textElement");
textField.appendChild(textElement);
////create child "textFieldExpression" of "textField" with attr
Element textFieldExpression = document.createElement("textFieldExpression");
textFieldExpression.setAttribute("class", valueClassName);
textFieldExpression.appendChild(document.createCDATASection("$V{" + varName + "}"));
textField.appendChild(textFieldExpression);
return textField;
}
/**
* Adds the static text labels to the report.
*/
private Node buildSummaryLabel(String calc, Document document, int x, int y, int width, int height, Boolean groupHeaderFlag, ReportField f, int columnIndex) {
Element textField2 = document.createElement("textField");
Element reportElement2 = document.createElement("reportElement");
reportElement2.setAttribute("key", "global_legend_footer_" + calc);
//reportElement2.setAttribute("style", "dj_style_2");
reportElement2.setAttribute("x", Integer.toString(x));
reportElement2.setAttribute("y", Integer.toString(y));
reportElement2.setAttribute("width", Integer.toString(width));
reportElement2.setAttribute("height", Integer.toString(height));
textField2.appendChild(reportElement2);
//create child "textElement" of "textField" (it's empty)
Element textElement2 = document.createElement("textElement");
textField2.appendChild(textElement2);
////create child "textFieldExpression" of "textField" with attr
Element textFieldExpression2 = document.createElement("textFieldExpression");
String valueClassName = String.class.getName();
if (groupHeaderFlag){
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); break;
case STRING: valueClassName = String.class.getName(); break;
case INTEGER: valueClassName = Long.class.getName(); break;
case DOUBLE: valueClassName = Double.class.getName(); break;
case DATE: valueClassName = Date.class.getName(); break;
case MONEY: valueClassName = Float.class.getName(); break;
case BOOLEAN: valueClassName = Boolean.class.getName();
}
String groupColumn = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
groupColumn = f.getColumnName() + "_" + columnIndex;
else
groupColumn = f.getAliasName() + "_" + columnIndex;
textFieldExpression2.appendChild(document.createCDATASection("$F{" + groupColumn + "}"));
//reportElement2.setAttribute("style", "SummaryStyle");
}
else{
textFieldExpression2.appendChild(document.createCDATASection("\"" + calc + "\""));
//reportElement2.setAttribute("style", "SummaryStyleBlue");
}
textFieldExpression2.setAttribute("class", valueClassName);
textField2.appendChild(textFieldExpression2);
return textField2;
}
/**
* Adds a variable to the JRXML/Jasper Report to store the specified calculation.
*
* @param columnName Used in the variable name.
* @param calc Calculation to be performed.
* @param resetGroup Name of the group that the calculation will be performed on.
* @param document XML document.
* @return Element
*/
private Node buildVariableNode(ReportField f, String calc, String resetGroup, Document document, Integer columnIndex ) {
String varName = null;
String columnName = null;
if (f.getAliasName() == null || f.getAliasName().length() == 0)
columnName = f.getColumnName() + "_" + columnIndex;
else
columnName = f.getAliasName() + "_" + columnIndex;
String valueClassName = null;
String initialize = "()";
//set the field data type
if (calc.compareToIgnoreCase("count") == 0){
valueClassName = Long.class.getName();
initialize = "(\"0\")";
}else{
switch (f.getFieldType()) {
case NONE: valueClassName = String.class.getName(); break;
case STRING: valueClassName = String.class.getName(); break;
case INTEGER: valueClassName = Long.class.getName(); initialize = "(\"0\")"; break;
case DOUBLE: valueClassName = Double.class.getName(); initialize = "(\"0\")"; break;
case DATE: valueClassName = Date.class.getName(); break;
case MONEY: valueClassName = Float.class.getName(); initialize = "(\"0\")"; break;
case BOOLEAN: valueClassName = Boolean.class.getName();
}
}
int test1 = new Integer(3);
long test = new Long(0);
if (resetGroup.compareToIgnoreCase("global_column_0") == 0)
varName = "variable-footer_global_" + columnName + "_" + calc;
else
varName = "variable-footer_" + resetGroup + "_" + columnName + "_" + calc;
Element variable = document.createElement("variable");
variable.setAttribute("name", varName);
variable.setAttribute("class", valueClassName);
variable.setAttribute("resetType", "Group");
variable.setAttribute("resetGroup", resetGroup);
variable.setAttribute("calculation", calc);
Element variableExpression = document.createElement("variableExpression");
variableExpression.appendChild(document.createCDATASection("$F{" + columnName + "}"));
variable.appendChild(variableExpression);
Element initialValueExpression = document.createElement("initialValueExpression");
initialValueExpression.appendChild(document.createCDATASection("new " + valueClassName + initialize));
variable.appendChild(initialValueExpression);
return variable;
}
/**
* Fixes the "category series is null" and "key is null" for the pie and bar charts
*
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param document The jrxml document.
*/
public void correctNullDataInChart(String chartType, Document document, List<ReportChartSettings> rcsList){
//TODO: right now we just allow one chart per report but when we change for multiple charts this will need to be refactored
//to iterate thru the list
ReportChartSettings rcs = rcsList.get(0);
if (!chartType.toLowerCase().contains("pie")){
//get the categoryExpression node
Node categoryExp = null;
if (chartType.equalsIgnoreCase("timeSeries") || chartType.equalsIgnoreCase("scatter") || chartType.toLowerCase().startsWith("xy")){
correctChartVariableForCountOperation(chartType, document, rcs);
addChartLabels(chartType, document, rcs);
return;
//You can not have null dates in the group by field
//so for now you need to add criteria in the guru to exclude null dates
//when using timeSeries, scatter or xy charts
//categoryExp = document.getElementsByTagName("timePeriodExpression").item(0);
}else {
categoryExp = document.getElementsByTagName("categoryExpression").item(0);
}
//String categoryExpField = categoryExp.getTextContent();
//String newcategoryExp = "(( " + categoryExpField + " != null) ? " + categoryExpField + ".toString() : \"null\" )";
categoryExp.setTextContent(correctNullDataField(categoryExp.getTextContent(), "null"));
//get the seriesExpression node
NodeList seriesNodes = document.getElementsByTagName("seriesExpression");
for (int i = 0; i < seriesNodes.getLength(); i++){
Node seriesExp = document.getElementsByTagName("seriesExpression").item(i);
//String seriesExpField = seriesExp.getTextContent();
//String newseriesExp = "(( " + seriesExpField + " != null) ? " + seriesExpField + ".toString() : \"null\" )";
seriesExp.setTextContent(correctNullDataField(seriesExp.getTextContent(), "null"));
}
//set the label expression
Node labelExp = document.getElementsByTagName("labelExpression").item(0);
String labelExpField = labelExp.getTextContent();
String newlabelExp = labelExpField + ".toString()";
labelExp.setTextContent(newlabelExp);
}else if (chartType.toLowerCase().contains("pie")){
//get the keyExpression node
Node keyExp = document.getElementsByTagName("keyExpression").item(0);
//String keyExpField = keyExp.getTextContent();
//String newkeyExp = "(( " + keyExpField + " != null) ? " + keyExpField + ".toString() : \"null\" )";
keyExp.setTextContent(correctNullDataField(keyExp.getTextContent(), "null"));
}
correctChartVariableForCountOperation(chartType, document, rcs);
addChartLabels(chartType, document, rcs);
}
public void correctChartVariableForCountOperation(String chartType, Document document, ReportChartSettings rcs){
for (ReportChartSettingsSeries thisRcs : rcs.getReportChartSettingsSeries()){
if (thisRcs.getOperation() != null && thisRcs.getOperation().equals("RecordCount") ){
NodeList variableNodeList = document.getElementsByTagName("variable");
for (int index = 0; index < variableNodeList.getLength(); index++) {
Node variableNode = variableNodeList.item(index);
String nodeName = variableNode.getAttributes().getNamedItem("name").getNodeValue();
if (nodeName.contains("CHART")
&& nodeName.contains(thisRcs.getSeriesColumn().getTitle())
&& nodeName.contains(rcs.getCategory().getName())) {
variableNode.getAttributes().getNamedItem("class").setNodeValue("java.lang.Number");
}
}
}
}
}
public void addChartLabels(String chartType, Document document, ReportChartSettings rcs){
//set title expression
if (rcs.getChartTitle() != null && !rcs.getChartTitle().isEmpty()){
Node titleExp = document.getElementsByTagName("titleExpression").item(0);
if (titleExp == null){
titleExp = document.createElement("titleExpression");
titleExp.setTextContent("\"" + rcs.getChartTitle() + "\"");
Node subTitleNodeParent = document.getElementsByTagName("chartTitle").item(0);
subTitleNodeParent.appendChild(titleExp);
}else {
titleExp.setTextContent("\"" + rcs.getChartTitle() + "\"");
}
}
//set subtitle expression
if (rcs.getChartSubTitle() != null && !rcs.getChartSubTitle().isEmpty()){
Node subTitleExp = document.getElementsByTagName("subtitleExpression").item(0);
if (subTitleExp == null){
subTitleExp = document.createElement("subtitleExpression");
subTitleExp.setTextContent("\"" + rcs.getChartSubTitle() + "\"");
Node subTitleNodeParent = document.getElementsByTagName("chartSubtitle").item(0);
subTitleNodeParent.appendChild(subTitleExp);
}else {
subTitleExp.setTextContent("\"" + rcs.getChartSubTitle() + "\"");
}
}
if ((!chartType.toLowerCase().contains("pie")) && (rcs.getCategoryAxisLabel() != null && !rcs.getCategoryAxisLabel().isEmpty())){
if (chartType.equalsIgnoreCase("timeSeries")){
Node timeAxisLabelExpression = document.getElementsByTagName("timeAxisLabelExpression").item(0);
if (timeAxisLabelExpression == null){
//add the node as it is not there
//it goes before timeAxisFormat node
Node timeAxisFormatNode = document.getElementsByTagName("timeAxisFormat").item(0);
timeAxisLabelExpression = document.createElement("timeAxisLabelExpression");
timeAxisLabelExpression.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
Node categoryAxisFormatNodeParent = document.getElementsByTagName(timeAxisFormatNode.getParentNode().getNodeName()).item(0);
categoryAxisFormatNodeParent.insertBefore(timeAxisLabelExpression, timeAxisFormatNode);
}else{
timeAxisLabelExpression.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
}
}else {
//set categoryAxisLabelExpression
Node categoryAxisLabelExp = document.getElementsByTagName("categoryAxisLabelExpression").item(0);
if (categoryAxisLabelExp == null){
//add the node as it is not there
//it goes before categoryAxisFormat node
Node categoryAxisFormatNode = document.getElementsByTagName("categoryAxisFormat").item(0);
categoryAxisLabelExp = document.createElement("categoryAxisLabelExpression");
categoryAxisLabelExp.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
Node categoryAxisFormatNodeParent = document.getElementsByTagName(categoryAxisFormatNode.getParentNode().getNodeName()).item(0);
categoryAxisFormatNodeParent.insertBefore(categoryAxisLabelExp, categoryAxisFormatNode);
}else{
categoryAxisLabelExp.setTextContent("\"" + rcs.getCategoryAxisLabel() + "\"");
}
}
//set valueAxisLabelExpression
if (rcs.getValueAxisLabel() != null && !rcs.getValueAxisLabel().isEmpty()){
Node valueAxisLabelExp = document.getElementsByTagName("valueAxisLabelExpression").item(0);
if (valueAxisLabelExp == null){
//add the node as it is not there
//it goes before valueAxisFormat node
Node valueAxisFormatNode = document.getElementsByTagName("valueAxisFormat").item(0);
valueAxisLabelExp = document.createElement("valueAxisLabelExpression");
valueAxisLabelExp.setTextContent("\"" + rcs.getValueAxisLabel() + "\"");
Node valueAxisFormatNodeParent = document.getElementsByTagName(valueAxisFormatNode.getParentNode().getNodeName()).item(0);
valueAxisFormatNodeParent.insertBefore(valueAxisLabelExp, valueAxisFormatNode);
}else{
valueAxisLabelExp.setTextContent("\"" + rcs.getValueAxisLabel() + "\"");
}
}
}
}
public String correctNullDataField(String infield, String replaceNullWith){
return "(( " + infield + " != null) ? " + infield + ".toString() : \" "+ replaceNullWith +"\" )";
}
/**
* Fixes a bug with pie charts only showing the first group. This bug
* was a result of the upgrade to Jasperserver 3.5 and will hopefully go
* away when we upgrade dyamic jasper.
*
* @param chartType The type of chart.
* @param document The jrxml document.
*/
public void correctPieChartEvaluationTime(String chartType, Document document){
if (chartType.toLowerCase().contains("pie")){
//get the chart node
Element chartElement = (Element)document.getElementsByTagName("chart").item(0);
//change the attribute evaluationTime from "Group" to "Report"
chartElement.getAttributeNode("evaluationTime").setValue("Report");
}
}
/**
* Removes the chart from the group created by dynamic jasper and
* puts it in the title or lastPageFooter section of the report.
*
* @param fileName file name of the XML document
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param location The location you want to put the chart. (header or footer)
*/
public void moveChartFromGroup(String fileName, String chartType, String location, List<ReportChartSettings> rcsList) throws ParserConfigurationException, SAXException, IOException{
//Find the chart node copy it
String chart = getChartNodeName(chartType);
if (chart != null){
Document document = loadXMLDocument(fileName);
//correct the "category series is null" and "key is null" errors
//before moving chart
correctNullDataInChart(chartType, document, rcsList);
//correct bug with pie chart due to upgrade to JS 3.5
if (chart.toLowerCase().contains("pie"))
correctPieChartEvaluationTime(chartType, document);
Node chartNode = document.getElementsByTagName(chart).item(0);
if (chartNode != null){
Element chartElement = (Element) chartNode;
Element chartRptElement = (Element) chartElement.getElementsByTagName("reportElement").item(0);
//Add the printwhenexpression to the chart report element if it goes in the header
if (location.compareToIgnoreCase("header") == 0){
Element printWhenExpression = document.createElement("printWhenExpression");
printWhenExpression.appendChild(document.createCDATASection("new java.lang.Boolean(((Number)$V{PAGE_NUMBER}).doubleValue() == 1)"));
chartRptElement.appendChild(printWhenExpression);
}
//change the band height back to 0
Element band = (Element) chartElement.getParentNode();
Integer bandHeight = Integer.decode(band.getAttribute("height"));
band.setAttribute("height", "0");
//remove the group footer band node from the group added for the chart
Element chartGroup = (Element) band.getParentNode().getParentNode();
Node groupFooter = (Element) chartGroup.getElementsByTagName("groupFooter").item(0);
Node groupFooterBand = (Element) ((Element) groupFooter).getElementsByTagName("band").item(0);
groupFooter.replaceChild((Node) document.createElement("band"), groupFooterBand);
//remove the chart node
removeAll(document, Node.ELEMENT_NODE, chart);
//add the copied chart node to the title band or the last page footer
String position = null;
if (location.compareTo("header") == 0)
position = "title";
else
position = "lastPageFooter";
Element positionNode = (Element) document.getElementsByTagName(position).item(0);
Element positionBandNode = (Element) positionNode.getElementsByTagName("band").item(0);
Integer positionBandHeight = Integer.decode(positionBandNode.getAttribute("height"));
// set the y value on the chart depends on the position of the chart
//set the new band height to allow room for the chart
if (position.compareTo("title") == 0){
chartRptElement.setAttribute("y", positionBandHeight.toString());
Integer newpositionNodeBandHeight = positionBandHeight + bandHeight;
positionBandNode.setAttribute("height", newpositionNodeBandHeight.toString());
}
else{
//change the y for the other elements in the last page footer so the chart is above them
NodeList rptElementsInLastPgFt = positionBandNode.getElementsByTagName("reportElement");
Integer newpositionNodeBandHeight = positionBandHeight + bandHeight;
Integer numberOfRptElements = rptElementsInLastPgFt.getLength();
for (int i = 0; i < numberOfRptElements; i++){
Integer yRptElement = Integer.decode(((Element) rptElementsInLastPgFt.item(i)).getAttribute("y"));
Integer yForOtherElements = yRptElement + bandHeight;
((Element) rptElementsInLastPgFt.item(i)).setAttribute("y", yForOtherElements.toString());
}
chartRptElement.setAttribute("y", "0");
positionBandNode.setAttribute("height", newpositionNodeBandHeight.toString());
}
positionBandNode.appendChild(chartNode);
saveXMLtoFile(fileName, document);
}
}
}
private String getChartNodeName(String chartType) {
String chart;
if (chartType.compareToIgnoreCase("area") == 0)
chart = "areaChart";
else if (chartType.compareToIgnoreCase("bar") == 0)
chart = "barChart";
else if (chartType.compareToIgnoreCase("bar3d") == 0)
chart = "bar3DChart";
else if (chartType.compareToIgnoreCase("line") == 0)
chart = "lineChart";
else if (chartType.compareToIgnoreCase("pie") == 0)
chart = "pieChart";
else if (chartType.compareToIgnoreCase("pie3d") == 0)
chart = "pie3DChart";
else if (chartType.compareToIgnoreCase("scatter") == 0)
chart = "scatterChart";
else if (chartType.compareToIgnoreCase("stackedarea") == 0)
chart = "stackedAreaChart";
else if (chartType.compareToIgnoreCase("stackedbar") == 0)
chart = "stackedBarChart";
else if (chartType.compareToIgnoreCase("stackedbar3d") == 0)
chart = "stackedBar3DChart";
else if (chartType.compareToIgnoreCase("timeseries") == 0)
chart = "timeSeriesChart";
else if (chartType.compareToIgnoreCase("xyarea") == 0)
chart = "xyAreaChart";
else if (chartType.compareToIgnoreCase("xybar") == 0)
chart = "xyBarChart";
else if (chartType.compareToIgnoreCase("xyline") == 0)
chart = "xyLineChart";
else
chart = null;
return chart;
}
/**
* Removes all elements from the report except the chart and
* places the chart in the summary section of the report.
*
* @param fileName file name of the XML document
* @param chartType The type of chart. Currently we only support Bar and Pie.
* @param location The location you want to put the chart. (header or footer)
*/
public void modifyChartOnlyReport(String fileName, String chartType, String location) throws ParserConfigurationException, SAXException, IOException{
String chart = getChartNodeName(chartType);
if (chart != null){
Document document = loadXMLDocument(fileName);
//copy the chart element
Node chartNode = document.getElementsByTagName(chart).item(0);
Element chartElement = (Element) chartNode;
//remove all unneeded elements
removeAll(document, Node.ELEMENT_NODE, "style");
removeAll(document, Node.ELEMENT_NODE, "groupHeader");
removeAll(document, Node.ELEMENT_NODE, "groupFooter");
removeAll(document, Node.ELEMENT_NODE, "background");
removeAll(document, Node.ELEMENT_NODE, "title");
removeAll(document, Node.ELEMENT_NODE, "pageHeader");
removeAll(document, Node.ELEMENT_NODE, "columnHeader");
removeAll(document, Node.ELEMENT_NODE, "detail");
removeAll(document, Node.ELEMENT_NODE, "columnFooter");
removeAll(document, Node.ELEMENT_NODE, "pageFooter");
removeAll(document, Node.ELEMENT_NODE, "lastPageFooter");
removeAll(document, Node.ELEMENT_NODE, "summary");
//set the size of the chart to width="330" height="220" (this size is defined by the OL dashboard)
String height = "220";
String width = "330";
Element chartNodeElement = (Element) chartElement.getElementsByTagName("chart").item(0);
Element chartReportElement = (Element) chartNodeElement.getElementsByTagName("reportElement").item(0);
if (chartReportElement != null){
chartReportElement.setAttribute("width", width);
chartReportElement.setAttribute("height", height);
}
//create a new summary node
Element summaryNode = document.createElement("summary");
Element summaryBand = document.createElement("band");
summaryBand.setAttribute("height", height);
//add the copied chart to the summary band
summaryBand.appendChild(chartElement);
//add the summaryBand to the summary node
summaryNode.appendChild(summaryBand);
//add the new summary node that contains the chart (this will replace the existing summary node)
Node jasperReport = document.getElementsByTagName("jasperReport").item(0);
jasperReport.appendChild(summaryNode);
saveXMLtoFile(fileName, document);
}
}
/*
*
*/
public void removeCrossTabDataSubset(String fileName) throws ParserConfigurationException, SAXException, IOException {
Document document = loadXMLDocument(fileName);
// Remove datasetRun element from the report xml
removeAll(document, Node.ELEMENT_NODE, "datasetRun");
// Remove detail element from the report xml
removeAll(document, Node.ELEMENT_NODE, "detail");
// Remove detail element from the report xml
removeAll(document, Node.ELEMENT_NODE, "columnHeader");
saveXMLtoFile(fileName, document);
}
public static void removeAll(Node node, short nodeType, String name) {
if (node.getNodeType() == nodeType &&
(name == null || node.getNodeName().equals(name))) {
node.getParentNode().removeChild(node);
} else {
// Visit the children
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
removeAll(list.item(i), nodeType, name);
}
}
}
private List<ReportField> getSelectedReportFields() {
Iterator<ReportSelectedField> itReportSelectedFields = reportWizard.getReportSelectedFields().iterator();
List<ReportField> selectedReportFieldsList = new LinkedList<ReportField>();
Integer columnIndex = 0;
while (itReportSelectedFields.hasNext()){
ReportSelectedField reportSelectedField = (ReportSelectedField) itReportSelectedFields.next();
if (reportSelectedField == null) continue;
ReportField f = reportFieldService.find(reportSelectedField.getFieldId());
if (f == null || f.getId() == -1) continue;
ReportField newField = new ReportField();
newField.setId(f.getId());
newField.setAliasName(f.getAliasName());
newField.setCanBeSummarized(f.getCanBeSummarized());
newField.setColumnName(f.getColumnName());
newField.setDisplayName(f.getDisplayName());
newField.setFieldType(f.getFieldType());
newField.setIsDefault(f.getIsDefault());
newField.setPrimaryKeys(f.getPrimaryKeys());
newField.setAverage(reportSelectedField.getAverage());
newField.setIsSummarized(reportSelectedField.getIsSummarized());
newField.setLargestValue(reportSelectedField.getMax());
newField.setSmallestValue(reportSelectedField.getMin());
newField.setPerformSummary(reportSelectedField.getSum());
newField.setRecordCount(reportSelectedField.getCount());
newField.setGroupBy(reportSelectedField.getGroupBy());
newField.setSelected(true);
//f.setDynamicColumnName(f.getColumnName() + "_" + columnIndex.toString());
//columnIndex++;
selectedReportFieldsList.add(newField);
}
return selectedReportFieldsList;
}
/**
* Sets the ReportWizard that contains the various report options.
* @param reportWizard
*/
public void setReportWizard(ReportWizard reportWizard) {
this.reportWizard = reportWizard;
}
/**
* Returns the ReportWizard that contains the various report options.
* @return
*/
public ReportWizard getReportWizard() {
return reportWizard;
}
public void setReportFieldService(ReportFieldService reportFieldService) {
this.reportFieldService = reportFieldService;
}
public ReportFieldService getReportFieldService() {
return reportFieldService;
}
}
|
diff --git a/main/src/java/chord/project/analyses/DlogAnalysis.java b/main/src/java/chord/project/analyses/DlogAnalysis.java
index 81435a82..3b378f70 100644
--- a/main/src/java/chord/project/analyses/DlogAnalysis.java
+++ b/main/src/java/chord/project/analyses/DlogAnalysis.java
@@ -1,316 +1,321 @@
/*
* Copyright (c) 2008-2010, Intel Corporation.
* Copyright (c) 2006-2007, The Trustees of Stanford University.
* All rights reserved.
* Licensed under the terms of the New BSD License.
*/
package chord.project.analyses;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import java.util.HashSet;
import chord.bddbddb.RelSign;
import chord.bddbddb.Solver;
import chord.util.StringUtils;
import gnu.trove.TIntArrayList;
/**
* Generic implementation of a Dlog task (a program analysis
* expressed in Datalog and solved using BDD-based solver
* <a href="http://bddbddb.sourceforge.net/">bddbddb</a>).
*
* @author Mayur Naik ([email protected])
*/
public class DlogAnalysis extends JavaAnalysis {
// absolute filename of the datalog program
private String fileName;
private Set<String> majorDomNames;
private Map<String, RelSign> consumedRels;
private Map<String, RelSign> producedRels;
private String dlogName;
private boolean hasNoErrors = true;
// number of line currently being parsed in the datalog program
private int lineNum;
// bdd ordering of all domains specified using .bddvarorder in
// the datalog program
private String order;
// ordered list of all domains specified using .bddvarorder in
// the datalog program
private List<String> minorDomNames;
// may return null
/**
* Provides the name of this Datalog analysis.
* It is specified via a line of the form "# name=..." in the
* file containing the analysis.
*
* @return The name of this Datalog analysis.
*/
public String getDlogName() {
return dlogName;
}
/**
* Provides the file containing this Datalog analysis.
*
* @return The file containing this Datalog analysis.
*/
public String getFileName() {
return fileName;
}
/**
* Parses the Datalog analysis in the specified file.
*
* @param fileName A file containing a Datalog analysis.
*
* @return true iff the Datalog analysis parses successfully.
*/
public boolean parse(String fileName) {
assert (this.fileName == null);
this.fileName = fileName;
majorDomNames = new HashSet<String>();
consumedRels = new HashMap<String, RelSign>();
producedRels = new HashMap<String, RelSign>();
minorDomNames = new ArrayList<String>();
BufferedReader in;
try {
in = new BufferedReader(new FileReader(new File(fileName)));
} catch (IOException ex) {
System.err.println("ERROR: IOException thrown while opening file '" +
fileName + "'; message follows: " + ex.getMessage());
return false;
}
Pattern p = Pattern.compile(
"(\\w)+\\((\\w)+:(\\w)+(,(\\w)+:(\\w)+)*\\)((input)|(output))");
for (lineNum = 1; true; lineNum++) {
String s;
try {
s = in.readLine();
} catch (IOException ex) {
error("IOException thrown while reading line; message follows: " +
ex.getMessage());
return false;
}
if (s == null)
break;
if (s.startsWith("#")) {
if (s.startsWith("# name=")) {
if (dlogName == null)
dlogName = s.trim().substring(7);
else
error("Name redeclared via # name=...");
}
continue;
}
+ int k = s.indexOf('#');
+ if (k != -1) s = s.substring(0, k);
+ s = s.trim();
+ if (s.length() == 0)
+ continue;
// strip all whitespaces from line
StringBuffer t = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c))
t.append(c);
}
s = t.toString();
if (s.startsWith(".bddvarorder")) {
if (order != null) {
error(".bddvarorder redefined.");
continue;
}
order = s.substring(12);
String[] a = order.split("_|x");
for (String minorDomName : a) {
if (minorDomNames.contains(minorDomName)) {
error("Domain name '" + minorDomName +
"' occurs multiple times in .bddvarorder; " +
"considering first occurrence.");
} else {
minorDomNames.add(minorDomName);
String majorDomName =
StringUtils.trimNumSuffix(minorDomName);
majorDomNames.add(majorDomName);
}
}
continue;
}
Matcher m = p.matcher(s);
if (!m.matches())
continue;
if (order == null) {
error(".bddvarorder not defined before first relation declared");
return false;
}
int i = s.indexOf('(');
String relName = s.substring(0, i);
if (consumedRels.containsKey(relName)) {
error("Relation '" + relName + "' redeclared");
continue;
}
if (producedRels.containsKey(relName)) {
error("Relation '" + relName + "' redeclared");
continue;
}
s = s.substring(i + 1);
boolean done = false;
boolean ignore = false;
List<String> relMinorDomNames = new ArrayList<String>();
List<String> relMajorDomNames = new ArrayList<String>();
TIntArrayList indices = new TIntArrayList();
while (!done) {
i = s.indexOf(':');
assert (i != -1);
s = s.substring(i + 1);
i = s.indexOf(',');
if (i == -1) {
i = s.indexOf(')');
assert (i != -1);
done = true;
}
String domName = s.substring(0, i);
String minorDomName;
String majorDomName;
int index;
if (!Character.isDigit(domName.charAt(i - 1))) {
majorDomName = domName;
index = 0;
int num = indices.size();
while (true) {
int j = 0;
for (String majorDomName2 : relMajorDomNames) {
if (majorDomName2.equals(majorDomName) &&
indices.get(j) == index) {
index++;
break;
}
j++;
}
if (j == num)
break;
}
minorDomName = majorDomName + Integer.toString(index);
} else {
minorDomName = domName;
int j = i - 1;
while (true) {
char c = domName.charAt(j);
if (Character.isDigit(c))
j--;
else
break;
}
majorDomName = domName.substring(0, j + 1);
index = Integer.parseInt(domName.substring(j + 1, i));
}
if (relMinorDomNames.contains(minorDomName)) {
error("Domain name '" + minorDomName +
"' occurs multiple times in declaration of " +
"relation '" + relName + "'");
ignore = true;
} else if (!minorDomNames.contains(minorDomName)) {
error("Domain name '" + domName +
"' in declaration of relation '" + relName +
"' does not occur in .bddvarorder");
ignore = true;
} else {
relMinorDomNames.add(minorDomName);
relMajorDomNames.add(majorDomName);
indices.add(index);
}
s = s.substring(i + 1);
}
if (ignore)
continue;
int numDoms = relMinorDomNames.size();
String[] domNames = new String[numDoms];
String domOrder = getSubOrder(relMinorDomNames);
for (int j = 0; j < numDoms; j++)
domNames[j] = relMinorDomNames.get(j);
Map<String, RelSign> map = null;
if (s.equals("input"))
map = consumedRels;
else if (s.equals("output"))
map = producedRels;
else
assert false;
RelSign relSign;
try {
relSign = new RelSign(domNames, domOrder);
} catch (RuntimeException ex) {
error(ex.getMessage());
continue;
}
map.put(relName, relSign);
}
return hasNoErrors;
}
private String getSubOrder(List<String> relMinorDomNames) {
int orderLen = order.length();
String subOrder = null;
char lastSep = ' ';
int i = 0;
for (String domName : minorDomNames) {
i += domName.length();
if (relMinorDomNames.contains(domName)) {
if (subOrder == null)
subOrder = domName;
else
subOrder = subOrder + lastSep + domName;
if (i != orderLen)
lastSep = order.charAt(i);
} else {
if (i != orderLen && order.charAt(i) == '_')
lastSep = '_';
}
i++;
}
return subOrder;
}
private void error(String errMsg) {
System.err.println("ERROR: " + fileName + ": line " +
lineNum + ": " + errMsg);
hasNoErrors = false;
}
/**
* Executes this Datalog analysis.
*/
public void run() {
Solver.run(fileName);
}
/**
* Provides the names of all domains of relations
* consumed/produced by this Datalog analysis.
*
* @return The names of all domains of relations
* consumed/produced by this Datalog analysis.
*/
public Set<String> getDomNames() {
return majorDomNames;
}
/**
* Provides the names and signatures of all relations consumed
* by this Datalog analysis.
*
* @return The names and signatures of all relations consumed
* by this Datalog analysis.
*/
public Map<String, RelSign> getConsumedRels() {
return consumedRels;
}
/**
* Provides the names and signatures of all relations produced
* by this Datalog analysis.
*
* @return The names and signatures of all relations produced
* by this Datalog analysis.
*/
public Map<String, RelSign> getProducedRels() {
return producedRels;
}
}
| true | true | public boolean parse(String fileName) {
assert (this.fileName == null);
this.fileName = fileName;
majorDomNames = new HashSet<String>();
consumedRels = new HashMap<String, RelSign>();
producedRels = new HashMap<String, RelSign>();
minorDomNames = new ArrayList<String>();
BufferedReader in;
try {
in = new BufferedReader(new FileReader(new File(fileName)));
} catch (IOException ex) {
System.err.println("ERROR: IOException thrown while opening file '" +
fileName + "'; message follows: " + ex.getMessage());
return false;
}
Pattern p = Pattern.compile(
"(\\w)+\\((\\w)+:(\\w)+(,(\\w)+:(\\w)+)*\\)((input)|(output))");
for (lineNum = 1; true; lineNum++) {
String s;
try {
s = in.readLine();
} catch (IOException ex) {
error("IOException thrown while reading line; message follows: " +
ex.getMessage());
return false;
}
if (s == null)
break;
if (s.startsWith("#")) {
if (s.startsWith("# name=")) {
if (dlogName == null)
dlogName = s.trim().substring(7);
else
error("Name redeclared via # name=...");
}
continue;
}
// strip all whitespaces from line
StringBuffer t = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c))
t.append(c);
}
s = t.toString();
if (s.startsWith(".bddvarorder")) {
if (order != null) {
error(".bddvarorder redefined.");
continue;
}
order = s.substring(12);
String[] a = order.split("_|x");
for (String minorDomName : a) {
if (minorDomNames.contains(minorDomName)) {
error("Domain name '" + minorDomName +
"' occurs multiple times in .bddvarorder; " +
"considering first occurrence.");
} else {
minorDomNames.add(minorDomName);
String majorDomName =
StringUtils.trimNumSuffix(minorDomName);
majorDomNames.add(majorDomName);
}
}
continue;
}
Matcher m = p.matcher(s);
if (!m.matches())
continue;
if (order == null) {
error(".bddvarorder not defined before first relation declared");
return false;
}
int i = s.indexOf('(');
String relName = s.substring(0, i);
if (consumedRels.containsKey(relName)) {
error("Relation '" + relName + "' redeclared");
continue;
}
if (producedRels.containsKey(relName)) {
error("Relation '" + relName + "' redeclared");
continue;
}
s = s.substring(i + 1);
boolean done = false;
boolean ignore = false;
List<String> relMinorDomNames = new ArrayList<String>();
List<String> relMajorDomNames = new ArrayList<String>();
TIntArrayList indices = new TIntArrayList();
while (!done) {
i = s.indexOf(':');
assert (i != -1);
s = s.substring(i + 1);
i = s.indexOf(',');
if (i == -1) {
i = s.indexOf(')');
assert (i != -1);
done = true;
}
String domName = s.substring(0, i);
String minorDomName;
String majorDomName;
int index;
if (!Character.isDigit(domName.charAt(i - 1))) {
majorDomName = domName;
index = 0;
int num = indices.size();
while (true) {
int j = 0;
for (String majorDomName2 : relMajorDomNames) {
if (majorDomName2.equals(majorDomName) &&
indices.get(j) == index) {
index++;
break;
}
j++;
}
if (j == num)
break;
}
minorDomName = majorDomName + Integer.toString(index);
} else {
minorDomName = domName;
int j = i - 1;
while (true) {
char c = domName.charAt(j);
if (Character.isDigit(c))
j--;
else
break;
}
majorDomName = domName.substring(0, j + 1);
index = Integer.parseInt(domName.substring(j + 1, i));
}
if (relMinorDomNames.contains(minorDomName)) {
error("Domain name '" + minorDomName +
"' occurs multiple times in declaration of " +
"relation '" + relName + "'");
ignore = true;
} else if (!minorDomNames.contains(minorDomName)) {
error("Domain name '" + domName +
"' in declaration of relation '" + relName +
"' does not occur in .bddvarorder");
ignore = true;
} else {
relMinorDomNames.add(minorDomName);
relMajorDomNames.add(majorDomName);
indices.add(index);
}
s = s.substring(i + 1);
}
if (ignore)
continue;
int numDoms = relMinorDomNames.size();
String[] domNames = new String[numDoms];
String domOrder = getSubOrder(relMinorDomNames);
for (int j = 0; j < numDoms; j++)
domNames[j] = relMinorDomNames.get(j);
Map<String, RelSign> map = null;
if (s.equals("input"))
map = consumedRels;
else if (s.equals("output"))
map = producedRels;
else
assert false;
RelSign relSign;
try {
relSign = new RelSign(domNames, domOrder);
} catch (RuntimeException ex) {
error(ex.getMessage());
continue;
}
map.put(relName, relSign);
}
return hasNoErrors;
}
| public boolean parse(String fileName) {
assert (this.fileName == null);
this.fileName = fileName;
majorDomNames = new HashSet<String>();
consumedRels = new HashMap<String, RelSign>();
producedRels = new HashMap<String, RelSign>();
minorDomNames = new ArrayList<String>();
BufferedReader in;
try {
in = new BufferedReader(new FileReader(new File(fileName)));
} catch (IOException ex) {
System.err.println("ERROR: IOException thrown while opening file '" +
fileName + "'; message follows: " + ex.getMessage());
return false;
}
Pattern p = Pattern.compile(
"(\\w)+\\((\\w)+:(\\w)+(,(\\w)+:(\\w)+)*\\)((input)|(output))");
for (lineNum = 1; true; lineNum++) {
String s;
try {
s = in.readLine();
} catch (IOException ex) {
error("IOException thrown while reading line; message follows: " +
ex.getMessage());
return false;
}
if (s == null)
break;
if (s.startsWith("#")) {
if (s.startsWith("# name=")) {
if (dlogName == null)
dlogName = s.trim().substring(7);
else
error("Name redeclared via # name=...");
}
continue;
}
int k = s.indexOf('#');
if (k != -1) s = s.substring(0, k);
s = s.trim();
if (s.length() == 0)
continue;
// strip all whitespaces from line
StringBuffer t = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c))
t.append(c);
}
s = t.toString();
if (s.startsWith(".bddvarorder")) {
if (order != null) {
error(".bddvarorder redefined.");
continue;
}
order = s.substring(12);
String[] a = order.split("_|x");
for (String minorDomName : a) {
if (minorDomNames.contains(minorDomName)) {
error("Domain name '" + minorDomName +
"' occurs multiple times in .bddvarorder; " +
"considering first occurrence.");
} else {
minorDomNames.add(minorDomName);
String majorDomName =
StringUtils.trimNumSuffix(minorDomName);
majorDomNames.add(majorDomName);
}
}
continue;
}
Matcher m = p.matcher(s);
if (!m.matches())
continue;
if (order == null) {
error(".bddvarorder not defined before first relation declared");
return false;
}
int i = s.indexOf('(');
String relName = s.substring(0, i);
if (consumedRels.containsKey(relName)) {
error("Relation '" + relName + "' redeclared");
continue;
}
if (producedRels.containsKey(relName)) {
error("Relation '" + relName + "' redeclared");
continue;
}
s = s.substring(i + 1);
boolean done = false;
boolean ignore = false;
List<String> relMinorDomNames = new ArrayList<String>();
List<String> relMajorDomNames = new ArrayList<String>();
TIntArrayList indices = new TIntArrayList();
while (!done) {
i = s.indexOf(':');
assert (i != -1);
s = s.substring(i + 1);
i = s.indexOf(',');
if (i == -1) {
i = s.indexOf(')');
assert (i != -1);
done = true;
}
String domName = s.substring(0, i);
String minorDomName;
String majorDomName;
int index;
if (!Character.isDigit(domName.charAt(i - 1))) {
majorDomName = domName;
index = 0;
int num = indices.size();
while (true) {
int j = 0;
for (String majorDomName2 : relMajorDomNames) {
if (majorDomName2.equals(majorDomName) &&
indices.get(j) == index) {
index++;
break;
}
j++;
}
if (j == num)
break;
}
minorDomName = majorDomName + Integer.toString(index);
} else {
minorDomName = domName;
int j = i - 1;
while (true) {
char c = domName.charAt(j);
if (Character.isDigit(c))
j--;
else
break;
}
majorDomName = domName.substring(0, j + 1);
index = Integer.parseInt(domName.substring(j + 1, i));
}
if (relMinorDomNames.contains(minorDomName)) {
error("Domain name '" + minorDomName +
"' occurs multiple times in declaration of " +
"relation '" + relName + "'");
ignore = true;
} else if (!minorDomNames.contains(minorDomName)) {
error("Domain name '" + domName +
"' in declaration of relation '" + relName +
"' does not occur in .bddvarorder");
ignore = true;
} else {
relMinorDomNames.add(minorDomName);
relMajorDomNames.add(majorDomName);
indices.add(index);
}
s = s.substring(i + 1);
}
if (ignore)
continue;
int numDoms = relMinorDomNames.size();
String[] domNames = new String[numDoms];
String domOrder = getSubOrder(relMinorDomNames);
for (int j = 0; j < numDoms; j++)
domNames[j] = relMinorDomNames.get(j);
Map<String, RelSign> map = null;
if (s.equals("input"))
map = consumedRels;
else if (s.equals("output"))
map = producedRels;
else
assert false;
RelSign relSign;
try {
relSign = new RelSign(domNames, domOrder);
} catch (RuntimeException ex) {
error(ex.getMessage());
continue;
}
map.put(relName, relSign);
}
return hasNoErrors;
}
|
diff --git a/Client/src/main/java/removeImage/RemoveImageGUI.java b/Client/src/main/java/removeImage/RemoveImageGUI.java
index 2a2ddff..1461ef0 100644
--- a/Client/src/main/java/removeImage/RemoveImageGUI.java
+++ b/Client/src/main/java/removeImage/RemoveImageGUI.java
@@ -1,250 +1,250 @@
package removeImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import repository.DeletePicturesCom;
/**
*
* @author Johan LG
*/
public class RemoveImageGUI extends GridPane {
private final ArrayList<Thumbnail> thumbnails;
private final ThumbnailLoader pl;
private final static int imagePerPane = 24;
private int thumbIndex = 0, maxImages = 0, rem = 0;
private FlowPane grid;
private Button next, previous;
private SelectedThumbnailLister lister;
public RemoveImageGUI() {
thumbnails = new ArrayList<>();
lister = new SelectedThumbnailLister(thumbnails);
int gap = 8;
setHgap(gap);
setVgap(gap);
setPadding(new Insets(gap));
ScrollPane scroll = new ScrollPane();
setVgrow(scroll, Priority.ALWAYS);
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS);
getColumnConstraints().add(cc);
scroll.setFitToWidth(true);
grid = new FlowPane();
grid.setPadding(new Insets(8));
grid.setVgap(gap);
grid.setHgap(gap);
grid.setAlignment(Pos.CENTER);
scroll.setContent(grid);
add(scroll, 0, 0, 4, 1);
Button mark = new Button("Merk alle");
Button unmark = new Button("Avmerk alle");
Button delete = new Button("Slett merkede");
previous = new Button("< Forrige");
next = new Button("Neste >");
Button markPage = new Button("Merk alle på siden");
Button unmarkPage = new Button("Avmerk alle på siden");
mark.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setSelected(true);
}
}
});
unmark.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setSelected(false);
}
}
});
delete.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
DeletePicturesCom delCom = new DeletePicturesCom();
try {
delCom.deletePictures(lister.ListSelectedThumbnails());
} catch (IOException ex) {
Logger.getLogger(RemoveImageGUI.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Thumbnail> selected = new ArrayList();
for (Thumbnail thumbnail : thumbnails) {
if (thumbnail.isSelected()) {
selected.add(thumbnail);
}
}
thumbnails.removeAll(selected);
updateGrid();
}
});
next.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
showNext();
}
});
previous.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
showPrevious();
}
});
previous.setDisable(true);
markPage.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
int range = imagePerPane;
if (maxImages == thumbIndex) {
range = rem;
}
for (int i = thumbIndex; i < thumbIndex + range; i++) {
thumbnails.get(i).setSelected(true);
}
}
});
unmarkPage.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
int range = imagePerPane;
if (maxImages == thumbIndex) {
range = rem;
}
for (int i = thumbIndex; i < thumbIndex + range; i++) {
thumbnails.get(i).setSelected(false);
}
}
});
HBox pageMarkBox = new HBox(gap);
pageMarkBox.getChildren().addAll(previous, markPage, unmarkPage, next);
pageMarkBox.setAlignment(Pos.CENTER);
add(pageMarkBox, 0, 1, 3, 1);
HBox markBox = new HBox(gap);
markBox.getChildren().addAll(mark, unmark);
markBox.setAlignment(Pos.CENTER);
add(markBox, 0, 2, 3, 1);
setHalignment(delete, HPos.RIGHT);
add(delete, 2, 2);
pl = new ThumbnailLoader(thumbnails);
maxImages = pl.imageListSize();
- if (maxImages < imagePerPane) {
+ if (maxImages <= imagePerPane) {
next.setDisable(true);
}
//temp
for (int i = 0; i < maxImages; i++) {
Thumbnail tn = new Thumbnail();
thumbnails.add(tn);
}
rem = maxImages % imagePerPane;
maxImages -= rem;
if (maxImages > imagePerPane) {
for (int i = 0; i < imagePerPane; i++) {
grid.getChildren().add(thumbnails.get(i));
}
} else {
grid.getChildren().addAll(thumbnails);
}
pl.addPictures(thumbnails);
pl.loadPictures(thumbnails, 0, imagePerPane * 2);
thumbIndex = 0;
GridPane.setHgrow(this, Priority.ALWAYS);
GridPane.setVgrow(this, Priority.ALWAYS);
}
private void showNext() {
thumbIndex += imagePerPane;
if (maxImages >= imagePerPane) {
grid.getChildren().clear();
if (thumbIndex == maxImages) {
for (int i = thumbIndex; i < (maxImages + rem); i++) {
previous.setDisable(false);
grid.getChildren().add(thumbnails.get(i));
}
next.setDisable(true);
} else {
for (int i = thumbIndex; i < (thumbIndex + imagePerPane); i++) {
previous.setDisable(false);
grid.getChildren().add(thumbnails.get(i));
}
}
if (thumbIndex > thumbnails.size() - 1) {
next.setDisable(true);
}
//Loading the pictures for the next page
pl.loadPictures(thumbnails, thumbIndex + imagePerPane, imagePerPane);
}
}
private void showPrevious() {
thumbIndex -= imagePerPane;
grid.getChildren().clear();
for (int i = thumbIndex; i < ((thumbIndex) + imagePerPane); i++) {
next.setDisable(false);
grid.getChildren().add(thumbnails.get(i));
}
if (thumbIndex == 0) {
previous.setDisable(true);
}
}
private void updateGrid() {
maxImages = thumbnails.size();
grid.getChildren().clear();
rem = maxImages % imagePerPane;
maxImages -= rem;
if (thumbIndex == maxImages) {
if (rem == 0 && thumbIndex != 0) {
showPrevious();
next.setDisable(true);
return;
}
for (int i = maxImages; i < (maxImages + rem); i++) {
grid.getChildren().add(thumbnails.get(i));
}
next.setDisable(true);
} else {
for (int i = thumbIndex; i < (thumbIndex + imagePerPane); i++) {
grid.getChildren().add(thumbnails.get(i));
thumbnails.get(i).loadImage();
}
}
}
}
| true | true | public RemoveImageGUI() {
thumbnails = new ArrayList<>();
lister = new SelectedThumbnailLister(thumbnails);
int gap = 8;
setHgap(gap);
setVgap(gap);
setPadding(new Insets(gap));
ScrollPane scroll = new ScrollPane();
setVgrow(scroll, Priority.ALWAYS);
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS);
getColumnConstraints().add(cc);
scroll.setFitToWidth(true);
grid = new FlowPane();
grid.setPadding(new Insets(8));
grid.setVgap(gap);
grid.setHgap(gap);
grid.setAlignment(Pos.CENTER);
scroll.setContent(grid);
add(scroll, 0, 0, 4, 1);
Button mark = new Button("Merk alle");
Button unmark = new Button("Avmerk alle");
Button delete = new Button("Slett merkede");
previous = new Button("< Forrige");
next = new Button("Neste >");
Button markPage = new Button("Merk alle på siden");
Button unmarkPage = new Button("Avmerk alle på siden");
mark.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setSelected(true);
}
}
});
unmark.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setSelected(false);
}
}
});
delete.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
DeletePicturesCom delCom = new DeletePicturesCom();
try {
delCom.deletePictures(lister.ListSelectedThumbnails());
} catch (IOException ex) {
Logger.getLogger(RemoveImageGUI.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Thumbnail> selected = new ArrayList();
for (Thumbnail thumbnail : thumbnails) {
if (thumbnail.isSelected()) {
selected.add(thumbnail);
}
}
thumbnails.removeAll(selected);
updateGrid();
}
});
next.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
showNext();
}
});
previous.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
showPrevious();
}
});
previous.setDisable(true);
markPage.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
int range = imagePerPane;
if (maxImages == thumbIndex) {
range = rem;
}
for (int i = thumbIndex; i < thumbIndex + range; i++) {
thumbnails.get(i).setSelected(true);
}
}
});
unmarkPage.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
int range = imagePerPane;
if (maxImages == thumbIndex) {
range = rem;
}
for (int i = thumbIndex; i < thumbIndex + range; i++) {
thumbnails.get(i).setSelected(false);
}
}
});
HBox pageMarkBox = new HBox(gap);
pageMarkBox.getChildren().addAll(previous, markPage, unmarkPage, next);
pageMarkBox.setAlignment(Pos.CENTER);
add(pageMarkBox, 0, 1, 3, 1);
HBox markBox = new HBox(gap);
markBox.getChildren().addAll(mark, unmark);
markBox.setAlignment(Pos.CENTER);
add(markBox, 0, 2, 3, 1);
setHalignment(delete, HPos.RIGHT);
add(delete, 2, 2);
pl = new ThumbnailLoader(thumbnails);
maxImages = pl.imageListSize();
if (maxImages < imagePerPane) {
next.setDisable(true);
}
//temp
for (int i = 0; i < maxImages; i++) {
Thumbnail tn = new Thumbnail();
thumbnails.add(tn);
}
rem = maxImages % imagePerPane;
maxImages -= rem;
if (maxImages > imagePerPane) {
for (int i = 0; i < imagePerPane; i++) {
grid.getChildren().add(thumbnails.get(i));
}
} else {
grid.getChildren().addAll(thumbnails);
}
pl.addPictures(thumbnails);
pl.loadPictures(thumbnails, 0, imagePerPane * 2);
thumbIndex = 0;
GridPane.setHgrow(this, Priority.ALWAYS);
GridPane.setVgrow(this, Priority.ALWAYS);
}
| public RemoveImageGUI() {
thumbnails = new ArrayList<>();
lister = new SelectedThumbnailLister(thumbnails);
int gap = 8;
setHgap(gap);
setVgap(gap);
setPadding(new Insets(gap));
ScrollPane scroll = new ScrollPane();
setVgrow(scroll, Priority.ALWAYS);
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS);
getColumnConstraints().add(cc);
scroll.setFitToWidth(true);
grid = new FlowPane();
grid.setPadding(new Insets(8));
grid.setVgap(gap);
grid.setHgap(gap);
grid.setAlignment(Pos.CENTER);
scroll.setContent(grid);
add(scroll, 0, 0, 4, 1);
Button mark = new Button("Merk alle");
Button unmark = new Button("Avmerk alle");
Button delete = new Button("Slett merkede");
previous = new Button("< Forrige");
next = new Button("Neste >");
Button markPage = new Button("Merk alle på siden");
Button unmarkPage = new Button("Avmerk alle på siden");
mark.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setSelected(true);
}
}
});
unmark.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setSelected(false);
}
}
});
delete.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
DeletePicturesCom delCom = new DeletePicturesCom();
try {
delCom.deletePictures(lister.ListSelectedThumbnails());
} catch (IOException ex) {
Logger.getLogger(RemoveImageGUI.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Thumbnail> selected = new ArrayList();
for (Thumbnail thumbnail : thumbnails) {
if (thumbnail.isSelected()) {
selected.add(thumbnail);
}
}
thumbnails.removeAll(selected);
updateGrid();
}
});
next.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
showNext();
}
});
previous.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
showPrevious();
}
});
previous.setDisable(true);
markPage.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
int range = imagePerPane;
if (maxImages == thumbIndex) {
range = rem;
}
for (int i = thumbIndex; i < thumbIndex + range; i++) {
thumbnails.get(i).setSelected(true);
}
}
});
unmarkPage.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
int range = imagePerPane;
if (maxImages == thumbIndex) {
range = rem;
}
for (int i = thumbIndex; i < thumbIndex + range; i++) {
thumbnails.get(i).setSelected(false);
}
}
});
HBox pageMarkBox = new HBox(gap);
pageMarkBox.getChildren().addAll(previous, markPage, unmarkPage, next);
pageMarkBox.setAlignment(Pos.CENTER);
add(pageMarkBox, 0, 1, 3, 1);
HBox markBox = new HBox(gap);
markBox.getChildren().addAll(mark, unmark);
markBox.setAlignment(Pos.CENTER);
add(markBox, 0, 2, 3, 1);
setHalignment(delete, HPos.RIGHT);
add(delete, 2, 2);
pl = new ThumbnailLoader(thumbnails);
maxImages = pl.imageListSize();
if (maxImages <= imagePerPane) {
next.setDisable(true);
}
//temp
for (int i = 0; i < maxImages; i++) {
Thumbnail tn = new Thumbnail();
thumbnails.add(tn);
}
rem = maxImages % imagePerPane;
maxImages -= rem;
if (maxImages > imagePerPane) {
for (int i = 0; i < imagePerPane; i++) {
grid.getChildren().add(thumbnails.get(i));
}
} else {
grid.getChildren().addAll(thumbnails);
}
pl.addPictures(thumbnails);
pl.loadPictures(thumbnails, 0, imagePerPane * 2);
thumbIndex = 0;
GridPane.setHgrow(this, Priority.ALWAYS);
GridPane.setVgrow(this, Priority.ALWAYS);
}
|
diff --git a/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java b/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java
index 225050d6..826fdc5b 100644
--- a/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java
+++ b/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java
@@ -1,179 +1,179 @@
package com.dreamoval.motech.omp.manager.orserve;
import com.dreamoval.motech.core.manager.CoreManager;
import com.dreamoval.motech.core.model.GatewayRequest;
import com.dreamoval.motech.core.model.GatewayResponse;
import com.dreamoval.motech.core.model.MStatus;
import com.dreamoval.motech.core.service.MotechContext;
import com.dreamoval.motech.omp.manager.GatewayMessageHandler;
import java.util.Date;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
/**
* Handles preparation and parsing of messages and responses from the OutReach Server message gateway
*
* @author Kofi A. Asamoah ([email protected])
* @date Jul 15, 2009
*/
public class ORServeGatewayMessageHandlerImpl implements GatewayMessageHandler {
private CoreManager coreManager;
private static Logger logger = Logger.getLogger(ORServeGatewayMessageHandlerImpl.class);
private Map<MStatus, String> codeStatusMap;
private Map<MStatus, String> codeResponseMap;
/**
*
* @see GatewayMessageHandler.parseResponse
*/
public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse, MotechContext context) {
logger.info("Parsing message gateway response");
logger.debug(gatewayResponse);
if(message == null)
return null;
if(gatewayResponse.isEmpty())
return null;
Set<GatewayResponse> responses = new HashSet<GatewayResponse>();
if(gatewayResponse.contains("error:") && gatewayResponse.contains("param:")){
- gatewayResponse = gatewayResponse.substring(0, 15).replace("\n", "");
+ gatewayResponse = gatewayResponse.trim().replace("\n", "");
}
String[] responseLines = gatewayResponse.split("\n");
for(String line : responseLines){
String[] responseParts = line.split(" ");
if(responseParts[0].equalsIgnoreCase("ID:")){
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setGatewayMessageId(responseParts[1]);
response.setRequestId(message.getRequestId());
response.setMessageStatus(MStatus.PENDING);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
if(responseParts.length == 4)
response.setRecipientNumber(responseParts[3]);
else
response.setRecipientNumber(message.getRecipientsNumber());
responses.add(response);
}
else{
logger.error("Gateway returned error: " + gatewayResponse);
String errorCode = responseParts[1];
errorCode.replaceAll(",", "");
errorCode.trim();
MStatus status = lookupResponse(errorCode);
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setRequestId(message.getRequestId());
response.setMessageStatus(status);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
responses.add(response);
}
}
logger.debug(responses);
return responses;
}
/**
*
* @see GatewayMessageHandler.parseMessageStatus
*/
public MStatus parseMessageStatus(String gatewayResponse) {
logger.info("Parsing message gateway status response");
String status;
String[] responseParts = gatewayResponse.split(" ");
if(responseParts.length == 4){
status = responseParts[3];
}
else{
status = "";
}
return lookupStatus(status);
}
/**
* @see GatewayMessageHandler.lookupStatus
*/
public MStatus lookupStatus(String code){
if(code.isEmpty()){
return MStatus.PENDING;
}
for(Entry<MStatus, String> entry: codeStatusMap.entrySet()){
if(entry.getValue().contains(code)){
return entry.getKey();
}
}
return MStatus.PENDING;
}
/**
* @see GatewayMessageHandler.lookupResponse
*/
public MStatus lookupResponse(String code){
if(code.isEmpty()){
return MStatus.SCHEDULED;
}
for(Entry<MStatus, String> entry: codeResponseMap.entrySet()){
if(entry.getValue().contains(code)){
return entry.getKey();
}
}
return MStatus.SCHEDULED;
}
/**
* @return the coreManager
*/
public CoreManager getCoreManager() {
return coreManager;
}
/**
* @param coreManager the coreManager to set
*/
public void setCoreManager(CoreManager coreManager) {
logger.debug("Setting ORServeGatewayMessageHandlerImpl.coreManager");
logger.debug(coreManager);
this.coreManager = coreManager;
}
public Map<MStatus, String> getCodeStatusMap() {
return codeStatusMap;
}
public void setCodeStatusMap(Map<MStatus, String> codeStatusMap) {
this.codeStatusMap = codeStatusMap;
}
public Map<MStatus, String> getCodeResponseMap() {
return codeResponseMap;
}
public void setCodeResponseMap(Map<MStatus, String> codeResponseMap) {
this.codeResponseMap = codeResponseMap;
}
}
| true | true | public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse, MotechContext context) {
logger.info("Parsing message gateway response");
logger.debug(gatewayResponse);
if(message == null)
return null;
if(gatewayResponse.isEmpty())
return null;
Set<GatewayResponse> responses = new HashSet<GatewayResponse>();
if(gatewayResponse.contains("error:") && gatewayResponse.contains("param:")){
gatewayResponse = gatewayResponse.substring(0, 15).replace("\n", "");
}
String[] responseLines = gatewayResponse.split("\n");
for(String line : responseLines){
String[] responseParts = line.split(" ");
if(responseParts[0].equalsIgnoreCase("ID:")){
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setGatewayMessageId(responseParts[1]);
response.setRequestId(message.getRequestId());
response.setMessageStatus(MStatus.PENDING);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
if(responseParts.length == 4)
response.setRecipientNumber(responseParts[3]);
else
response.setRecipientNumber(message.getRecipientsNumber());
responses.add(response);
}
else{
logger.error("Gateway returned error: " + gatewayResponse);
String errorCode = responseParts[1];
errorCode.replaceAll(",", "");
errorCode.trim();
MStatus status = lookupResponse(errorCode);
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setRequestId(message.getRequestId());
response.setMessageStatus(status);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
responses.add(response);
}
}
logger.debug(responses);
return responses;
}
| public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse, MotechContext context) {
logger.info("Parsing message gateway response");
logger.debug(gatewayResponse);
if(message == null)
return null;
if(gatewayResponse.isEmpty())
return null;
Set<GatewayResponse> responses = new HashSet<GatewayResponse>();
if(gatewayResponse.contains("error:") && gatewayResponse.contains("param:")){
gatewayResponse = gatewayResponse.trim().replace("\n", "");
}
String[] responseLines = gatewayResponse.split("\n");
for(String line : responseLines){
String[] responseParts = line.split(" ");
if(responseParts[0].equalsIgnoreCase("ID:")){
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setGatewayMessageId(responseParts[1]);
response.setRequestId(message.getRequestId());
response.setMessageStatus(MStatus.PENDING);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
if(responseParts.length == 4)
response.setRecipientNumber(responseParts[3]);
else
response.setRecipientNumber(message.getRecipientsNumber());
responses.add(response);
}
else{
logger.error("Gateway returned error: " + gatewayResponse);
String errorCode = responseParts[1];
errorCode.replaceAll(",", "");
errorCode.trim();
MStatus status = lookupResponse(errorCode);
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setRequestId(message.getRequestId());
response.setMessageStatus(status);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
responses.add(response);
}
}
logger.debug(responses);
return responses;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.