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/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java index 55041154..fbfde97e 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java @@ -1,815 +1,819 @@ /* * 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.android.inputmethod.keyboard; import com.android.inputmethod.compat.InputMethodManagerCompatWrapper; import com.android.inputmethod.latin.LatinIME; import com.android.inputmethod.latin.LatinImeLogger; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.Settings; import com.android.inputmethod.latin.SubtypeSwitcher; import com.android.inputmethod.latin.Utils; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.util.Log; import android.view.InflateException; import android.view.inputmethod.EditorInfo; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Locale; public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = "KeyboardSwitcher"; private static final boolean DEBUG = false; public static final boolean DEBUG_STATE = false; private static String sConfigDefaultKeyboardThemeId; public static final String PREF_KEYBOARD_LAYOUT = "pref_keyboard_layout_20100902"; private static final int[] KEYBOARD_THEMES = { R.layout.input_basic, R.layout.input_basic_highcontrast, R.layout.input_stone_normal, R.layout.input_stone_bold, R.layout.input_gingerbread, R.layout.input_honeycomb, }; private SubtypeSwitcher mSubtypeSwitcher; private SharedPreferences mPrefs; private LatinKeyboardView mInputView; private LatinIME mInputMethodService; // TODO: Combine these key state objects with auto mode switch state. private ShiftKeyState mShiftKeyState = new ShiftKeyState("Shift"); private ModifierKeyState mSymbolKeyState = new ModifierKeyState("Symbol"); private KeyboardId mSymbolsId; private KeyboardId mSymbolsShiftedId; private KeyboardId mCurrentId; private final HashMap<KeyboardId, SoftReference<LatinKeyboard>> mKeyboardCache = new HashMap<KeyboardId, SoftReference<LatinKeyboard>>(); private EditorInfo mAttribute; private boolean mIsSymbols; /** mIsAutoCorrectionActive indicates that auto corrected word will be input instead of * what user actually typed. */ private boolean mIsAutoCorrectionActive; private boolean mVoiceKeyEnabled; private boolean mVoiceButtonOnPrimary; // TODO: Encapsulate these state handling to separate class and combine with ShiftKeyState // and ModifierKeyState. private static final int SWITCH_STATE_ALPHA = 0; private static final int SWITCH_STATE_SYMBOL_BEGIN = 1; private static final int SWITCH_STATE_SYMBOL = 2; // The following states are used only on the distinct multi-touch panel devices. private static final int SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL = 3; private static final int SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE = 4; private static final int SWITCH_STATE_CHORDING_ALPHA = 5; private static final int SWITCH_STATE_CHORDING_SYMBOL = 6; private int mSwitchState = SWITCH_STATE_ALPHA; // Indicates whether or not we have the settings key in option of settings private boolean mSettingsKeyEnabledInSettings; private static final int SETTINGS_KEY_MODE_AUTO = R.string.settings_key_mode_auto; private static final int SETTINGS_KEY_MODE_ALWAYS_SHOW = R.string.settings_key_mode_always_show; // NOTE: No need to have SETTINGS_KEY_MODE_ALWAYS_HIDE here because it's not being referred to // in the source code now. // Default is SETTINGS_KEY_MODE_AUTO. private static final int DEFAULT_SETTINGS_KEY_MODE = SETTINGS_KEY_MODE_AUTO; private int mLayoutId; private static final KeyboardSwitcher sInstance = new KeyboardSwitcher(); public static KeyboardSwitcher getInstance() { return sInstance; } private KeyboardSwitcher() { // Intentional empty constructor for singleton. } public static void init(LatinIME ims, SharedPreferences prefs) { sInstance.mInputMethodService = ims; sInstance.mPrefs = prefs; sInstance.mSubtypeSwitcher = SubtypeSwitcher.getInstance(); try { sConfigDefaultKeyboardThemeId = ims.getString( R.string.config_default_keyboard_theme_id); sInstance.mLayoutId = Integer.valueOf( prefs.getString(PREF_KEYBOARD_LAYOUT, sConfigDefaultKeyboardThemeId)); } catch (NumberFormatException e) { sConfigDefaultKeyboardThemeId = "0"; sInstance.mLayoutId = 0; } prefs.registerOnSharedPreferenceChangeListener(sInstance); } public void loadKeyboard(EditorInfo attribute, boolean voiceKeyEnabled, boolean voiceButtonOnPrimary) { mSwitchState = SWITCH_STATE_ALPHA; try { loadKeyboardInternal(attribute, voiceKeyEnabled, voiceButtonOnPrimary, false); } catch (RuntimeException e) { // Get KeyboardId to record which keyboard has been failed to load. final KeyboardId id = getKeyboardId(attribute, false); Log.w(TAG, "loading keyboard failed: " + id, e); LatinImeLogger.logOnException(id.toString(), e); } } private void loadKeyboardInternal(EditorInfo attribute, boolean voiceButtonEnabled, boolean voiceButtonOnPrimary, boolean isSymbols) { if (mInputView == null) return; mAttribute = attribute; mVoiceKeyEnabled = voiceButtonEnabled; mVoiceButtonOnPrimary = voiceButtonOnPrimary; mIsSymbols = isSymbols; // Update the settings key state because number of enabled IMEs could have been changed mSettingsKeyEnabledInSettings = getSettingsKeyMode(mPrefs, mInputMethodService); final KeyboardId id = getKeyboardId(attribute, isSymbols); makeSymbolsKeyboardIds(id.mMode, attribute); mCurrentId = id; mInputView.setKeyPreviewEnabled(mInputMethodService.getPopupOn()); setKeyboard(getKeyboard(id)); } private void setKeyboard(final Keyboard newKeyboard) { final Keyboard oldKeyboard = mInputView.getKeyboard(); mInputView.setKeyboard(newKeyboard); final boolean localeChanged = (oldKeyboard == null) || !newKeyboard.mId.mLocale.equals(oldKeyboard.mId.mLocale); mInputMethodService.mHandler.startDisplayLanguageOnSpacebar(localeChanged); } private LatinKeyboard getKeyboard(KeyboardId id) { final SoftReference<LatinKeyboard> ref = mKeyboardCache.get(id); LatinKeyboard keyboard = (ref == null) ? null : ref.get(); if (keyboard == null) { final Resources res = mInputMethodService.getResources(); final Locale savedLocale = Utils.setSystemLocale(res, mSubtypeSwitcher.getInputLocale()); keyboard = new LatinKeyboard(mInputMethodService, id); if (id.mEnableShiftLock) { keyboard.enableShiftLock(); } mKeyboardCache.put(id, new SoftReference<LatinKeyboard>(keyboard)); if (DEBUG) Log.d(TAG, "keyboard cache size=" + mKeyboardCache.size() + ": " + ((ref == null) ? "LOAD" : "GCed") + " id=" + id); Utils.setSystemLocale(res, savedLocale); } else if (DEBUG) { Log.d(TAG, "keyboard cache size=" + mKeyboardCache.size() + ": HIT id=" + id); } keyboard.onAutoCorrectionStateChanged(mIsAutoCorrectionActive); keyboard.setShifted(false); // If the cached keyboard had been switched to another keyboard while the language was // displayed on its spacebar, it might have had arbitrary text fade factor. In such case, // we should reset the text fade factor. It is also applicable to shortcut key. keyboard.setSpacebarTextFadeFactor(0.0f, null); keyboard.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady(), null); keyboard.setSpacebarSlidingLanguageSwitchDiff(0); return keyboard; } private boolean hasVoiceKey(boolean isSymbols) { return mVoiceKeyEnabled && (isSymbols != mVoiceButtonOnPrimary); } private boolean hasSettingsKey(EditorInfo attribute) { return mSettingsKeyEnabledInSettings && !Utils.inPrivateImeOptions(mInputMethodService.getPackageName(), LatinIME.IME_OPTION_NO_SETTINGS_KEY, attribute); } private KeyboardId getKeyboardId(EditorInfo attribute, boolean isSymbols) { final int mode = Utils.getKeyboardMode(attribute); final boolean hasVoiceKey = hasVoiceKey(isSymbols); final int charColorId = getColorScheme(); final int xmlId; final boolean enableShiftLock; if (isSymbols) { if (mode == KeyboardId.MODE_PHONE) { xmlId = R.xml.kbd_phone_symbols; } else if (mode == KeyboardId.MODE_NUMBER) { // Note: MODE_NUMBER keyboard layout has no "switch alpha symbol" key. xmlId = R.xml.kbd_number; } else { xmlId = R.xml.kbd_symbols; } enableShiftLock = false; } else { if (mode == KeyboardId.MODE_PHONE) { xmlId = R.xml.kbd_phone; enableShiftLock = false; } else if (mode == KeyboardId.MODE_NUMBER) { xmlId = R.xml.kbd_number; enableShiftLock = false; } else { xmlId = R.xml.kbd_qwerty; enableShiftLock = true; } } final boolean hasSettingsKey = hasSettingsKey(attribute); final Resources res = mInputMethodService.getResources(); final int orientation = res.getConfiguration().orientation; final Locale locale = mSubtypeSwitcher.getInputLocale(); return new KeyboardId( res.getResourceEntryName(xmlId), xmlId, charColorId, locale, orientation, mode, attribute, hasSettingsKey, mVoiceKeyEnabled, hasVoiceKey, enableShiftLock); } private void makeSymbolsKeyboardIds(final int mode, EditorInfo attribute) { final Locale locale = mSubtypeSwitcher.getInputLocale(); final Resources res = mInputMethodService.getResources(); final int orientation = res.getConfiguration().orientation; final int colorScheme = getColorScheme(); final boolean hasVoiceKey = mVoiceKeyEnabled && !mVoiceButtonOnPrimary; final boolean hasSettingsKey = hasSettingsKey(attribute); // Note: This comment is only applied for phone number keyboard layout. // On non-xlarge device, "@integer/key_switch_alpha_symbol" key code is used to switch // between "phone keyboard" and "phone symbols keyboard". But on xlarge device, // "@integer/key_shift" key code is used for that purpose in order to properly display // "more" and "locked more" key labels. To achieve these behavior, we should initialize // mSymbolsId and mSymbolsShiftedId to "phone keyboard" and "phone symbols keyboard" // respectively here for xlarge device's layout switching. int xmlId = mode == KeyboardId.MODE_PHONE ? R.xml.kbd_phone : R.xml.kbd_symbols; final String xmlName = res.getResourceEntryName(xmlId); mSymbolsId = new KeyboardId(xmlName, xmlId, colorScheme, locale, orientation, mode, attribute, hasSettingsKey, mVoiceKeyEnabled, hasVoiceKey, false); xmlId = mode == KeyboardId.MODE_PHONE ? R.xml.kbd_phone_symbols : R.xml.kbd_symbols_shift; mSymbolsShiftedId = new KeyboardId(xmlName, xmlId, colorScheme, locale, orientation, mode, attribute, hasSettingsKey, mVoiceKeyEnabled, hasVoiceKey, false); } public int getKeyboardMode() { return mCurrentId != null ? mCurrentId.mMode : KeyboardId.MODE_TEXT; } public boolean isAlphabetMode() { return mCurrentId != null && mCurrentId.isAlphabetKeyboard(); } public boolean isInputViewShown() { return mInputView != null && mInputView.isShown(); } public boolean isKeyboardAvailable() { if (mInputView != null) return mInputView.getKeyboard() != null; return false; } public LatinKeyboard getLatinKeyboard() { if (mInputView != null) { final Keyboard keyboard = mInputView.getKeyboard(); if (keyboard instanceof LatinKeyboard) return (LatinKeyboard)keyboard; } return null; } public boolean isShiftedOrShiftLocked() { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null) return latinKeyboard.isShiftedOrShiftLocked(); return false; } public boolean isShiftLocked() { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null) return latinKeyboard.isShiftLocked(); return false; } public boolean isAutomaticTemporaryUpperCase() { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null) return latinKeyboard.isAutomaticTemporaryUpperCase(); return false; } public boolean isManualTemporaryUpperCase() { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null) return latinKeyboard.isManualTemporaryUpperCase(); return false; } private boolean isManualTemporaryUpperCaseFromAuto() { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null) return latinKeyboard.isManualTemporaryUpperCaseFromAuto(); return false; } private void setManualTemporaryUpperCase(boolean shifted) { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null) { // On non-distinct multi touch panel device, we should also turn off the shift locked // state when shift key is pressed to go to normal mode. // On the other hand, on distinct multi touch panel device, turning off the shift locked // state with shift key pressing is handled by onReleaseShift(). if ((!hasDistinctMultitouch() || isAccessibilityEnabled()) && !shifted && latinKeyboard.isShiftLocked()) { latinKeyboard.setShiftLocked(false); } if (latinKeyboard.setShifted(shifted)) { mInputView.invalidateAllKeys(); } } } private void setShiftLocked(boolean shiftLocked) { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null && latinKeyboard.setShiftLocked(shiftLocked)) { mInputView.invalidateAllKeys(); } } /** * Toggle keyboard shift state triggered by user touch event. */ public void toggleShift() { mInputMethodService.mHandler.cancelUpdateShiftState(); if (DEBUG_STATE) Log.d(TAG, "toggleShift:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " shiftKeyState=" + mShiftKeyState); if (isAlphabetMode()) { setManualTemporaryUpperCase(!isShiftedOrShiftLocked()); } else { toggleShiftInSymbol(); } } public void toggleCapsLock() { mInputMethodService.mHandler.cancelUpdateShiftState(); if (DEBUG_STATE) Log.d(TAG, "toggleCapsLock:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " shiftKeyState=" + mShiftKeyState); if (isAlphabetMode()) { if (isShiftLocked()) { // Shift key is long pressed while caps lock state, we will toggle back to normal // state. And mark as if shift key is released. setShiftLocked(false); mShiftKeyState.onRelease(); } else { setShiftLocked(true); } } } private void setAutomaticTemporaryUpperCase() { LatinKeyboard latinKeyboard = getLatinKeyboard(); if (latinKeyboard != null) { latinKeyboard.setAutomaticTemporaryUpperCase(); mInputView.invalidateAllKeys(); } } /** * Update keyboard shift state triggered by connected EditText status change. */ public void updateShiftState() { final ShiftKeyState shiftKeyState = mShiftKeyState; if (DEBUG_STATE) Log.d(TAG, "updateShiftState:" + " autoCaps=" + mInputMethodService.getCurrentAutoCapsState() + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " shiftKeyState=" + shiftKeyState); if (isAlphabetMode()) { if (!isShiftLocked() && !shiftKeyState.isIgnoring()) { if (shiftKeyState.isReleasing() && mInputMethodService.getCurrentAutoCapsState()) { // Only when shift key is releasing, automatic temporary upper case will be set. setAutomaticTemporaryUpperCase(); } else { setManualTemporaryUpperCase(shiftKeyState.isMomentary()); } } } else { // In symbol keyboard mode, we should clear shift key state because only alphabet // keyboard has shift key. shiftKeyState.onRelease(); } } public void changeKeyboardMode() { if (DEBUG_STATE) Log.d(TAG, "changeKeyboardMode:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " shiftKeyState=" + mShiftKeyState); toggleKeyboardMode(); if (isShiftLocked() && isAlphabetMode()) setShiftLocked(true); updateShiftState(); } public void onPressShift(boolean withSliding) { if (!isKeyboardAvailable()) return; // If accessibility is enabled, disable momentary shift lock. if (isAccessibilityEnabled()) return; ShiftKeyState shiftKeyState = mShiftKeyState; if (DEBUG_STATE) Log.d(TAG, "onPressShift:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " shiftKeyState=" + shiftKeyState + " sliding=" + withSliding); if (isAlphabetMode()) { if (isShiftLocked()) { // Shift key is pressed while caps lock state, we will treat this state as shifted // caps lock state and mark as if shift key pressed while normal state. shiftKeyState.onPress(); setManualTemporaryUpperCase(true); } else if (isAutomaticTemporaryUpperCase()) { // Shift key is pressed while automatic temporary upper case, we have to move to // manual temporary upper case. shiftKeyState.onPress(); setManualTemporaryUpperCase(true); } else if (isShiftedOrShiftLocked()) { // In manual upper case state, we just record shift key has been pressing while // shifted state. shiftKeyState.onPressOnShifted(); } else { // In base layout, chording or manual temporary upper case mode is started. shiftKeyState.onPress(); toggleShift(); } } else { // In symbol mode, just toggle symbol and symbol more keyboard. shiftKeyState.onPress(); toggleShift(); mSwitchState = SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE; } } public void onReleaseShift(boolean withSliding) { if (!isKeyboardAvailable()) return; // If accessibility is enabled, disable momentary shift lock. if (isAccessibilityEnabled()) return; ShiftKeyState shiftKeyState = mShiftKeyState; if (DEBUG_STATE) Log.d(TAG, "onReleaseShift:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " shiftKeyState=" + shiftKeyState + " sliding=" + withSliding); if (isAlphabetMode()) { if (shiftKeyState.isMomentary()) { // After chording input while normal state. toggleShift(); } else if (isShiftLocked() && !shiftKeyState.isIgnoring() && !withSliding) { // Shift has been pressed without chording while caps lock state. toggleCapsLock(); // To be able to turn off caps lock by "double tap" on shift key, we should ignore // the second tap of the "double tap" from now for a while because we just have // already turned off caps lock above. mInputView.startIgnoringDoubleTap(); } else if (isShiftedOrShiftLocked() && shiftKeyState.isPressingOnShifted() && !withSliding) { // Shift has been pressed without chording while shifted state. toggleShift(); } else if (isManualTemporaryUpperCaseFromAuto() && shiftKeyState.isPressing() && !withSliding) { // Shift has been pressed without chording while manual temporary upper case // transited from automatic temporary upper case. toggleShift(); } } else { // In symbol mode, snap back to the previous keyboard mode if the user chords the shift // key and another key, then releases the shift key. if (mSwitchState == SWITCH_STATE_CHORDING_SYMBOL) { toggleShift(); } } shiftKeyState.onRelease(); } public void onPressSymbol() { // If accessibility is enabled, disable momentary symbol lock. if (isAccessibilityEnabled()) return; if (DEBUG_STATE) Log.d(TAG, "onPressSymbol:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " symbolKeyState=" + mSymbolKeyState); changeKeyboardMode(); mSymbolKeyState.onPress(); mSwitchState = SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL; } public void onReleaseSymbol() { // If accessibility is enabled, disable momentary symbol lock. if (isAccessibilityEnabled()) return; if (DEBUG_STATE) Log.d(TAG, "onReleaseSymbol:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " symbolKeyState=" + mSymbolKeyState); // Snap back to the previous keyboard mode if the user chords the mode change key and // another key, then releases the mode change key. if (mSwitchState == SWITCH_STATE_CHORDING_ALPHA) { changeKeyboardMode(); } mSymbolKeyState.onRelease(); } public void onOtherKeyPressed() { // If accessibility is enabled, disable momentary mode locking. if (isAccessibilityEnabled()) return; if (DEBUG_STATE) Log.d(TAG, "onOtherKeyPressed:" + " keyboard=" + getLatinKeyboard().getKeyboardShiftState() + " shiftKeyState=" + mShiftKeyState + " symbolKeyState=" + mSymbolKeyState); mShiftKeyState.onOtherKeyPressed(); mSymbolKeyState.onOtherKeyPressed(); } public void onCancelInput() { // Snap back to the previous keyboard mode if the user cancels sliding input. if (getPointerCount() == 1) { if (mSwitchState == SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL) { changeKeyboardMode(); } else if (mSwitchState == SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE) { toggleShift(); } } } private void toggleShiftInSymbol() { if (isAlphabetMode()) return; final LatinKeyboard keyboard; if (mCurrentId.equals(mSymbolsId) || !mCurrentId.equals(mSymbolsShiftedId)) { mCurrentId = mSymbolsShiftedId; keyboard = getKeyboard(mCurrentId); // Symbol shifted keyboard has an ALT key that has a caps lock style indicator. To // enable the indicator, we need to call setShiftLocked(true). keyboard.setShiftLocked(true); } else { mCurrentId = mSymbolsId; keyboard = getKeyboard(mCurrentId); // Symbol keyboard has an ALT key that has a caps lock style indicator. To disable the // indicator, we need to call setShiftLocked(false). keyboard.setShiftLocked(false); } setKeyboard(keyboard); } public boolean isInMomentarySwitchState() { return mSwitchState == SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL || mSwitchState == SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE; } public boolean isVibrateAndSoundFeedbackRequired() { return mInputView == null || !mInputView.isInSlidingKeyInput(); } private int getPointerCount() { return mInputView == null ? 0 : mInputView.getPointerCount(); } private void toggleKeyboardMode() { loadKeyboardInternal(mAttribute, mVoiceKeyEnabled, mVoiceButtonOnPrimary, !mIsSymbols); if (mIsSymbols) { mSwitchState = SWITCH_STATE_SYMBOL_BEGIN; } else { mSwitchState = SWITCH_STATE_ALPHA; } } public boolean isAccessibilityEnabled() { return mInputView != null && mInputView.isAccessibilityEnabled(); } public boolean hasDistinctMultitouch() { return mInputView != null && mInputView.hasDistinctMultitouch(); } private static boolean isSpaceCharacter(int c) { return c == Keyboard.CODE_SPACE || c == Keyboard.CODE_ENTER; } private static boolean isQuoteCharacter(int c) { // Apostrophe, quotation mark. if (c == '\'' || c == '"') return true; // \u2018: Left single quotation mark // \u2019: Right single quotation mark // \u201a: Single low-9 quotation mark // \u201b: Single high-reversed-9 quotation mark // \u201c: Left double quotation mark // \u201d: Right double quotation mark // \u201e: Double low-9 quotation mark // \u201f: Double high-reversed-9 quotation mark if (c >= '\u2018' && c <= '\u201f') return true; // \u00ab: Left-pointing double angle quotation mark // \u00bb: Right-pointing double angle quotation mark if (c == '\u00ab' || c == '\u00bb') return true; return false; } /** * Updates state machine to figure out when to automatically snap back to the previous mode. */ public void onKey(int code) { if (DEBUG_STATE) Log.d(TAG, "onKey: code=" + code + " switchState=" + mSwitchState + " pointers=" + getPointerCount()); switch (mSwitchState) { case SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL: // Only distinct multi touch devices can be in this state. // On non-distinct multi touch devices, mode change key is handled by // {@link LatinIME#onCodeInput}, not by {@link LatinIME#onPress} and // {@link LatinIME#onRelease}. So, on such devices, {@link #mSwitchState} starts // from {@link #SWITCH_STATE_SYMBOL_BEGIN}, or {@link #SWITCH_STATE_ALPHA}, not from // {@link #SWITCH_STATE_MOMENTARY}. if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) { // Detected only the mode change key has been pressed, and then released. if (mIsSymbols) { mSwitchState = SWITCH_STATE_SYMBOL_BEGIN; } else { mSwitchState = SWITCH_STATE_ALPHA; } } else if (getPointerCount() == 1) { // Snap back to the previous keyboard mode if the user pressed the mode change key // and slid to other key, then released the finger. // If the user cancels the sliding input, snapping back to the previous keyboard // mode is handled by {@link #onCancelInput}. changeKeyboardMode(); } else { // Chording input is being started. The keyboard mode will be snapped back to the // previous mode in {@link onReleaseSymbol} when the mode change key is released. mSwitchState = SWITCH_STATE_CHORDING_ALPHA; } break; case SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE: if (code == Keyboard.CODE_SHIFT) { // Detected only the shift key has been pressed on symbol layout, and then released. mSwitchState = SWITCH_STATE_SYMBOL_BEGIN; } else if (getPointerCount() == 1) { // Snap back to the previous keyboard mode if the user pressed the shift key on // symbol mode and slid to other key, then released the finger. toggleShift(); mSwitchState = SWITCH_STATE_SYMBOL; } else { // Chording input is being started. The keyboard mode will be snapped back to the // previous mode in {@link onReleaseShift} when the shift key is released. mSwitchState = SWITCH_STATE_CHORDING_SYMBOL; } break; case SWITCH_STATE_SYMBOL_BEGIN: if (!isSpaceCharacter(code) && code >= 0) { mSwitchState = SWITCH_STATE_SYMBOL; } + // Snap back to alpha keyboard mode immediately if user types a quote character. + if (isQuoteCharacter(code)) { + changeKeyboardMode(); + } break; case SWITCH_STATE_SYMBOL: case SWITCH_STATE_CHORDING_SYMBOL: // Snap back to alpha keyboard mode if user types one or more non-space/enter - // characters followed by a space/enter or quotation mark. + // characters followed by a space/enter or a quote character. if (isSpaceCharacter(code) || isQuoteCharacter(code)) { changeKeyboardMode(); } break; } } public LatinKeyboardView getInputView() { return mInputView; } public LatinKeyboardView onCreateInputView() { createInputViewInternal(mLayoutId, true); return mInputView; } private void createInputViewInternal(int newLayout, boolean forceReset) { int layoutId = newLayout; if (mLayoutId != layoutId || mInputView == null || forceReset) { if (mInputView != null) { mInputView.closing(); } if (KEYBOARD_THEMES.length <= layoutId) { layoutId = Integer.valueOf(sConfigDefaultKeyboardThemeId); } Utils.GCUtils.getInstance().reset(); boolean tryGC = true; for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { mInputView = (LatinKeyboardView) mInputMethodService.getLayoutInflater( ).inflate(KEYBOARD_THEMES[layoutId], null); tryGC = false; } catch (OutOfMemoryError e) { Log.w(TAG, "load keyboard failed: " + e); tryGC = Utils.GCUtils.getInstance().tryGCOrWait( mLayoutId + "," + layoutId, e); } catch (InflateException e) { Log.w(TAG, "load keyboard failed: " + e); tryGC = Utils.GCUtils.getInstance().tryGCOrWait( mLayoutId + "," + layoutId, e); } } mInputView.setOnKeyboardActionListener(mInputMethodService); mLayoutId = layoutId; } } private void postSetInputView() { mInputMethodService.mHandler.post(new Runnable() { @Override public void run() { if (mInputView != null) { mInputMethodService.setInputView(mInputView); } mInputMethodService.updateInputViewShown(); } }); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (PREF_KEYBOARD_LAYOUT.equals(key)) { final int layoutId = Integer.valueOf( sharedPreferences.getString(key, sConfigDefaultKeyboardThemeId)); createInputViewInternal(layoutId, false); postSetInputView(); } else if (Settings.PREF_SETTINGS_KEY.equals(key)) { mSettingsKeyEnabledInSettings = getSettingsKeyMode(sharedPreferences, mInputMethodService); createInputViewInternal(mLayoutId, true); postSetInputView(); } } private int getColorScheme() { return (mInputView != null) ? mInputView.getColorScheme() : KeyboardView.COLOR_SCHEME_WHITE; } public void onAutoCorrectionStateChanged(boolean isAutoCorrection) { if (isAutoCorrection != mIsAutoCorrectionActive) { LatinKeyboardView keyboardView = getInputView(); mIsAutoCorrectionActive = isAutoCorrection; keyboardView.invalidateKey(((LatinKeyboard) keyboardView.getKeyboard()) .onAutoCorrectionStateChanged(isAutoCorrection)); } } private static boolean getSettingsKeyMode(SharedPreferences prefs, Context context) { Resources resources = context.getResources(); final boolean showSettingsKeyOption = resources.getBoolean( R.bool.config_enable_show_settings_key_option); if (showSettingsKeyOption) { final String settingsKeyMode = prefs.getString(Settings.PREF_SETTINGS_KEY, resources.getString(DEFAULT_SETTINGS_KEY_MODE)); // We show the settings key when 1) SETTINGS_KEY_MODE_ALWAYS_SHOW or // 2) SETTINGS_KEY_MODE_AUTO and there are two or more enabled IMEs on the system if (settingsKeyMode.equals(resources.getString(SETTINGS_KEY_MODE_ALWAYS_SHOW)) || (settingsKeyMode.equals(resources.getString(SETTINGS_KEY_MODE_AUTO)) && Utils.hasMultipleEnabledIMEsOrSubtypes( (InputMethodManagerCompatWrapper.getInstance(context))))) { return true; } return false; } // If the show settings key option is disabled, we always try showing the settings key. return true; } }
false
true
public void onKey(int code) { if (DEBUG_STATE) Log.d(TAG, "onKey: code=" + code + " switchState=" + mSwitchState + " pointers=" + getPointerCount()); switch (mSwitchState) { case SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL: // Only distinct multi touch devices can be in this state. // On non-distinct multi touch devices, mode change key is handled by // {@link LatinIME#onCodeInput}, not by {@link LatinIME#onPress} and // {@link LatinIME#onRelease}. So, on such devices, {@link #mSwitchState} starts // from {@link #SWITCH_STATE_SYMBOL_BEGIN}, or {@link #SWITCH_STATE_ALPHA}, not from // {@link #SWITCH_STATE_MOMENTARY}. if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) { // Detected only the mode change key has been pressed, and then released. if (mIsSymbols) { mSwitchState = SWITCH_STATE_SYMBOL_BEGIN; } else { mSwitchState = SWITCH_STATE_ALPHA; } } else if (getPointerCount() == 1) { // Snap back to the previous keyboard mode if the user pressed the mode change key // and slid to other key, then released the finger. // If the user cancels the sliding input, snapping back to the previous keyboard // mode is handled by {@link #onCancelInput}. changeKeyboardMode(); } else { // Chording input is being started. The keyboard mode will be snapped back to the // previous mode in {@link onReleaseSymbol} when the mode change key is released. mSwitchState = SWITCH_STATE_CHORDING_ALPHA; } break; case SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE: if (code == Keyboard.CODE_SHIFT) { // Detected only the shift key has been pressed on symbol layout, and then released. mSwitchState = SWITCH_STATE_SYMBOL_BEGIN; } else if (getPointerCount() == 1) { // Snap back to the previous keyboard mode if the user pressed the shift key on // symbol mode and slid to other key, then released the finger. toggleShift(); mSwitchState = SWITCH_STATE_SYMBOL; } else { // Chording input is being started. The keyboard mode will be snapped back to the // previous mode in {@link onReleaseShift} when the shift key is released. mSwitchState = SWITCH_STATE_CHORDING_SYMBOL; } break; case SWITCH_STATE_SYMBOL_BEGIN: if (!isSpaceCharacter(code) && code >= 0) { mSwitchState = SWITCH_STATE_SYMBOL; } break; case SWITCH_STATE_SYMBOL: case SWITCH_STATE_CHORDING_SYMBOL: // Snap back to alpha keyboard mode if user types one or more non-space/enter // characters followed by a space/enter or quotation mark. if (isSpaceCharacter(code) || isQuoteCharacter(code)) { changeKeyboardMode(); } break; } }
public void onKey(int code) { if (DEBUG_STATE) Log.d(TAG, "onKey: code=" + code + " switchState=" + mSwitchState + " pointers=" + getPointerCount()); switch (mSwitchState) { case SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL: // Only distinct multi touch devices can be in this state. // On non-distinct multi touch devices, mode change key is handled by // {@link LatinIME#onCodeInput}, not by {@link LatinIME#onPress} and // {@link LatinIME#onRelease}. So, on such devices, {@link #mSwitchState} starts // from {@link #SWITCH_STATE_SYMBOL_BEGIN}, or {@link #SWITCH_STATE_ALPHA}, not from // {@link #SWITCH_STATE_MOMENTARY}. if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) { // Detected only the mode change key has been pressed, and then released. if (mIsSymbols) { mSwitchState = SWITCH_STATE_SYMBOL_BEGIN; } else { mSwitchState = SWITCH_STATE_ALPHA; } } else if (getPointerCount() == 1) { // Snap back to the previous keyboard mode if the user pressed the mode change key // and slid to other key, then released the finger. // If the user cancels the sliding input, snapping back to the previous keyboard // mode is handled by {@link #onCancelInput}. changeKeyboardMode(); } else { // Chording input is being started. The keyboard mode will be snapped back to the // previous mode in {@link onReleaseSymbol} when the mode change key is released. mSwitchState = SWITCH_STATE_CHORDING_ALPHA; } break; case SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE: if (code == Keyboard.CODE_SHIFT) { // Detected only the shift key has been pressed on symbol layout, and then released. mSwitchState = SWITCH_STATE_SYMBOL_BEGIN; } else if (getPointerCount() == 1) { // Snap back to the previous keyboard mode if the user pressed the shift key on // symbol mode and slid to other key, then released the finger. toggleShift(); mSwitchState = SWITCH_STATE_SYMBOL; } else { // Chording input is being started. The keyboard mode will be snapped back to the // previous mode in {@link onReleaseShift} when the shift key is released. mSwitchState = SWITCH_STATE_CHORDING_SYMBOL; } break; case SWITCH_STATE_SYMBOL_BEGIN: if (!isSpaceCharacter(code) && code >= 0) { mSwitchState = SWITCH_STATE_SYMBOL; } // Snap back to alpha keyboard mode immediately if user types a quote character. if (isQuoteCharacter(code)) { changeKeyboardMode(); } break; case SWITCH_STATE_SYMBOL: case SWITCH_STATE_CHORDING_SYMBOL: // Snap back to alpha keyboard mode if user types one or more non-space/enter // characters followed by a space/enter or a quote character. if (isSpaceCharacter(code) || isQuoteCharacter(code)) { changeKeyboardMode(); } break; } }
diff --git a/src/com/mrockey28/bukkit/ItemRepair/Repair.java b/src/com/mrockey28/bukkit/ItemRepair/Repair.java index b2265d2..03ecbac 100644 --- a/src/com/mrockey28/bukkit/ItemRepair/Repair.java +++ b/src/com/mrockey28/bukkit/ItemRepair/Repair.java @@ -1,122 +1,122 @@ package com.mrockey28.bukkit.ItemRepair; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Logger; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.mrockey28.bukkit.ItemRepair.AutoRepairPlugin.operationType; public class Repair extends AutoRepairSupport{ public static final Logger log = Logger.getLogger("Minecraft"); public Repair(AutoRepairPlugin instance) { super(instance, getPlayer()); } public boolean manualRepair(ItemStack tool) { doRepairOperation(tool, operationType.MANUAL_REPAIR); return false; } public boolean autoRepairTool(ItemStack tool) { doRepairOperation(tool, operationType.AUTO_REPAIR); return false; } public void repairAll(Player player) { ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0); HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts(); for (ItemStack item : player.getInventory().getContents()) { - if (item == null || item.getType() == Material.AIR) + if (item == null || item.getType() == Material.AIR || item.getType() == Material.WOOL) { continue; } if (item.getDurability() != 0) { doRepairOperation(item, operationType.FULL_REPAIR); if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString())) { couldNotRepair.add(item); } } } for (ItemStack item : player.getInventory().getArmorContents()) { if (item == null || item.getType() == Material.AIR) { continue; } if (item.getDurability() != 0) { doRepairOperation(item, operationType.FULL_REPAIR); if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString())) { couldNotRepair.add(item); } } } if (!couldNotRepair.isEmpty()) { String itemsNotRepaired = ""; for (ItemStack item : couldNotRepair) { itemsNotRepaired += (item.getType().toString() + ", "); } itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2); player.sendMessage("�cDid not repair the following items: "); player.sendMessage("�c" + itemsNotRepaired); } } public void repairArmor(Player player) { ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0); HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts(); for (ItemStack item : player.getInventory().getArmorContents()) { if (item == null || item.getType() == Material.AIR) { continue; } if (item.getDurability() != 0) { doRepairOperation(item, operationType.FULL_REPAIR); if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString())) { couldNotRepair.add(item); } } } if (!couldNotRepair.isEmpty()) { String itemsNotRepaired = ""; for (ItemStack item : couldNotRepair) { itemsNotRepaired += (item.getType().toString() + ", "); } itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2); player.sendMessage("�cDid not repair the following items: "); player.sendMessage("�c" + itemsNotRepaired); } } }
true
true
public void repairAll(Player player) { ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0); HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts(); for (ItemStack item : player.getInventory().getContents()) { if (item == null || item.getType() == Material.AIR) { continue; } if (item.getDurability() != 0) { doRepairOperation(item, operationType.FULL_REPAIR); if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString())) { couldNotRepair.add(item); } } } for (ItemStack item : player.getInventory().getArmorContents()) { if (item == null || item.getType() == Material.AIR) { continue; } if (item.getDurability() != 0) { doRepairOperation(item, operationType.FULL_REPAIR); if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString())) { couldNotRepair.add(item); } } } if (!couldNotRepair.isEmpty()) { String itemsNotRepaired = ""; for (ItemStack item : couldNotRepair) { itemsNotRepaired += (item.getType().toString() + ", "); } itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2); player.sendMessage("�cDid not repair the following items: "); player.sendMessage("�c" + itemsNotRepaired); } }
public void repairAll(Player player) { ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0); HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts(); for (ItemStack item : player.getInventory().getContents()) { if (item == null || item.getType() == Material.AIR || item.getType() == Material.WOOL) { continue; } if (item.getDurability() != 0) { doRepairOperation(item, operationType.FULL_REPAIR); if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString())) { couldNotRepair.add(item); } } } for (ItemStack item : player.getInventory().getArmorContents()) { if (item == null || item.getType() == Material.AIR) { continue; } if (item.getDurability() != 0) { doRepairOperation(item, operationType.FULL_REPAIR); if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString())) { couldNotRepair.add(item); } } } if (!couldNotRepair.isEmpty()) { String itemsNotRepaired = ""; for (ItemStack item : couldNotRepair) { itemsNotRepaired += (item.getType().toString() + ", "); } itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2); player.sendMessage("�cDid not repair the following items: "); player.sendMessage("�c" + itemsNotRepaired); } }
diff --git a/kundera-core/src/main/java/com/impetus/kundera/graph/ObjectGraphBuilder.java b/kundera-core/src/main/java/com/impetus/kundera/graph/ObjectGraphBuilder.java index ef240e5da..d9cdf4b22 100644 --- a/kundera-core/src/main/java/com/impetus/kundera/graph/ObjectGraphBuilder.java +++ b/kundera-core/src/main/java/com/impetus/kundera/graph/ObjectGraphBuilder.java @@ -1,336 +1,336 @@ /** * Copyright 2012 Impetus Infotech. * * 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.impetus.kundera.graph; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.persistence.GeneratedValue; import javax.persistence.MapKeyJoinColumn; import org.apache.commons.lang.StringUtils; import com.impetus.kundera.graph.NodeLink.LinkProperty; import com.impetus.kundera.lifecycle.states.DetachedState; import com.impetus.kundera.lifecycle.states.ManagedState; import com.impetus.kundera.lifecycle.states.NodeState; import com.impetus.kundera.lifecycle.states.RemovedState; import com.impetus.kundera.lifecycle.states.TransientState; import com.impetus.kundera.metadata.KunderaMetadataManager; import com.impetus.kundera.metadata.MetadataUtils; import com.impetus.kundera.metadata.model.EntityMetadata; import com.impetus.kundera.metadata.model.Relation; import com.impetus.kundera.persistence.IdGenerator; import com.impetus.kundera.persistence.PersistenceDelegator; import com.impetus.kundera.persistence.PersistenceValidator; import com.impetus.kundera.persistence.context.PersistenceCache; import com.impetus.kundera.property.PropertyAccessorHelper; import com.impetus.kundera.proxy.KunderaProxy; import com.impetus.kundera.proxy.ProxyHelper; import com.impetus.kundera.proxy.collection.ProxyCollection; import com.impetus.kundera.utils.DeepEquals; /** * Responsible for generating {@link ObjectGraph} of nodes from a given entity * * @author amresh.singh */ public class ObjectGraphBuilder { private PersistenceCache persistenceCache; private PersistenceDelegator pd; private IdGenerator idGenerator; private PersistenceValidator validator; public ObjectGraphBuilder(PersistenceCache pcCache, PersistenceDelegator pd) { this.persistenceCache = pcCache; this.pd = pd; this.idGenerator = new IdGenerator(); this.validator = new PersistenceValidator(); } public ObjectGraph getObjectGraph(Object entity, NodeState initialNodeState) { // Initialize object graph ObjectGraph objectGraph = new ObjectGraph(); // Recursively build object graph and get head node. Node headNode = getNode(entity, objectGraph, initialNodeState); // Set head node into object graph if (headNode != null) { objectGraph.setHeadNode(headNode); } return objectGraph; } /** * Constructs and returns {@link Node} representation for a given entity * object. Output is fully constructed graph with relationships embedded. * Each node is put into <code>graph</code> once it is constructed. * * @param entity * @return */ private Node getNode(Object entity, ObjectGraph graph, NodeState initialNodeState) { EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(entity.getClass()); // entity metadata could be null. if (entityMetadata == null) { throw new IllegalArgumentException( "Entity object is invalid, operation failed. Please check previous log message for details"); } // Generate and set Id if @GeneratedValue present. if (((Field) entityMetadata.getIdAttribute().getJavaMember()).isAnnotationPresent(GeneratedValue.class)) { Object id = PropertyAccessorHelper.getId(entity, entityMetadata); Node nodeInPersistenceCache = null; if (id != null) { String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass()); nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId); } // if node not in persistence cache it means it came first time // for persist, then generate id for it. if (nodeInPersistenceCache == null - || !nodeInPersistenceCache.getCurrentNodeState().equals(ManagedState.class)) + || !nodeInPersistenceCache.getCurrentNodeState().getClass().isAssignableFrom(ManagedState.class)) { idGenerator.generateAndSetId(entity, entityMetadata, pd); } } if (!validator.isValidEntityObject(entity)) { throw new IllegalArgumentException( "Entity object is invalid, operation failed. Please check previous log message for details"); } Object id = PropertyAccessorHelper.getId(entity, entityMetadata); String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass()); Node node = graph.getNode(nodeId); // If this node is already there in graph (may happen for bidirectional // relationship, do nothing and return null) if (node != null) { if (node.isGraphCompleted()) { return node; } return null; } // Construct this Node first, if one not already there in Persistence // Cache Node nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId); // Make a deep copy of entity data if (nodeInPersistenceCache == null) { node = new Node(nodeId, entity, initialNodeState, persistenceCache, id); } else { node = nodeInPersistenceCache; // Determine whether this node is dirty based on comparison between // Node data and entity data // If dirty, set the entity data into node and mark it as dirty if (!DeepEquals.deepEquals(node.getData(), entity)) { node.setData(entity); node.setDirty(true); } else if (node.isProcessed()) { node.setDirty(false); } // If node is NOT in managed state, its data needs to be // replaced with the one provided in entity object } // Put this node into object graph graph.addNode(nodeId, node); // Iterate over relations and construct children nodes for (Relation relation : entityMetadata.getRelations()) { // Child Object set in this entity Object childObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); if (childObject != null && !ProxyHelper.isProxy(childObject)) { EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(childObject.getClass()); if (metadata != null && relation.isJoinedByPrimaryKey()) { PropertyAccessorHelper.setId(childObject, metadata, PropertyAccessorHelper.getId(entity, entityMetadata)); } // This child object could be either an entity(1-1 or M-1) // or a // collection/ Map of entities(1-M or M-M) if (Collection.class.isAssignableFrom(childObject.getClass())) { // For each entity in the collection, construct a child // node and add to graph Collection childrenObjects = (Collection) childObject; if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects)) for (Object childObj : childrenObjects) { if (childObj != null) { addChildNodesToGraph(graph, node, relation, childObj, initialNodeState); } } } else if (Map.class.isAssignableFrom(childObject.getClass())) { Map childrenObjects = (Map) childObject; if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects)) { for (Map.Entry entry : (Set<Map.Entry>) childrenObjects.entrySet()) { addChildNodesToGraph(graph, node, relation, entry, initialNodeState); } } } else { // Construct child node and add to graph addChildNodesToGraph(graph, node, relation, childObject, initialNodeState); } } } // Means compelte graph is build. node.setGraphCompleted(true); return node; } /** * @param graph * @param node * @param relation * @param childObject */ private void addChildNodesToGraph(ObjectGraph graph, Node node, Relation relation, Object childObject, NodeState initialNodeState) { if (childObject instanceof KunderaProxy || childObject instanceof ProxyCollection) { return; } else if (childObject instanceof Map.Entry) { Map.Entry entry = (Map.Entry) childObject; Object relObject = entry.getKey(); Object entityObject = entry.getValue(); Node childNode = getNode(entityObject, graph, initialNodeState); if (childNode != null) { if (!StringUtils.isEmpty(relation.getMappedBy()) && relation.getProperty().getAnnotation(MapKeyJoinColumn.class) == null) { return; } NodeLink nodeLink = new NodeLink(node.getNodeId(), childNode.getNodeId()); nodeLink.setMultiplicity(relation.getType()); EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getDataClass()); nodeLink.setLinkProperties(getLinkProperties(metadata, relation)); nodeLink.addLinkProperty(LinkProperty.LINK_VALUE, relObject); // Add Parent node to this child childNode.addParentNode(nodeLink, node); // Add child node to this node node.addChildNode(nodeLink, childNode); } } else { // Construct child node for this child object via recursive call Node childNode = getNode(childObject, graph, initialNodeState); if (childNode != null) { // Construct Node Link for this relationship NodeLink nodeLink = new NodeLink(node.getNodeId(), childNode.getNodeId()); nodeLink.setMultiplicity(relation.getType()); EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getDataClass()); nodeLink.setLinkProperties(getLinkProperties(metadata, relation)); // Add Parent node to this child childNode.addParentNode(nodeLink, node); // Add child node to this node node.addChildNode(nodeLink, childNode); } } } /** * * @param metadata * Entity metadata of the parent node * @param relation * @return */ private Map<LinkProperty, Object> getLinkProperties(EntityMetadata metadata, Relation relation) { Map<LinkProperty, Object> linkProperties = new HashMap<NodeLink.LinkProperty, Object>(); linkProperties.put(LinkProperty.LINK_NAME, MetadataUtils.getMappedName(metadata, relation)); linkProperties.put(LinkProperty.IS_SHARED_BY_PRIMARY_KEY, relation.isJoinedByPrimaryKey()); linkProperties.put(LinkProperty.IS_BIDIRECTIONAL, !relation.isUnary()); linkProperties.put(LinkProperty.IS_RELATED_VIA_JOIN_TABLE, relation.isRelatedViaJoinTable()); linkProperties.put(LinkProperty.PROPERTY, relation.getProperty()); linkProperties.put(LinkProperty.CASCADE, relation.getCascades()); if (relation.isRelatedViaJoinTable()) { linkProperties.put(LinkProperty.JOIN_TABLE_METADATA, relation.getJoinTableMetadata()); } // TODO: Add more link properties as required return linkProperties; } }
true
true
private Node getNode(Object entity, ObjectGraph graph, NodeState initialNodeState) { EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(entity.getClass()); // entity metadata could be null. if (entityMetadata == null) { throw new IllegalArgumentException( "Entity object is invalid, operation failed. Please check previous log message for details"); } // Generate and set Id if @GeneratedValue present. if (((Field) entityMetadata.getIdAttribute().getJavaMember()).isAnnotationPresent(GeneratedValue.class)) { Object id = PropertyAccessorHelper.getId(entity, entityMetadata); Node nodeInPersistenceCache = null; if (id != null) { String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass()); nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId); } // if node not in persistence cache it means it came first time // for persist, then generate id for it. if (nodeInPersistenceCache == null || !nodeInPersistenceCache.getCurrentNodeState().equals(ManagedState.class)) { idGenerator.generateAndSetId(entity, entityMetadata, pd); } } if (!validator.isValidEntityObject(entity)) { throw new IllegalArgumentException( "Entity object is invalid, operation failed. Please check previous log message for details"); } Object id = PropertyAccessorHelper.getId(entity, entityMetadata); String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass()); Node node = graph.getNode(nodeId); // If this node is already there in graph (may happen for bidirectional // relationship, do nothing and return null) if (node != null) { if (node.isGraphCompleted()) { return node; } return null; } // Construct this Node first, if one not already there in Persistence // Cache Node nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId); // Make a deep copy of entity data if (nodeInPersistenceCache == null) { node = new Node(nodeId, entity, initialNodeState, persistenceCache, id); } else { node = nodeInPersistenceCache; // Determine whether this node is dirty based on comparison between // Node data and entity data // If dirty, set the entity data into node and mark it as dirty if (!DeepEquals.deepEquals(node.getData(), entity)) { node.setData(entity); node.setDirty(true); } else if (node.isProcessed()) { node.setDirty(false); } // If node is NOT in managed state, its data needs to be // replaced with the one provided in entity object } // Put this node into object graph graph.addNode(nodeId, node); // Iterate over relations and construct children nodes for (Relation relation : entityMetadata.getRelations()) { // Child Object set in this entity Object childObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); if (childObject != null && !ProxyHelper.isProxy(childObject)) { EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(childObject.getClass()); if (metadata != null && relation.isJoinedByPrimaryKey()) { PropertyAccessorHelper.setId(childObject, metadata, PropertyAccessorHelper.getId(entity, entityMetadata)); } // This child object could be either an entity(1-1 or M-1) // or a // collection/ Map of entities(1-M or M-M) if (Collection.class.isAssignableFrom(childObject.getClass())) { // For each entity in the collection, construct a child // node and add to graph Collection childrenObjects = (Collection) childObject; if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects)) for (Object childObj : childrenObjects) { if (childObj != null) { addChildNodesToGraph(graph, node, relation, childObj, initialNodeState); } } } else if (Map.class.isAssignableFrom(childObject.getClass())) { Map childrenObjects = (Map) childObject; if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects)) { for (Map.Entry entry : (Set<Map.Entry>) childrenObjects.entrySet()) { addChildNodesToGraph(graph, node, relation, entry, initialNodeState); } } } else { // Construct child node and add to graph addChildNodesToGraph(graph, node, relation, childObject, initialNodeState); } } } // Means compelte graph is build. node.setGraphCompleted(true); return node; }
private Node getNode(Object entity, ObjectGraph graph, NodeState initialNodeState) { EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(entity.getClass()); // entity metadata could be null. if (entityMetadata == null) { throw new IllegalArgumentException( "Entity object is invalid, operation failed. Please check previous log message for details"); } // Generate and set Id if @GeneratedValue present. if (((Field) entityMetadata.getIdAttribute().getJavaMember()).isAnnotationPresent(GeneratedValue.class)) { Object id = PropertyAccessorHelper.getId(entity, entityMetadata); Node nodeInPersistenceCache = null; if (id != null) { String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass()); nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId); } // if node not in persistence cache it means it came first time // for persist, then generate id for it. if (nodeInPersistenceCache == null || !nodeInPersistenceCache.getCurrentNodeState().getClass().isAssignableFrom(ManagedState.class)) { idGenerator.generateAndSetId(entity, entityMetadata, pd); } } if (!validator.isValidEntityObject(entity)) { throw new IllegalArgumentException( "Entity object is invalid, operation failed. Please check previous log message for details"); } Object id = PropertyAccessorHelper.getId(entity, entityMetadata); String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass()); Node node = graph.getNode(nodeId); // If this node is already there in graph (may happen for bidirectional // relationship, do nothing and return null) if (node != null) { if (node.isGraphCompleted()) { return node; } return null; } // Construct this Node first, if one not already there in Persistence // Cache Node nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId); // Make a deep copy of entity data if (nodeInPersistenceCache == null) { node = new Node(nodeId, entity, initialNodeState, persistenceCache, id); } else { node = nodeInPersistenceCache; // Determine whether this node is dirty based on comparison between // Node data and entity data // If dirty, set the entity data into node and mark it as dirty if (!DeepEquals.deepEquals(node.getData(), entity)) { node.setData(entity); node.setDirty(true); } else if (node.isProcessed()) { node.setDirty(false); } // If node is NOT in managed state, its data needs to be // replaced with the one provided in entity object } // Put this node into object graph graph.addNode(nodeId, node); // Iterate over relations and construct children nodes for (Relation relation : entityMetadata.getRelations()) { // Child Object set in this entity Object childObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); if (childObject != null && !ProxyHelper.isProxy(childObject)) { EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(childObject.getClass()); if (metadata != null && relation.isJoinedByPrimaryKey()) { PropertyAccessorHelper.setId(childObject, metadata, PropertyAccessorHelper.getId(entity, entityMetadata)); } // This child object could be either an entity(1-1 or M-1) // or a // collection/ Map of entities(1-M or M-M) if (Collection.class.isAssignableFrom(childObject.getClass())) { // For each entity in the collection, construct a child // node and add to graph Collection childrenObjects = (Collection) childObject; if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects)) for (Object childObj : childrenObjects) { if (childObj != null) { addChildNodesToGraph(graph, node, relation, childObj, initialNodeState); } } } else if (Map.class.isAssignableFrom(childObject.getClass())) { Map childrenObjects = (Map) childObject; if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects)) { for (Map.Entry entry : (Set<Map.Entry>) childrenObjects.entrySet()) { addChildNodesToGraph(graph, node, relation, entry, initialNodeState); } } } else { // Construct child node and add to graph addChildNodesToGraph(graph, node, relation, childObject, initialNodeState); } } } // Means compelte graph is build. node.setGraphCompleted(true); return node; }
diff --git a/org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/dto/GitSynchronizeData.java b/org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/dto/GitSynchronizeData.java index 255aa5d8..f48f3654 100644 --- a/org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/dto/GitSynchronizeData.java +++ b/org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/dto/GitSynchronizeData.java @@ -1,150 +1,150 @@ /******************************************************************************* * Copyright (C) 2010, Dariusz Luksza <[email protected]> * * 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.egit.core.synchronize.dto; import static org.eclipse.core.runtime.Assert.isNotNull; import static org.eclipse.egit.core.RevUtils.getCommonAncestor; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.ObjectWalk; import org.eclipse.jgit.revwalk.RevCommit; /** * Simple data transfer object containing all necessary information for * launching synchronization */ public class GitSynchronizeData { private static final IWorkspaceRoot ROOT = ResourcesPlugin.getWorkspace() .getRoot(); private final boolean includeLocal; private final Repository repo; private final RevCommit srcRev; private final RevCommit dstRev; private final RevCommit commonAncestorRev; private final Set<IProject> projects; private final String repoParentPath; /** * Constructs {@link GitSynchronizeData} object * * @param repository * @param srcRev * @param dstRev * @param includeLocal * <code>true</code> if local changes should be included in * comparison * @throws IOException */ public GitSynchronizeData(Repository repository, String srcRev, String dstRev, boolean includeLocal) throws IOException { isNotNull(repository); isNotNull(srcRev); isNotNull(dstRev); repo = repository; ObjectWalk ow = new ObjectWalk(repo); - if (!srcRev.isEmpty()) + if (srcRev.length() > 0) this.srcRev = ow.parseCommit(repo.resolve(srcRev)); else this.srcRev = null; - if (!dstRev.isEmpty()) + if (dstRev.length() > 0) this.dstRev = ow.parseCommit(repo.resolve(dstRev)); else this.dstRev = null; if (this.dstRev != null || this.srcRev != null) this.commonAncestorRev = getCommonAncestor(repo, this.srcRev, this.dstRev); else this.commonAncestorRev = null; this.includeLocal = includeLocal; repoParentPath = repo.getDirectory().getParentFile().getAbsolutePath(); projects = new HashSet<IProject>(); final IProject[] workspaceProjects = ROOT.getProjects(); for (IProject project : workspaceProjects) { RepositoryMapping mapping = RepositoryMapping.getMapping(project); if (mapping != null && mapping.getRepository() == repo) projects.add(project); } } /** * @return instance of repository that should be synchronized */ public Repository getRepository() { return repo; } /** * @return synchronize source rev name */ public RevCommit getSrcRevCommit() { return srcRev; } /** * @return synchronize destination rev name */ public RevCommit getDstRevCommit() { return dstRev; } /** * @return list of project's that are connected with this repository */ public Set<IProject> getProjects() { return Collections.unmodifiableSet(projects); } /** * @param file * @return <true> if given {@link File} is contained by this repository */ public boolean contains(File file) { return file.getAbsoluteFile().toString().startsWith(repoParentPath); } /** * @return <code>true</code> if local changes should be included in * comparison */ public boolean shouldIncludeLocal() { return includeLocal; } /** * @return common ancestor commit */ public RevCommit getCommonAncestorRev() { return commonAncestorRev; } }
false
true
public GitSynchronizeData(Repository repository, String srcRev, String dstRev, boolean includeLocal) throws IOException { isNotNull(repository); isNotNull(srcRev); isNotNull(dstRev); repo = repository; ObjectWalk ow = new ObjectWalk(repo); if (!srcRev.isEmpty()) this.srcRev = ow.parseCommit(repo.resolve(srcRev)); else this.srcRev = null; if (!dstRev.isEmpty()) this.dstRev = ow.parseCommit(repo.resolve(dstRev)); else this.dstRev = null; if (this.dstRev != null || this.srcRev != null) this.commonAncestorRev = getCommonAncestor(repo, this.srcRev, this.dstRev); else this.commonAncestorRev = null; this.includeLocal = includeLocal; repoParentPath = repo.getDirectory().getParentFile().getAbsolutePath(); projects = new HashSet<IProject>(); final IProject[] workspaceProjects = ROOT.getProjects(); for (IProject project : workspaceProjects) { RepositoryMapping mapping = RepositoryMapping.getMapping(project); if (mapping != null && mapping.getRepository() == repo) projects.add(project); } }
public GitSynchronizeData(Repository repository, String srcRev, String dstRev, boolean includeLocal) throws IOException { isNotNull(repository); isNotNull(srcRev); isNotNull(dstRev); repo = repository; ObjectWalk ow = new ObjectWalk(repo); if (srcRev.length() > 0) this.srcRev = ow.parseCommit(repo.resolve(srcRev)); else this.srcRev = null; if (dstRev.length() > 0) this.dstRev = ow.parseCommit(repo.resolve(dstRev)); else this.dstRev = null; if (this.dstRev != null || this.srcRev != null) this.commonAncestorRev = getCommonAncestor(repo, this.srcRev, this.dstRev); else this.commonAncestorRev = null; this.includeLocal = includeLocal; repoParentPath = repo.getDirectory().getParentFile().getAbsolutePath(); projects = new HashSet<IProject>(); final IProject[] workspaceProjects = ROOT.getProjects(); for (IProject project : workspaceProjects) { RepositoryMapping mapping = RepositoryMapping.getMapping(project); if (mapping != null && mapping.getRepository() == repo) projects.add(project); } }
diff --git a/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/StatusController.java b/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/StatusController.java index 64a9d29..488403f 100644 --- a/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/StatusController.java +++ b/omod/src/main/java/org/openmrs/module/iqchartimport/web/controller/StatusController.java @@ -1,89 +1,89 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.iqchartimport.web.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.module.iqchartimport.EntityBuilder; import org.openmrs.module.iqchartimport.Utils; import org.openmrs.module.iqchartimport.task.ImportIssue; import org.openmrs.module.iqchartimport.task.TaskEngine; import org.openmrs.module.iqchartimport.task.ImportTask; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Import status AJAX controller */ @Controller("iqChartImportStatusController") @RequestMapping("/module/iqchartimport/status") public class StatusController { protected static final Log log = LogFactory.getLog(StatusController.class); @RequestMapping(method = RequestMethod.GET) public void getProgress(HttpServletRequest request, HttpServletResponse response) throws IOException { Utils.checkSuperUser(); ImportTask task = TaskEngine.getCurrentTask(); StringBuilder json = new StringBuilder(); if (task != null) { EntityBuilder builder = task.getEntityBuilder(); String completed = task.isCompleted() ? "true" : "false"; String exception; if (task.getException() != null) { String clazz = "'" + task.getException().getClass().getName() + "'"; - String message = (task.getException().getMessage() != null) ? ("'" + task.getException().getMessage() + "'") : "null"; + String message = (task.getException().getMessage() != null) ? ("'" + task.getException().getMessage().replace("'", "\\'") + "'") : "null"; exception = "{ clazz: " + clazz + ", message: " + message + " }"; } else exception = "null"; json.append("{\n"); json.append(" task: {\n"); json.append(" completed: " + completed + ",\n"); json.append(" exception: " + exception + ",\n"); json.append(" progress: " + task.getProgress() + ",\n"); json.append(" timeTaken: " + task.getTimeTaken() + ",\n"); json.append(" importedPatients: " + task.getImportedPatients() + ",\n"); json.append(" importedEncounters: " + task.getImportedEncounters() + ",\n"); json.append(" importedObservations: " + task.getImportedObservations() + ",\n"); json.append(" importedOrders: " + task.getImportedOrders() + ",\n"); json.append(" cache: { hitCount: " + builder.getCache().getHitCount() + ", missCount: " + builder.getCache().getMissCount() + " },\n"); json.append(" issues: [\n"); for (ImportIssue issue : task.getIssues()) { json.append(" { patientId: " + issue.getPatient().getPatientId() + ", message: \"" + issue.getMessage() + "\" },\n"); } json.append(" ]\n"); json.append(" }\n"); json.append("}"); } else json.append("{ task: null, issues: null }"); response.setContentType("application/json"); response.getWriter().write(json.toString()); } }
true
true
public void getProgress(HttpServletRequest request, HttpServletResponse response) throws IOException { Utils.checkSuperUser(); ImportTask task = TaskEngine.getCurrentTask(); StringBuilder json = new StringBuilder(); if (task != null) { EntityBuilder builder = task.getEntityBuilder(); String completed = task.isCompleted() ? "true" : "false"; String exception; if (task.getException() != null) { String clazz = "'" + task.getException().getClass().getName() + "'"; String message = (task.getException().getMessage() != null) ? ("'" + task.getException().getMessage() + "'") : "null"; exception = "{ clazz: " + clazz + ", message: " + message + " }"; } else exception = "null"; json.append("{\n"); json.append(" task: {\n"); json.append(" completed: " + completed + ",\n"); json.append(" exception: " + exception + ",\n"); json.append(" progress: " + task.getProgress() + ",\n"); json.append(" timeTaken: " + task.getTimeTaken() + ",\n"); json.append(" importedPatients: " + task.getImportedPatients() + ",\n"); json.append(" importedEncounters: " + task.getImportedEncounters() + ",\n"); json.append(" importedObservations: " + task.getImportedObservations() + ",\n"); json.append(" importedOrders: " + task.getImportedOrders() + ",\n"); json.append(" cache: { hitCount: " + builder.getCache().getHitCount() + ", missCount: " + builder.getCache().getMissCount() + " },\n"); json.append(" issues: [\n"); for (ImportIssue issue : task.getIssues()) { json.append(" { patientId: " + issue.getPatient().getPatientId() + ", message: \"" + issue.getMessage() + "\" },\n"); } json.append(" ]\n"); json.append(" }\n"); json.append("}"); } else json.append("{ task: null, issues: null }"); response.setContentType("application/json"); response.getWriter().write(json.toString()); }
public void getProgress(HttpServletRequest request, HttpServletResponse response) throws IOException { Utils.checkSuperUser(); ImportTask task = TaskEngine.getCurrentTask(); StringBuilder json = new StringBuilder(); if (task != null) { EntityBuilder builder = task.getEntityBuilder(); String completed = task.isCompleted() ? "true" : "false"; String exception; if (task.getException() != null) { String clazz = "'" + task.getException().getClass().getName() + "'"; String message = (task.getException().getMessage() != null) ? ("'" + task.getException().getMessage().replace("'", "\\'") + "'") : "null"; exception = "{ clazz: " + clazz + ", message: " + message + " }"; } else exception = "null"; json.append("{\n"); json.append(" task: {\n"); json.append(" completed: " + completed + ",\n"); json.append(" exception: " + exception + ",\n"); json.append(" progress: " + task.getProgress() + ",\n"); json.append(" timeTaken: " + task.getTimeTaken() + ",\n"); json.append(" importedPatients: " + task.getImportedPatients() + ",\n"); json.append(" importedEncounters: " + task.getImportedEncounters() + ",\n"); json.append(" importedObservations: " + task.getImportedObservations() + ",\n"); json.append(" importedOrders: " + task.getImportedOrders() + ",\n"); json.append(" cache: { hitCount: " + builder.getCache().getHitCount() + ", missCount: " + builder.getCache().getMissCount() + " },\n"); json.append(" issues: [\n"); for (ImportIssue issue : task.getIssues()) { json.append(" { patientId: " + issue.getPatient().getPatientId() + ", message: \"" + issue.getMessage() + "\" },\n"); } json.append(" ]\n"); json.append(" }\n"); json.append("}"); } else json.append("{ task: null, issues: null }"); response.setContentType("application/json"); response.getWriter().write(json.toString()); }
diff --git a/de.lmu.ifi.dbs.knowing.debug.core/src/de/lmu/ifi/dbs/knowing/debug/core/launching/DPULaunchConfigurationDelegate.java b/de.lmu.ifi.dbs.knowing.debug.core/src/de/lmu/ifi/dbs/knowing/debug/core/launching/DPULaunchConfigurationDelegate.java index 9933be22..7068a4ba 100644 --- a/de.lmu.ifi.dbs.knowing.debug.core/src/de/lmu/ifi/dbs/knowing/debug/core/launching/DPULaunchConfigurationDelegate.java +++ b/de.lmu.ifi.dbs.knowing.debug.core/src/de/lmu/ifi/dbs/knowing/debug/core/launching/DPULaunchConfigurationDelegate.java @@ -1,172 +1,173 @@ /* *\ ** |¯¯|/¯¯/|¯¯ \|¯¯| /¯¯/\¯¯\'|¯¯| |¯¯||¯¯||¯¯ \|¯¯| /¯¯/|__| ** ** | '| '( | '|\ '|| | | '|| '|/\| '|| '|| '|\ '|| | ,---, ** ** |__|\__\|__|'|__| \__\/__/'|__,/\'__||__||__|'|__| \__\/__| ** ** ** ** Knowing Framework ** ** Apache License - http://www.apache.org/licenses/ ** ** LMU Munich - Database Systems Group ** ** http://www.dbs.ifi.lmu.de/ ** \* */ package de.lmu.ifi.dbs.knowing.debug.core.launching; import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.pde.launching.OSGiLaunchConfigurationDelegate; import org.eclipse.sapphire.modeling.ResourceStoreException; import org.eclipse.sapphire.modeling.xml.RootXmlResource; import org.eclipse.sapphire.modeling.xml.XmlResourceStore; import org.eclipse.sapphire.workspace.WorkspaceFileResourceStore; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import de.lmu.ifi.dbs.knowing.core.model.IDataProcessingUnit; import de.lmu.ifi.dbs.knowing.core.model.IParameter; import de.lmu.ifi.dbs.knowing.debug.core.internal.Activator; import de.lmu.ifi.dbs.knowing.launcher.LaunchConfiguration; /** * * @author Nepomuk Seiler * */ public class DPULaunchConfigurationDelegate extends OSGiLaunchConfigurationDelegate { /* ======================================= */ /* = Constants are only internally used = */ /* = see knowing.launcher/reference.conf = */ /* ======================================= */ public static final String DPU_PROJECT = "knowing.dpu.project"; /** Relative to project */ public static final String DPU_PATH = "knowing.dpu.path"; public static final String DPU_EXECUTION_PATH = "knowing.dpu.executionpath"; public static final String DPU_PARAMETERS = "knowing.dpu.parameters"; private static final String VM_ARGUMENTS = "org.eclipse.jdt.launching.VM_ARGUMENTS"; @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { monitor.subTask("Loading Data Processing Unit"); String projectName = configuration.getAttribute(DPU_PROJECT, (String) null); String relativePath = configuration.getAttribute(DPU_PATH, (String) null); String execPath = configuration.getAttribute(DPU_EXECUTION_PATH, System.getProperty("user.home")); String vmArguments = configuration.getAttribute(VM_ARGUMENTS, (String) null); IFile dpuFile = findDPUFile(projectName, relativePath); if(!dpuFile.exists()) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "DPU doesn't exist! " + dpuFile.getLocationURI())); IDataProcessingUnit dpu = null; try { dpu = loadDPU(dpuFile); } catch (ResourceStoreException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error loading DPU!", e)); } Path executionPath = Paths.get(execPath); if(!Files.isDirectory(executionPath)) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Execution path is a file!")); if(!Files.isWritable(executionPath)) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Execution path is not writeable!")); Map<String, Object> confMap = new HashMap<>(); confMap.put("dpu.name", dpu.getName().getContent()); confMap.put("dpu.uri", dpuFile.getLocationURI().toString()); confMap.put("dpu.executionpath", execPath); - //TODO Cannot put a Config into the confMap. Will generate a list. - Map<String, String> parameterMap = parameterMap(configuration.getAttribute(DPU_PARAMETERS, Collections.EMPTY_LIST)); - confMap.put("dpu.parameters", ConfigFactory.parseMap(parameterMap)); + List<IParameter> parameters = stringToParameters(configuration.getAttribute(DPU_PARAMETERS, Collections.EMPTY_LIST)); + for (IParameter p : parameters) { + confMap.put("dpu.parameters." + p.getKey().getContent(), p.getValue().getContent()); + } Config config = ConfigFactory.parseMap(confMap); Path applicationConf = executionPath.resolve("application.conf"); try(Writer w = Files.newBufferedWriter(applicationConf, Charset.defaultCharset())) { w.write(config.root().render()); } catch (IOException e) { e.printStackTrace(); } String arguments = vmArguments + " -D" + LaunchConfiguration.APPLICATION_CONF() + "=" + applicationConf.toUri(); ILaunchConfigurationWorkingCopy copy = configuration.copy("WithDPUSettings"); copy.setAttribute(VM_ARGUMENTS, arguments); super.launch(copy, mode, launch, monitor); } public static IFile findDPUFile(String projectName, String relativePath) { if(projectName == null || relativePath == null) return null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(projectName); return (IFile) project.findMember(relativePath); } public static IDataProcessingUnit loadDPU(IFile dpuFile) throws ResourceStoreException { XmlResourceStore store = new XmlResourceStore(new WorkspaceFileResourceStore(dpuFile)); RootXmlResource resource = new RootXmlResource(store); IDataProcessingUnit original = IDataProcessingUnit.TYPE.instantiate(resource); IDataProcessingUnit dpu = IDataProcessingUnit.TYPE.instantiate(); dpu.copy(original); return dpu; } public static List<IParameter> stringToParameters(List<String> tokens) { if(tokens == null || tokens.isEmpty()) return new ArrayList<>(0); ArrayList<IParameter> result = new ArrayList<>(tokens.size()); for (String token : tokens) { IParameter p = IParameter.TYPE.instantiate(); String[] keyValue = token.split("="); p.setKey(keyValue[0]); p.setValue(keyValue[1]); result.add(p); } return result; } public static List<String> parametersToString(List<IParameter> parameters) { if(parameters == null || parameters.isEmpty()) return new ArrayList<>(0); ArrayList<String> result = new ArrayList<>(parameters.size()); for (IParameter p : parameters) { result.add(p.getKey().getContent() + "=" + p.getValue().getContent()); } return result; } public static Map<String, String> parameterMap(List<String> tokens) { Map<String, String> results = new HashMap<>(); for (String token : tokens) { String[] keyValue = token.split("="); results.put(keyValue[0], keyValue[1]); } return results; } }
true
true
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { monitor.subTask("Loading Data Processing Unit"); String projectName = configuration.getAttribute(DPU_PROJECT, (String) null); String relativePath = configuration.getAttribute(DPU_PATH, (String) null); String execPath = configuration.getAttribute(DPU_EXECUTION_PATH, System.getProperty("user.home")); String vmArguments = configuration.getAttribute(VM_ARGUMENTS, (String) null); IFile dpuFile = findDPUFile(projectName, relativePath); if(!dpuFile.exists()) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "DPU doesn't exist! " + dpuFile.getLocationURI())); IDataProcessingUnit dpu = null; try { dpu = loadDPU(dpuFile); } catch (ResourceStoreException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error loading DPU!", e)); } Path executionPath = Paths.get(execPath); if(!Files.isDirectory(executionPath)) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Execution path is a file!")); if(!Files.isWritable(executionPath)) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Execution path is not writeable!")); Map<String, Object> confMap = new HashMap<>(); confMap.put("dpu.name", dpu.getName().getContent()); confMap.put("dpu.uri", dpuFile.getLocationURI().toString()); confMap.put("dpu.executionpath", execPath); //TODO Cannot put a Config into the confMap. Will generate a list. Map<String, String> parameterMap = parameterMap(configuration.getAttribute(DPU_PARAMETERS, Collections.EMPTY_LIST)); confMap.put("dpu.parameters", ConfigFactory.parseMap(parameterMap)); Config config = ConfigFactory.parseMap(confMap); Path applicationConf = executionPath.resolve("application.conf"); try(Writer w = Files.newBufferedWriter(applicationConf, Charset.defaultCharset())) { w.write(config.root().render()); } catch (IOException e) { e.printStackTrace(); } String arguments = vmArguments + " -D" + LaunchConfiguration.APPLICATION_CONF() + "=" + applicationConf.toUri(); ILaunchConfigurationWorkingCopy copy = configuration.copy("WithDPUSettings"); copy.setAttribute(VM_ARGUMENTS, arguments); super.launch(copy, mode, launch, monitor); }
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { monitor.subTask("Loading Data Processing Unit"); String projectName = configuration.getAttribute(DPU_PROJECT, (String) null); String relativePath = configuration.getAttribute(DPU_PATH, (String) null); String execPath = configuration.getAttribute(DPU_EXECUTION_PATH, System.getProperty("user.home")); String vmArguments = configuration.getAttribute(VM_ARGUMENTS, (String) null); IFile dpuFile = findDPUFile(projectName, relativePath); if(!dpuFile.exists()) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "DPU doesn't exist! " + dpuFile.getLocationURI())); IDataProcessingUnit dpu = null; try { dpu = loadDPU(dpuFile); } catch (ResourceStoreException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error loading DPU!", e)); } Path executionPath = Paths.get(execPath); if(!Files.isDirectory(executionPath)) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Execution path is a file!")); if(!Files.isWritable(executionPath)) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Execution path is not writeable!")); Map<String, Object> confMap = new HashMap<>(); confMap.put("dpu.name", dpu.getName().getContent()); confMap.put("dpu.uri", dpuFile.getLocationURI().toString()); confMap.put("dpu.executionpath", execPath); List<IParameter> parameters = stringToParameters(configuration.getAttribute(DPU_PARAMETERS, Collections.EMPTY_LIST)); for (IParameter p : parameters) { confMap.put("dpu.parameters." + p.getKey().getContent(), p.getValue().getContent()); } Config config = ConfigFactory.parseMap(confMap); Path applicationConf = executionPath.resolve("application.conf"); try(Writer w = Files.newBufferedWriter(applicationConf, Charset.defaultCharset())) { w.write(config.root().render()); } catch (IOException e) { e.printStackTrace(); } String arguments = vmArguments + " -D" + LaunchConfiguration.APPLICATION_CONF() + "=" + applicationConf.toUri(); ILaunchConfigurationWorkingCopy copy = configuration.copy("WithDPUSettings"); copy.setAttribute(VM_ARGUMENTS, arguments); super.launch(copy, mode, launch, monitor); }
diff --git a/source/de/anomic/plasma/plasmaCrawlWorker.java b/source/de/anomic/plasma/plasmaCrawlWorker.java index 6e7d5d844..3efe0ad8c 100644 --- a/source/de/anomic/plasma/plasmaCrawlWorker.java +++ b/source/de/anomic/plasma/plasmaCrawlWorker.java @@ -1,534 +1,535 @@ //plasmaCrawlWorker.java //------------------------ //part of YaCy //(C) by Michael Peter Christen; [email protected] //first published on http://www.anomic.de //Frankfurt, Germany, 2004 // //last major change: $LastChangedDate$ by $LastChangedBy$ //Revision: $LastChangedRevision$ // //This program is free software; you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation; either version 2 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //Using this software in any meaning (reading, learning, copying, compiling, //running) means that you agree that the Author(s) is (are) not responsible //for cost, loss of data or any harm that may be caused directly or indirectly //by usage of this softare or this documentation. The usage of this software //is on your own risk. The installation and usage (starting/running) of this //software may allow other people or application to access your computer and //any attached devices and is highly dependent on the configuration of the //software which must be done by the user of the software; the author(s) is //(are) also not responsible for proper configuration and usage of the //software, even if provoked by documentation provided together with //the software. // //Any changes to this file according to the GPL as documented in the file //gpl.txt aside this file in the shipment you received can be done to the //lines that follows this copyright notice here, but changes must not be //done inside the copyright notive above. A re-distribution must contain //the intact and unchanged copyright notice. //Contributions and changes to the program code must be marked as such. package de.anomic.plasma; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.NoRouteToHostException; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.Date; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import de.anomic.http.httpHeader; import de.anomic.http.httpc; import de.anomic.http.httpdProxyHandler; import de.anomic.server.serverCore; import de.anomic.server.serverDate; import de.anomic.server.logging.serverLog; import de.anomic.server.logging.serverMiniLogFormatter; import de.anomic.tools.bitfield; import de.anomic.yacy.yacyCore; public final class plasmaCrawlWorker extends Thread { private static final int DEFAULT_CRAWLING_RETRY_COUNT = 5; private static final String threadBaseName = "CrawlerWorker"; private final CrawlerPool myPool; private final plasmaHTCache cacheManager; private final int socketTimeout; private final boolean remoteProxyUse; private final String remoteProxyHost; private final int remoteProxyPort; private final serverLog log; public plasmaCrawlLoaderMessage theMsg; private URL url; private String name; private String referer; private String initiator; private int depth; private long startdate; private plasmaCrawlProfile.entry profile; //private String error; private boolean running = false; private boolean stopped = false; private boolean done = false; private static boolean doCrawlerLogging = false; /** * Do logging configuration for special proxy access log file */ // static { // try { // Logger crawlerLogger = Logger.getLogger("CRAWLER.access"); // crawlerLogger.setUseParentHandlers(false); // FileHandler txtLog = new FileHandler("log/crawlerAccess%u%g.log",1024*1024, 20, true); // txtLog.setFormatter(new serverMiniLogFormatter()); // txtLog.setLevel(Level.FINEST); // crawlerLogger.addHandler(txtLog); // // doAccessLogging = true; // } catch (Exception e) { // System.err.println("PROXY: Unable to configure proxy access logging."); // } // } public plasmaCrawlWorker( ThreadGroup theTG, CrawlerPool thePool, plasmaHTCache cacheManager, int socketTimeout, boolean remoteProxyUse, String remoteProxyHost, int remoteProxyPort, serverLog log) { super(theTG,threadBaseName + "_inPool"); this.myPool = thePool; this.cacheManager = cacheManager; this.socketTimeout = socketTimeout; this.remoteProxyUse = remoteProxyUse; this.remoteProxyHost = remoteProxyHost; this.remoteProxyPort = remoteProxyPort; this.log = log; } public synchronized void execute(plasmaCrawlLoaderMessage theMsg) { this.theMsg = theMsg; this.url = theMsg.url; this.name = theMsg.name; this.referer = theMsg.referer; this.initiator = theMsg.initiator; this.depth = theMsg.depth; this.profile = theMsg.profile; this.startdate = System.currentTimeMillis(); //this.error = null; this.done = false; if (!this.running) { // this.setDaemon(true); this.start(); } else { this.notifyAll(); } } public void reset() { this.theMsg = null; this.url = null; this.referer = null; this.initiator = null; this.depth = 0; this.startdate = 0; this.profile = null; //this.error = null; } public void run() { this.running = true; // The thread keeps running. while (!this.stopped && !Thread.interrupted()) { if (this.done) { // We are waiting for a task now. synchronized (this) { try { this.wait(); //Wait until we get a request to process. } catch (InterruptedException e) { this.stopped = true; // log.error("", e); } } } else { //There is a task....let us execute it. try { execute(); } catch (Exception e) { // log.error("", e); } finally { reset(); if (!this.stopped && !this.isInterrupted()) { try { this.myPool.returnObject(this); this.setName(this.threadBaseName + "_inPool"); } catch (Exception e1) { log.logSevere("pool error", e1); } } } } } } public void execute() throws IOException { try { this.setName(this.threadBaseName + "_" + this.url); load(this.url, this.name, this.referer, this.initiator, this.depth, this.profile, this.socketTimeout, this.remoteProxyHost, this.remoteProxyPort, this.remoteProxyUse, this.cacheManager, this.log); } catch (IOException e) { //throw e; } finally { this.done = true; } } public void setStopped(boolean stopped) { this.stopped = stopped; } public boolean isRunning() { return this.running; } public void close() { if (this.isAlive()) { try { // trying to close all still open httpc-Sockets first int closedSockets = httpc.closeOpenSockets(this); if (closedSockets > 0) { this.log.logInfo(closedSockets + " HTTP-client sockets of thread '" + this.getName() + "' closed."); } } catch (Exception e) {} } } public static void load( URL url, String name, String referer, String initiator, int depth, plasmaCrawlProfile.entry profile, int socketTimeout, String remoteProxyHost, int remoteProxyPort, boolean remoteProxyUse, plasmaHTCache cacheManager, serverLog log ) throws IOException { load(url, name, referer, initiator, depth, profile, socketTimeout, remoteProxyHost, remoteProxyPort, remoteProxyUse, cacheManager, log, DEFAULT_CRAWLING_RETRY_COUNT, true ); } private static void load( URL url, String name, String referer, String initiator, int depth, plasmaCrawlProfile.entry profile, int socketTimeout, String remoteProxyHost, int remoteProxyPort, boolean remoteProxyUse, plasmaHTCache cacheManager, serverLog log, int crawlingRetryCount, boolean useContentEncodingGzip ) throws IOException { if (url == null) return; // if the recrawling limit was exceeded we stop crawling now if (crawlingRetryCount <= 0) return; // getting a reference to the plasmaSwitchboard plasmaSwitchboard sb = plasmaCrawlLoader.switchboard; Date requestDate = new Date(); // remember the time... String host = url.getHost(); String path = url.getPath(); int port = url.getPort(); boolean ssl = url.getProtocol().equals("https"); if (port < 0) port = (ssl) ? 443 : 80; // check if url is in blacklist String hostlow = host.toLowerCase(); if (plasmaSwitchboard.urlBlacklist.isListed(hostlow, path)) { log.logInfo("CRAWLER Rejecting URL '" + url.toString() + "'. URL is in blacklist."); sb.urlPool.errorURL.newEntry(url, referer,initiator, yacyCore.seedDB.mySeed.hash, name, "denied_(url_in_blacklist)", new bitfield(plasmaURL.urlFlagLength), true); + return; } // TODO: resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // set referrer; in some case advertise a little bit: referer = (referer == null) ? "" : referer.trim(); if (referer.length() == 0) referer = "http://www.yacy.net/yacy/"; // take a file from the net httpc remote = null; try { // create a request header httpHeader requestHeader = new httpHeader(); requestHeader.put(httpHeader.USER_AGENT, httpdProxyHandler.userAgent); requestHeader.put(httpHeader.REFERER, referer); requestHeader.put(httpHeader.ACCEPT_LANGUAGE, sb.getConfig("crawler.acceptLanguage","en-us,en;q=0.5")); requestHeader.put(httpHeader.ACCEPT_CHARSET, sb.getConfig("crawler.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7")); if (useContentEncodingGzip) requestHeader.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate"); //System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG // open the connection remote = (remoteProxyUse) ? httpc.getInstance(host, port, socketTimeout, ssl, remoteProxyHost, remoteProxyPort) : httpc.getInstance(host, port, socketTimeout, ssl); // specifying if content encoding is allowed remote.setAllowContentEncoding(useContentEncodingGzip); // send request httpc.response res = remote.GET(path, requestHeader); if (res.status.startsWith("200") || res.status.startsWith("203")) { // the transfer is ok long contentLength = res.responseHeader.contentLength(); // reserve cache entry plasmaHTCache.Entry htCache = cacheManager.newEntry(requestDate, depth, url, name, requestHeader, res.status, res.responseHeader, initiator, profile); // request has been placed and result has been returned. work off response File cacheFile = cacheManager.getCachePath(url); try { String error = null; if ((!(plasmaParser.supportedMimeTypesContains(res.responseHeader.mime()))) && (!(plasmaParser.supportedFileExt(url)))) { // if the response has not the right file type then reject file remote.close(); log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString()); } else { if (cacheFile.isFile()) { cacheManager.deleteFile(url); } // we write the new cache entry to file system directly cacheFile.getParentFile().mkdirs(); FileOutputStream fos = null; try { fos = new FileOutputStream(cacheFile); res.writeContent(fos); // superfluous write to array htCache.cacheArray = null; cacheManager.writeFileAnnouncement(cacheFile); //htCache.cacheArray = res.writeContent(fos); // writes in cacheArray and cache file } finally { if (fos!=null)try{fos.close();}catch(Exception e){} } } // enQueue new entry with response header if (profile != null) { cacheManager.push(htCache); } } catch (SocketException e) { // this may happen if the client suddenly closes its connection // maybe the user has stopped loading // in that case, we are not responsible and just forget it // but we clean the cache also, since it may be only partial // and most possible corrupted if (cacheFile.exists()) cacheFile.delete(); log.logSevere("CRAWLER LOADER ERROR1: with URL=" + url.toString() + ": " + e.toString()); } } else if (res.status.startsWith("30")) { if (crawlingRetryCount > 0) { if (res.responseHeader.containsKey(httpHeader.LOCATION)) { // getting redirection URL String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION); redirectionUrlString = redirectionUrlString.trim(); // normalizing URL redirectionUrlString = plasmaParser.urlNormalform(redirectionUrlString); // generating the new URL object URL redirectionUrl = new URL(url, redirectionUrlString); // returning the used httpc httpc.returnInstance(remote); remote = null; // restart crawling with new url log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + url.toString() + "\nRedirecting request to: " + redirectionUrl); // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown."); return; } // generating url hash String urlhash = plasmaURL.urlHash(redirectionUrl); // removing url from loader queue plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash); // retry crawling with new url load(redirectionUrl, name, referer, initiator, depth, profile, socketTimeout, remoteProxyHost, remoteProxyPort, remoteProxyUse, cacheManager, log, --crawlingRetryCount, useContentEncodingGzip ); } } else { log.logInfo("Redirection counter exceeded for URL " + url.toString() + ". Processing aborted."); } }else { // if the response has not the right response type then reject file log.logInfo("REJECTED WRONG STATUS TYPE '" + res.status + "' for URL " + url.toString()); // not processed any further } if (remote != null) remote.close(); } catch (Exception e) { boolean retryCrawling = false; String errorMsg = e.getMessage(); if (e instanceof MalformedURLException) { log.logWarning("CRAWLER Malformed URL '" + url.toString() + "' detected. "); } else if (e instanceof NoRouteToHostException) { log.logWarning("CRAWLER No route to host found while trying to crawl URL '" + url.toString() + "'."); } else if ((e instanceof UnknownHostException) || ((errorMsg != null) && (errorMsg.indexOf("unknown host") >= 0))) { log.logWarning("CRAWLER Unknown host in URL '" + url.toString() + "'. " + "Referer URL: " + ((referer == null) ?"Unknown":referer)); } else if (e instanceof java.net.BindException) { log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Corrupt GZIP trailer") >= 0)) { log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() + "'. Retrying request without using gzip content encoding."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Read timed out") >= 0)) { log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("connect timed out") >= 0)) { log.logWarning("CRAWLER Timeout while trying to connect to '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Connection timed out") >= 0)) { log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Connection refused") >= 0)) { log.logWarning("CRAWLER Connection refused while trying to connect to '" + url.toString() + "'."); } else if ((errorMsg != null) && (errorMsg.indexOf("There is not enough space on the disk") >= 0)) { log.logSevere("CRAWLER Not enough space on the disk detected while crawling '" + url.toString() + "'. " + "Pausing crawlers. "); plasmaCrawlLoader.switchboard.pauseCrawling(); } else if ((errorMsg != null) && (errorMsg.indexOf("Network is unreachable") >=0)) { log.logSevere("CRAWLER Network is unreachable while trying to crawl URL '" + url.toString() + "'. "); } else if ((errorMsg != null) && (errorMsg.indexOf("No trusted certificate found")>= 0)) { log.logSevere("CRAWLER No trusted certificate found for URL '" + url.toString() + "'. "); } else { log.logSevere("CRAWLER Unexpected Error with URL '" + url.toString() + "': " + e.toString(),e); } if (retryCrawling) { // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown."); return; } // returning the used httpc httpc.returnInstance(remote); remote = null; // setting the retry counter to 1 if (crawlingRetryCount > 2) crawlingRetryCount = 2; // retry crawling load(url, name, referer, initiator, depth, profile, socketTimeout, remoteProxyHost, remoteProxyPort, remoteProxyUse, cacheManager, log, --crawlingRetryCount, false ); } } finally { if (remote != null) httpc.returnInstance(remote); } } }
true
true
private static void load( URL url, String name, String referer, String initiator, int depth, plasmaCrawlProfile.entry profile, int socketTimeout, String remoteProxyHost, int remoteProxyPort, boolean remoteProxyUse, plasmaHTCache cacheManager, serverLog log, int crawlingRetryCount, boolean useContentEncodingGzip ) throws IOException { if (url == null) return; // if the recrawling limit was exceeded we stop crawling now if (crawlingRetryCount <= 0) return; // getting a reference to the plasmaSwitchboard plasmaSwitchboard sb = plasmaCrawlLoader.switchboard; Date requestDate = new Date(); // remember the time... String host = url.getHost(); String path = url.getPath(); int port = url.getPort(); boolean ssl = url.getProtocol().equals("https"); if (port < 0) port = (ssl) ? 443 : 80; // check if url is in blacklist String hostlow = host.toLowerCase(); if (plasmaSwitchboard.urlBlacklist.isListed(hostlow, path)) { log.logInfo("CRAWLER Rejecting URL '" + url.toString() + "'. URL is in blacklist."); sb.urlPool.errorURL.newEntry(url, referer,initiator, yacyCore.seedDB.mySeed.hash, name, "denied_(url_in_blacklist)", new bitfield(plasmaURL.urlFlagLength), true); } // TODO: resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // set referrer; in some case advertise a little bit: referer = (referer == null) ? "" : referer.trim(); if (referer.length() == 0) referer = "http://www.yacy.net/yacy/"; // take a file from the net httpc remote = null; try { // create a request header httpHeader requestHeader = new httpHeader(); requestHeader.put(httpHeader.USER_AGENT, httpdProxyHandler.userAgent); requestHeader.put(httpHeader.REFERER, referer); requestHeader.put(httpHeader.ACCEPT_LANGUAGE, sb.getConfig("crawler.acceptLanguage","en-us,en;q=0.5")); requestHeader.put(httpHeader.ACCEPT_CHARSET, sb.getConfig("crawler.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7")); if (useContentEncodingGzip) requestHeader.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate"); //System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG // open the connection remote = (remoteProxyUse) ? httpc.getInstance(host, port, socketTimeout, ssl, remoteProxyHost, remoteProxyPort) : httpc.getInstance(host, port, socketTimeout, ssl); // specifying if content encoding is allowed remote.setAllowContentEncoding(useContentEncodingGzip); // send request httpc.response res = remote.GET(path, requestHeader); if (res.status.startsWith("200") || res.status.startsWith("203")) { // the transfer is ok long contentLength = res.responseHeader.contentLength(); // reserve cache entry plasmaHTCache.Entry htCache = cacheManager.newEntry(requestDate, depth, url, name, requestHeader, res.status, res.responseHeader, initiator, profile); // request has been placed and result has been returned. work off response File cacheFile = cacheManager.getCachePath(url); try { String error = null; if ((!(plasmaParser.supportedMimeTypesContains(res.responseHeader.mime()))) && (!(plasmaParser.supportedFileExt(url)))) { // if the response has not the right file type then reject file remote.close(); log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString()); } else { if (cacheFile.isFile()) { cacheManager.deleteFile(url); } // we write the new cache entry to file system directly cacheFile.getParentFile().mkdirs(); FileOutputStream fos = null; try { fos = new FileOutputStream(cacheFile); res.writeContent(fos); // superfluous write to array htCache.cacheArray = null; cacheManager.writeFileAnnouncement(cacheFile); //htCache.cacheArray = res.writeContent(fos); // writes in cacheArray and cache file } finally { if (fos!=null)try{fos.close();}catch(Exception e){} } } // enQueue new entry with response header if (profile != null) { cacheManager.push(htCache); } } catch (SocketException e) { // this may happen if the client suddenly closes its connection // maybe the user has stopped loading // in that case, we are not responsible and just forget it // but we clean the cache also, since it may be only partial // and most possible corrupted if (cacheFile.exists()) cacheFile.delete(); log.logSevere("CRAWLER LOADER ERROR1: with URL=" + url.toString() + ": " + e.toString()); } } else if (res.status.startsWith("30")) { if (crawlingRetryCount > 0) { if (res.responseHeader.containsKey(httpHeader.LOCATION)) { // getting redirection URL String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION); redirectionUrlString = redirectionUrlString.trim(); // normalizing URL redirectionUrlString = plasmaParser.urlNormalform(redirectionUrlString); // generating the new URL object URL redirectionUrl = new URL(url, redirectionUrlString); // returning the used httpc httpc.returnInstance(remote); remote = null; // restart crawling with new url log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + url.toString() + "\nRedirecting request to: " + redirectionUrl); // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown."); return; } // generating url hash String urlhash = plasmaURL.urlHash(redirectionUrl); // removing url from loader queue plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash); // retry crawling with new url load(redirectionUrl, name, referer, initiator, depth, profile, socketTimeout, remoteProxyHost, remoteProxyPort, remoteProxyUse, cacheManager, log, --crawlingRetryCount, useContentEncodingGzip ); } } else { log.logInfo("Redirection counter exceeded for URL " + url.toString() + ". Processing aborted."); } }else { // if the response has not the right response type then reject file log.logInfo("REJECTED WRONG STATUS TYPE '" + res.status + "' for URL " + url.toString()); // not processed any further } if (remote != null) remote.close(); } catch (Exception e) { boolean retryCrawling = false; String errorMsg = e.getMessage(); if (e instanceof MalformedURLException) { log.logWarning("CRAWLER Malformed URL '" + url.toString() + "' detected. "); } else if (e instanceof NoRouteToHostException) { log.logWarning("CRAWLER No route to host found while trying to crawl URL '" + url.toString() + "'."); } else if ((e instanceof UnknownHostException) || ((errorMsg != null) && (errorMsg.indexOf("unknown host") >= 0))) { log.logWarning("CRAWLER Unknown host in URL '" + url.toString() + "'. " + "Referer URL: " + ((referer == null) ?"Unknown":referer)); } else if (e instanceof java.net.BindException) { log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Corrupt GZIP trailer") >= 0)) { log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() + "'. Retrying request without using gzip content encoding."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Read timed out") >= 0)) { log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("connect timed out") >= 0)) { log.logWarning("CRAWLER Timeout while trying to connect to '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Connection timed out") >= 0)) { log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Connection refused") >= 0)) { log.logWarning("CRAWLER Connection refused while trying to connect to '" + url.toString() + "'."); } else if ((errorMsg != null) && (errorMsg.indexOf("There is not enough space on the disk") >= 0)) { log.logSevere("CRAWLER Not enough space on the disk detected while crawling '" + url.toString() + "'. " + "Pausing crawlers. "); plasmaCrawlLoader.switchboard.pauseCrawling(); } else if ((errorMsg != null) && (errorMsg.indexOf("Network is unreachable") >=0)) { log.logSevere("CRAWLER Network is unreachable while trying to crawl URL '" + url.toString() + "'. "); } else if ((errorMsg != null) && (errorMsg.indexOf("No trusted certificate found")>= 0)) { log.logSevere("CRAWLER No trusted certificate found for URL '" + url.toString() + "'. "); } else { log.logSevere("CRAWLER Unexpected Error with URL '" + url.toString() + "': " + e.toString(),e); } if (retryCrawling) { // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown."); return; } // returning the used httpc httpc.returnInstance(remote); remote = null; // setting the retry counter to 1 if (crawlingRetryCount > 2) crawlingRetryCount = 2; // retry crawling load(url, name, referer, initiator, depth, profile, socketTimeout, remoteProxyHost, remoteProxyPort, remoteProxyUse, cacheManager, log, --crawlingRetryCount, false ); } } finally { if (remote != null) httpc.returnInstance(remote); } }
private static void load( URL url, String name, String referer, String initiator, int depth, plasmaCrawlProfile.entry profile, int socketTimeout, String remoteProxyHost, int remoteProxyPort, boolean remoteProxyUse, plasmaHTCache cacheManager, serverLog log, int crawlingRetryCount, boolean useContentEncodingGzip ) throws IOException { if (url == null) return; // if the recrawling limit was exceeded we stop crawling now if (crawlingRetryCount <= 0) return; // getting a reference to the plasmaSwitchboard plasmaSwitchboard sb = plasmaCrawlLoader.switchboard; Date requestDate = new Date(); // remember the time... String host = url.getHost(); String path = url.getPath(); int port = url.getPort(); boolean ssl = url.getProtocol().equals("https"); if (port < 0) port = (ssl) ? 443 : 80; // check if url is in blacklist String hostlow = host.toLowerCase(); if (plasmaSwitchboard.urlBlacklist.isListed(hostlow, path)) { log.logInfo("CRAWLER Rejecting URL '" + url.toString() + "'. URL is in blacklist."); sb.urlPool.errorURL.newEntry(url, referer,initiator, yacyCore.seedDB.mySeed.hash, name, "denied_(url_in_blacklist)", new bitfield(plasmaURL.urlFlagLength), true); return; } // TODO: resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // set referrer; in some case advertise a little bit: referer = (referer == null) ? "" : referer.trim(); if (referer.length() == 0) referer = "http://www.yacy.net/yacy/"; // take a file from the net httpc remote = null; try { // create a request header httpHeader requestHeader = new httpHeader(); requestHeader.put(httpHeader.USER_AGENT, httpdProxyHandler.userAgent); requestHeader.put(httpHeader.REFERER, referer); requestHeader.put(httpHeader.ACCEPT_LANGUAGE, sb.getConfig("crawler.acceptLanguage","en-us,en;q=0.5")); requestHeader.put(httpHeader.ACCEPT_CHARSET, sb.getConfig("crawler.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7")); if (useContentEncodingGzip) requestHeader.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate"); //System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG // open the connection remote = (remoteProxyUse) ? httpc.getInstance(host, port, socketTimeout, ssl, remoteProxyHost, remoteProxyPort) : httpc.getInstance(host, port, socketTimeout, ssl); // specifying if content encoding is allowed remote.setAllowContentEncoding(useContentEncodingGzip); // send request httpc.response res = remote.GET(path, requestHeader); if (res.status.startsWith("200") || res.status.startsWith("203")) { // the transfer is ok long contentLength = res.responseHeader.contentLength(); // reserve cache entry plasmaHTCache.Entry htCache = cacheManager.newEntry(requestDate, depth, url, name, requestHeader, res.status, res.responseHeader, initiator, profile); // request has been placed and result has been returned. work off response File cacheFile = cacheManager.getCachePath(url); try { String error = null; if ((!(plasmaParser.supportedMimeTypesContains(res.responseHeader.mime()))) && (!(plasmaParser.supportedFileExt(url)))) { // if the response has not the right file type then reject file remote.close(); log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString()); } else { if (cacheFile.isFile()) { cacheManager.deleteFile(url); } // we write the new cache entry to file system directly cacheFile.getParentFile().mkdirs(); FileOutputStream fos = null; try { fos = new FileOutputStream(cacheFile); res.writeContent(fos); // superfluous write to array htCache.cacheArray = null; cacheManager.writeFileAnnouncement(cacheFile); //htCache.cacheArray = res.writeContent(fos); // writes in cacheArray and cache file } finally { if (fos!=null)try{fos.close();}catch(Exception e){} } } // enQueue new entry with response header if (profile != null) { cacheManager.push(htCache); } } catch (SocketException e) { // this may happen if the client suddenly closes its connection // maybe the user has stopped loading // in that case, we are not responsible and just forget it // but we clean the cache also, since it may be only partial // and most possible corrupted if (cacheFile.exists()) cacheFile.delete(); log.logSevere("CRAWLER LOADER ERROR1: with URL=" + url.toString() + ": " + e.toString()); } } else if (res.status.startsWith("30")) { if (crawlingRetryCount > 0) { if (res.responseHeader.containsKey(httpHeader.LOCATION)) { // getting redirection URL String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION); redirectionUrlString = redirectionUrlString.trim(); // normalizing URL redirectionUrlString = plasmaParser.urlNormalform(redirectionUrlString); // generating the new URL object URL redirectionUrl = new URL(url, redirectionUrlString); // returning the used httpc httpc.returnInstance(remote); remote = null; // restart crawling with new url log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + url.toString() + "\nRedirecting request to: " + redirectionUrl); // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown."); return; } // generating url hash String urlhash = plasmaURL.urlHash(redirectionUrl); // removing url from loader queue plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash); // retry crawling with new url load(redirectionUrl, name, referer, initiator, depth, profile, socketTimeout, remoteProxyHost, remoteProxyPort, remoteProxyUse, cacheManager, log, --crawlingRetryCount, useContentEncodingGzip ); } } else { log.logInfo("Redirection counter exceeded for URL " + url.toString() + ". Processing aborted."); } }else { // if the response has not the right response type then reject file log.logInfo("REJECTED WRONG STATUS TYPE '" + res.status + "' for URL " + url.toString()); // not processed any further } if (remote != null) remote.close(); } catch (Exception e) { boolean retryCrawling = false; String errorMsg = e.getMessage(); if (e instanceof MalformedURLException) { log.logWarning("CRAWLER Malformed URL '" + url.toString() + "' detected. "); } else if (e instanceof NoRouteToHostException) { log.logWarning("CRAWLER No route to host found while trying to crawl URL '" + url.toString() + "'."); } else if ((e instanceof UnknownHostException) || ((errorMsg != null) && (errorMsg.indexOf("unknown host") >= 0))) { log.logWarning("CRAWLER Unknown host in URL '" + url.toString() + "'. " + "Referer URL: " + ((referer == null) ?"Unknown":referer)); } else if (e instanceof java.net.BindException) { log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Corrupt GZIP trailer") >= 0)) { log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() + "'. Retrying request without using gzip content encoding."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Read timed out") >= 0)) { log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("connect timed out") >= 0)) { log.logWarning("CRAWLER Timeout while trying to connect to '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Connection timed out") >= 0)) { log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() + "'. Retrying request."); retryCrawling = true; } else if ((errorMsg != null) && (errorMsg.indexOf("Connection refused") >= 0)) { log.logWarning("CRAWLER Connection refused while trying to connect to '" + url.toString() + "'."); } else if ((errorMsg != null) && (errorMsg.indexOf("There is not enough space on the disk") >= 0)) { log.logSevere("CRAWLER Not enough space on the disk detected while crawling '" + url.toString() + "'. " + "Pausing crawlers. "); plasmaCrawlLoader.switchboard.pauseCrawling(); } else if ((errorMsg != null) && (errorMsg.indexOf("Network is unreachable") >=0)) { log.logSevere("CRAWLER Network is unreachable while trying to crawl URL '" + url.toString() + "'. "); } else if ((errorMsg != null) && (errorMsg.indexOf("No trusted certificate found")>= 0)) { log.logSevere("CRAWLER No trusted certificate found for URL '" + url.toString() + "'. "); } else { log.logSevere("CRAWLER Unexpected Error with URL '" + url.toString() + "': " + e.toString(),e); } if (retryCrawling) { // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { log.logSevere("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown."); return; } // returning the used httpc httpc.returnInstance(remote); remote = null; // setting the retry counter to 1 if (crawlingRetryCount > 2) crawlingRetryCount = 2; // retry crawling load(url, name, referer, initiator, depth, profile, socketTimeout, remoteProxyHost, remoteProxyPort, remoteProxyUse, cacheManager, log, --crawlingRetryCount, false ); } } finally { if (remote != null) httpc.returnInstance(remote); } }
diff --git a/easysoa-distribution/easysoa-distribution-startup-monitor/src/main/java/org/easysoa/startup/StartupMonitor.java b/easysoa-distribution/easysoa-distribution-startup-monitor/src/main/java/org/easysoa/startup/StartupMonitor.java index f3ccd3ae..a11d9a43 100644 --- a/easysoa-distribution/easysoa-distribution-startup-monitor/src/main/java/org/easysoa/startup/StartupMonitor.java +++ b/easysoa-distribution/easysoa-distribution-startup-monitor/src/main/java/org/easysoa/startup/StartupMonitor.java @@ -1,104 +1,104 @@ package org.easysoa.startup; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import org.easysoa.EasySOAConstants; /** * * @author mkalam-alami * */ public class StartupMonitor { private static final String EASYSOA_URL = "http://localhost:8083"; private static final int STARTUP_TIMEOUT = 60000; public static void main(String[] args) { // Port list Map<Integer, String> portsToCheck = new ConcurrentHashMap<Integer, String>(); portsToCheck.put(EasySOAConstants.WEB_PORT, "EasySOA home"); portsToCheck.put(EasySOAConstants.NUXEO_PORT, "Service registry"); portsToCheck.put(EasySOAConstants.HTTP_DISCOVERY_PROXY_PORT, "HTTP Monitoring proxy"); portsToCheck.put(EasySOAConstants.HTML_FORM_GENERATOR_PORT, "UI Scaffolding proxy"); portsToCheck.put(EasySOAConstants.PAF_SERVICES_PORT, "Pure Air Flowers demo"); portsToCheck.put(EasySOAConstants.TRIP_SERVICES_PORT, "Smart Travel demo"); portsToCheck.put(EasySOAConstants.TRIP_BACKUP_SERVICES_PORT, "Smart Travel demo (services backup)"); // Start-up list print("* Servers to be started"); for (Entry<Integer, String> entry : portsToCheck.entrySet()) { print(entry.getValue() + " (port " + entry.getKey() + ")"); } // Check loop long initialTime = System.currentTimeMillis(); int timeout = 200; int up = 0, total = portsToCheck.size(); print("\n* Checking servers..."); while (!portsToCheck.isEmpty() && System.currentTimeMillis() - initialTime < STARTUP_TIMEOUT) { for (Integer port : portsToCheck.keySet()) { if (isAvailable("http://localhost:" + port, timeout)) { String label = portsToCheck.remove(port); up++; print(label + " is up... (" + up + "/" + total + ")"); } if (System.currentTimeMillis() - initialTime > STARTUP_TIMEOUT) { break; } } timeout += 500; } // Feedback if (portsToCheck.isEmpty()) { print("Everything is ready!"); } else { print("...Something must be wrong, but I'll make you browse to the EasySOA home anyway."); } // Open browser try { - URI easysoaUri = new URI("EASYSOA_URL"); + URI easysoaUri = new URI(EASYSOA_URL); Desktop.getDesktop().browse(easysoaUri); } catch (Exception e) { print("\nPlease browse to '" + EASYSOA_URL +"' to get started with the demo."); } } /** * * @param url * @param timeout in ms * @return */ public static boolean isAvailable(String url, int timeout) { try { URLConnection connection = new URL(url).openConnection(); connection.setConnectTimeout(timeout); connection.connect(); } catch (IOException e) { return false; } return true; } public static void print(String string) { System.out.println(string); } }
true
true
public static void main(String[] args) { // Port list Map<Integer, String> portsToCheck = new ConcurrentHashMap<Integer, String>(); portsToCheck.put(EasySOAConstants.WEB_PORT, "EasySOA home"); portsToCheck.put(EasySOAConstants.NUXEO_PORT, "Service registry"); portsToCheck.put(EasySOAConstants.HTTP_DISCOVERY_PROXY_PORT, "HTTP Monitoring proxy"); portsToCheck.put(EasySOAConstants.HTML_FORM_GENERATOR_PORT, "UI Scaffolding proxy"); portsToCheck.put(EasySOAConstants.PAF_SERVICES_PORT, "Pure Air Flowers demo"); portsToCheck.put(EasySOAConstants.TRIP_SERVICES_PORT, "Smart Travel demo"); portsToCheck.put(EasySOAConstants.TRIP_BACKUP_SERVICES_PORT, "Smart Travel demo (services backup)"); // Start-up list print("* Servers to be started"); for (Entry<Integer, String> entry : portsToCheck.entrySet()) { print(entry.getValue() + " (port " + entry.getKey() + ")"); } // Check loop long initialTime = System.currentTimeMillis(); int timeout = 200; int up = 0, total = portsToCheck.size(); print("\n* Checking servers..."); while (!portsToCheck.isEmpty() && System.currentTimeMillis() - initialTime < STARTUP_TIMEOUT) { for (Integer port : portsToCheck.keySet()) { if (isAvailable("http://localhost:" + port, timeout)) { String label = portsToCheck.remove(port); up++; print(label + " is up... (" + up + "/" + total + ")"); } if (System.currentTimeMillis() - initialTime > STARTUP_TIMEOUT) { break; } } timeout += 500; } // Feedback if (portsToCheck.isEmpty()) { print("Everything is ready!"); } else { print("...Something must be wrong, but I'll make you browse to the EasySOA home anyway."); } // Open browser try { URI easysoaUri = new URI("EASYSOA_URL"); Desktop.getDesktop().browse(easysoaUri); } catch (Exception e) { print("\nPlease browse to '" + EASYSOA_URL +"' to get started with the demo."); } }
public static void main(String[] args) { // Port list Map<Integer, String> portsToCheck = new ConcurrentHashMap<Integer, String>(); portsToCheck.put(EasySOAConstants.WEB_PORT, "EasySOA home"); portsToCheck.put(EasySOAConstants.NUXEO_PORT, "Service registry"); portsToCheck.put(EasySOAConstants.HTTP_DISCOVERY_PROXY_PORT, "HTTP Monitoring proxy"); portsToCheck.put(EasySOAConstants.HTML_FORM_GENERATOR_PORT, "UI Scaffolding proxy"); portsToCheck.put(EasySOAConstants.PAF_SERVICES_PORT, "Pure Air Flowers demo"); portsToCheck.put(EasySOAConstants.TRIP_SERVICES_PORT, "Smart Travel demo"); portsToCheck.put(EasySOAConstants.TRIP_BACKUP_SERVICES_PORT, "Smart Travel demo (services backup)"); // Start-up list print("* Servers to be started"); for (Entry<Integer, String> entry : portsToCheck.entrySet()) { print(entry.getValue() + " (port " + entry.getKey() + ")"); } // Check loop long initialTime = System.currentTimeMillis(); int timeout = 200; int up = 0, total = portsToCheck.size(); print("\n* Checking servers..."); while (!portsToCheck.isEmpty() && System.currentTimeMillis() - initialTime < STARTUP_TIMEOUT) { for (Integer port : portsToCheck.keySet()) { if (isAvailable("http://localhost:" + port, timeout)) { String label = portsToCheck.remove(port); up++; print(label + " is up... (" + up + "/" + total + ")"); } if (System.currentTimeMillis() - initialTime > STARTUP_TIMEOUT) { break; } } timeout += 500; } // Feedback if (portsToCheck.isEmpty()) { print("Everything is ready!"); } else { print("...Something must be wrong, but I'll make you browse to the EasySOA home anyway."); } // Open browser try { URI easysoaUri = new URI(EASYSOA_URL); Desktop.getDesktop().browse(easysoaUri); } catch (Exception e) { print("\nPlease browse to '" + EASYSOA_URL +"' to get started with the demo."); } }
diff --git a/src/org/apache/xerces/dom/DeferredDocumentImpl.java b/src/org/apache/xerces/dom/DeferredDocumentImpl.java index d82d519a..27f23549 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/src/slug/soc/game/TerrianGenerator.java b/src/slug/soc/game/TerrianGenerator.java index 85395b7..4b89156 100644 --- a/src/slug/soc/game/TerrianGenerator.java +++ b/src/slug/soc/game/TerrianGenerator.java @@ -1,268 +1,268 @@ package slug.soc.game; import java.awt.Color; import java.awt.Point; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import slug.soc.game.gameObjects.*; public class TerrianGenerator { private TerrainObject[] temperateTerrain = { new TerrainObjectWater(), new TerrainObjectGrassPlain(), new TerrainObjectGrassPlain(), new TerrainObjectForest(), new TerrainObjectGrassPlain(), new TerrainObjectGrassHill() }; private TerrainObject[] articTerrain = { new TerrainObjectWater(), new TerrainObjectSnowPlain(), new TerrainObjectSnowHill() }; private ArrayList<Point> rivers = new ArrayList<Point>(); public TerrianGenerator(){ } private TerrainObject[][] constructTerrainMap(int[][] intMap){ TerrainObject[][] map = new TerrainObject[intMap.length][intMap.length]; for(int y = 0; y < map.length; y++){ for(int x = 0; x < map.length; x++){ if(y < map.length/101 || y > map.length - (map.length/101)){ try { if(intMap[y][x] < articTerrain.length){ map[y][x] = articTerrain[intMap[y][x]].getClass().newInstance(); } else{ map[y][x] = articTerrain[articTerrain.length - (1 + RandomProvider.getInstance().nextInt(2))].getClass().newInstance(); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } else{ try { if(intMap[y][x] < temperateTerrain.length){ map[y][x] = temperateTerrain[intMap[y][x]].getClass().newInstance(); } else{ if(intMap[y][x] > 10){ map[y][x] = new TerrainObjectMountain(); } else{ map[y][x] = temperateTerrain[temperateTerrain.length - (1 + RandomProvider.getInstance().nextInt(3))].getClass().newInstance(); } } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } for(Point p : rivers){ map[(int) p.getY()][(int) p.getX()] = new TerrainObjectRiverHorizontal(); } generateBiomes(map); return map; } private int[][] simulateAnt(int[][] intMap, int cx, int cy, int l){ for(int i = 0, c = l;i < c ; i++){ if(cy < 0 || cx < 0 || cy > intMap.length -1 || cx > intMap.length -1){ cy = RandomProvider.getInstance().nextInt(intMap.length); cx = RandomProvider.getInstance().nextInt(intMap.length); } intMap[cy][cx] += 1; cy += RandomProvider.getInstance().nextInt(3) - 1; cx += RandomProvider.getInstance().nextInt(3) - 1; } return intMap; } private int[][] generateIntMap(int w, int h){ int[][] intMap = new int[w][h]; for(int y = 0; y < intMap.length; y++){ for(int x = 0; x < intMap.length; x++){ intMap[y][x] = 0; } } return intMap; } private TerrainObject[][] generateBiomes(TerrainObject[][] map){ for(int y = 0; y < map.length; y++){ for(int x = 0; x < map.length; x++){ if(!map[y][x].isBiome() && (!(map[y][x] instanceof TerrainObjectWater)) ){ createBiome(x, y, map,WordGenerator.getInstance().getRandomAdjective()); } } } return map; } private void smoothTerrain(int[][] intMap){ for(int i = 0; i < 2; i++){ for(int y = 0; y < intMap.length; y++){ for(int x = 0; x < intMap.length; x++){ if(intMap[y][x] == 0){ if(x > 0 && y > 0 && x < intMap.length - 1 && y < intMap.length - 1){ if((intMap[y + 1][x] > 0 && intMap[y -1][x] > 0) || (intMap[y][x + 1] > 0 && intMap[y][x - 1] > 0)){ intMap[y][x] = 1; } } } } } } } private void generateRivers(int[][] intMap){ int sY = 39, sX = 60; int[][] hMap = new int[intMap.length][intMap.length]; for(int y = 0; y < intMap.length; y++){ for(int x = 0; x < intMap.length; x++){ hMap[y][x] = intMap[y][x]; if(intMap[y][x] > temperateTerrain.length){ hMap[y][x] = temperateTerrain.length -1; } } } ArrayList<Point> river = new ArrayList<Point>(); river.add(new Point(sX, sY)); int i = hMap[sY][sX]; int cY = sY, cX = sX; boolean finishedBuilding = false; while(finishedBuilding == false){ ArrayList<Point> possiblePath = new ArrayList<Point>(); - if(hMap[cY + 1][cX] <= hMap[cY][cX] && cY + 1 < hMap.length){ + if(hMap[cY + 1][cX] <= hMap[cY][cX] && cY + 1 < hMap.length - 1){ possiblePath.add(new Point(cX , cY + 1)); } if(hMap[cY - 1][cX] <= hMap[cY][cX] && cY - 1 > -1){ possiblePath.add(new Point(cX, cY - 1)); } - if(hMap[cY][cX + 1] <= hMap[cY][cX] && cX + 1 < hMap.length){ + if(hMap[cY][cX + 1] <= hMap[cY][cX] && cX + 1 < hMap.length - 1){ possiblePath.add(new Point(cX + 1, cY)); } if(hMap[cY][cX - 1] <= hMap[cY][cX] && cX - 1 > -1){ possiblePath.add(new Point(cX - 1, cY)); } if(possiblePath.isEmpty()){ finishedBuilding = true; } ArrayList<Point> updatedPath = new ArrayList<Point>(); for(Point p : possiblePath){ for(Point rp : river){ if(!p.equals(rp)){ updatedPath.add(p); } } } possiblePath = updatedPath; if(possiblePath.isEmpty()){ finishedBuilding = true; } if(!finishedBuilding){ int r = RandomProvider.getInstance().nextInt(possiblePath.size()); river.add(possiblePath.get(r)); cY = (int) possiblePath.get(r).getY(); cX = (int) possiblePath.get(r).getX(); } } rivers = river; } private void createBiome(int x, int y, TerrainObject[][] map, String n){ map[y][x].setBiomeString(n + " "); if(y + 1 < map.length -1){ if(!map[y + 1][x].isBiome() && map[y + 1][x].getClass() == (map[y][x]).getClass()){ createBiome(x, y + 1, map, n); } } if(y - 1 > 0){ if(!map[y - 1][x].isBiome() && (map[y - 1][x].getClass() == (map[y][x]).getClass())){ createBiome(x, y - 1, map, n); } } if(x + 1 < map.length -1){ if(!map[y][x + 1].isBiome() && map[y][x + 1].getClass() == (map[y][x]).getClass()){ createBiome(x + 1, y, map, n); } } if(x - 1 > 0){ if(!map[y][x - 1].isBiome() && map[y][x - 1].getClass() == (map[y][x]).getClass()){ createBiome(x - 1, y, map, n); } } } public TerrainObject[][] testGenerateMapAnt(int w, int h){ int[][] intMap = generateIntMap(w, h); intMap = simulateAnt(intMap, intMap.length/2, intMap.length/2, 1001); return constructTerrainMap(intMap); } public TerrainObject[][] testGenerateMapMultiCont(int w, int h){ int[][] intMap = generateIntMap(w, h); for(int n = 0, cy = RandomProvider.getInstance().nextInt(intMap.length), cx = RandomProvider.getInstance().nextInt(intMap.length); n < 4; n++){ intMap = simulateAnt(intMap, cx, cy, 2001); } smoothTerrain(intMap); int avg = 0; int q = 0; int c = 0; for(int y = 0; y < intMap.length; y++){ for(int x = 0;x < intMap.length; x++){ //calcualte average tile value. if(intMap[y][x] > 0){ avg += intMap[y][x]; c++; if(intMap[y][x] > q){ q = intMap[y][x]; } } } } System.out.println(avg/c); System.out.println(q); generateRivers(intMap); System.out.println("finish river gen"); return constructTerrainMap(intMap); } }
false
true
private void generateRivers(int[][] intMap){ int sY = 39, sX = 60; int[][] hMap = new int[intMap.length][intMap.length]; for(int y = 0; y < intMap.length; y++){ for(int x = 0; x < intMap.length; x++){ hMap[y][x] = intMap[y][x]; if(intMap[y][x] > temperateTerrain.length){ hMap[y][x] = temperateTerrain.length -1; } } } ArrayList<Point> river = new ArrayList<Point>(); river.add(new Point(sX, sY)); int i = hMap[sY][sX]; int cY = sY, cX = sX; boolean finishedBuilding = false; while(finishedBuilding == false){ ArrayList<Point> possiblePath = new ArrayList<Point>(); if(hMap[cY + 1][cX] <= hMap[cY][cX] && cY + 1 < hMap.length){ possiblePath.add(new Point(cX , cY + 1)); } if(hMap[cY - 1][cX] <= hMap[cY][cX] && cY - 1 > -1){ possiblePath.add(new Point(cX, cY - 1)); } if(hMap[cY][cX + 1] <= hMap[cY][cX] && cX + 1 < hMap.length){ possiblePath.add(new Point(cX + 1, cY)); } if(hMap[cY][cX - 1] <= hMap[cY][cX] && cX - 1 > -1){ possiblePath.add(new Point(cX - 1, cY)); } if(possiblePath.isEmpty()){ finishedBuilding = true; } ArrayList<Point> updatedPath = new ArrayList<Point>(); for(Point p : possiblePath){ for(Point rp : river){ if(!p.equals(rp)){ updatedPath.add(p); } } } possiblePath = updatedPath; if(possiblePath.isEmpty()){ finishedBuilding = true; } if(!finishedBuilding){ int r = RandomProvider.getInstance().nextInt(possiblePath.size()); river.add(possiblePath.get(r)); cY = (int) possiblePath.get(r).getY(); cX = (int) possiblePath.get(r).getX(); } } rivers = river; }
private void generateRivers(int[][] intMap){ int sY = 39, sX = 60; int[][] hMap = new int[intMap.length][intMap.length]; for(int y = 0; y < intMap.length; y++){ for(int x = 0; x < intMap.length; x++){ hMap[y][x] = intMap[y][x]; if(intMap[y][x] > temperateTerrain.length){ hMap[y][x] = temperateTerrain.length -1; } } } ArrayList<Point> river = new ArrayList<Point>(); river.add(new Point(sX, sY)); int i = hMap[sY][sX]; int cY = sY, cX = sX; boolean finishedBuilding = false; while(finishedBuilding == false){ ArrayList<Point> possiblePath = new ArrayList<Point>(); if(hMap[cY + 1][cX] <= hMap[cY][cX] && cY + 1 < hMap.length - 1){ possiblePath.add(new Point(cX , cY + 1)); } if(hMap[cY - 1][cX] <= hMap[cY][cX] && cY - 1 > -1){ possiblePath.add(new Point(cX, cY - 1)); } if(hMap[cY][cX + 1] <= hMap[cY][cX] && cX + 1 < hMap.length - 1){ possiblePath.add(new Point(cX + 1, cY)); } if(hMap[cY][cX - 1] <= hMap[cY][cX] && cX - 1 > -1){ possiblePath.add(new Point(cX - 1, cY)); } if(possiblePath.isEmpty()){ finishedBuilding = true; } ArrayList<Point> updatedPath = new ArrayList<Point>(); for(Point p : possiblePath){ for(Point rp : river){ if(!p.equals(rp)){ updatedPath.add(p); } } } possiblePath = updatedPath; if(possiblePath.isEmpty()){ finishedBuilding = true; } if(!finishedBuilding){ int r = RandomProvider.getInstance().nextInt(possiblePath.size()); river.add(possiblePath.get(r)); cY = (int) possiblePath.get(r).getY(); cX = (int) possiblePath.get(r).getX(); } } rivers = river; }
diff --git a/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/EvolutionMonitor.java b/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/EvolutionMonitor.java index a31b1a4..4216edc 100644 --- a/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/EvolutionMonitor.java +++ b/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/EvolutionMonitor.java @@ -1,208 +1,208 @@ // ============================================================================ // Copyright 2006-2009 Daniel W. Dyer // // 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.uncommons.watchmaker.swing.evolutionmonitor; import java.awt.BorderLayout; import java.awt.Window; import java.lang.reflect.InvocationTargetException; import java.util.LinkedList; import java.util.List; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.StandardChartTheme; import org.uncommons.watchmaker.framework.EvolutionObserver; import org.uncommons.watchmaker.framework.PopulationData; import org.uncommons.watchmaker.framework.interactive.Renderer; import org.uncommons.watchmaker.swing.ObjectSwingRenderer; /** * The Evolution Monitor is a component that can be attached to an * {@link org.uncommons.watchmaker.framework.EvolutionEngine} to provide * real-time information (in a Swing GUI) about the current state of the * evolution. * @param <T> The type of the evolved entities monitored by this component. * @author Daniel Dyer */ public class EvolutionMonitor<T> implements EvolutionObserver<T> { private final List<EvolutionObserver<? super T>> views = new LinkedList<EvolutionObserver<? super T>>(); private JComponent monitorComponent; private Window window = null; /** * Creates an EvolutionMonitor with a single panel that graphs the fitness scores * of the population from generation to generation. */ public EvolutionMonitor() { this(new ObjectSwingRenderer()); } /** * Creates an EvolutionMonitor with a second panel that displays a graphical * representation of the fittest candidate in the population. * @param renderer Renders a candidate solution as a JComponent. */ public EvolutionMonitor(final Renderer<? super T, JComponent> renderer) { if (SwingUtilities.isEventDispatchThread()) { init(renderer); } else { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { init(renderer); } }); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - throw new InstantiationError(ex.getMessage()); + throw new IllegalStateException(ex); } catch (InvocationTargetException ex) { - throw new InstantiationError(ex.getMessage()); + throw new IllegalStateException(ex); } } } private void init(Renderer<? super T, JComponent> renderer) { // Make sure all JFreeChart charts are created with the legacy theme // (grey surround and white data area). ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme()); JTabbedPane tabs = new JTabbedPane(); monitorComponent = new JPanel(new BorderLayout()); monitorComponent.add(tabs, BorderLayout.CENTER); FittestCandidateView<T> candidateView = new FittestCandidateView<T>(renderer); tabs.add("Fittest Individual", candidateView); views.add(candidateView); PopulationFitnessView fitnessView = new PopulationFitnessView(); tabs.add("Population Fitness", fitnessView); views.add(fitnessView); JVMView jvmView = new JVMView(); tabs.add("JVM Memory", jvmView); StatusBar statusBar = new StatusBar(); monitorComponent.add(statusBar, BorderLayout.SOUTH); views.add(statusBar); } /** * {@inheritDoc} */ public void populationUpdate(PopulationData<? extends T> populationData) { for (EvolutionObserver<? super T> view : views) { view.populationUpdate(populationData); } } public JComponent getGUIComponent() { return monitorComponent; } /** * Displays the evolution monitor component in a new {@link JFrame}. There is no * need to make sure this method is invoked from the Event Dispatch Thread, the * method itself ensures that the window is created and displayed from the EDT. * @param title The title for the new frame. * @param exitOnClose Whether the JVM should exit when the frame is closed. Useful * if this is the only application window. */ public void showInFrame(final String title, final boolean exitOnClose) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(exitOnClose ? JFrame.EXIT_ON_CLOSE : JFrame.DISPOSE_ON_CLOSE); showWindow(frame); } }); } /** * Displays the evolution monitor component in a new {@link JDialog}. There is no * need to make sure this method is invoked from the Event Dispatch Thread, the * method itself ensures that the window is created and displayed from the EDT. * @param owner The owning frame for the new dialog. * @param title The title for the new dialog. * @param modal Whether the */ public void showInDialog(final JFrame owner, final String title, final boolean modal) { SwingUtilities.invokeLater(new Runnable() { public void run() { JDialog dialog = new JDialog(owner, title, modal); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); showWindow(dialog); } }); } /** * Helper method for showing the evolution monitor in a frame or dialog. * @param newWindow The frame or dialog used to show the evolution monitor. */ private void showWindow(Window newWindow) { if (window != null) { window.remove(getGUIComponent()); window.setVisible(false); window.dispose(); window = null; } newWindow.add(getGUIComponent(), BorderLayout.CENTER); newWindow.pack(); newWindow.setVisible(true); this.window = newWindow; } }
false
true
public EvolutionMonitor(final Renderer<? super T, JComponent> renderer) { if (SwingUtilities.isEventDispatchThread()) { init(renderer); } else { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { init(renderer); } }); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new InstantiationError(ex.getMessage()); } catch (InvocationTargetException ex) { throw new InstantiationError(ex.getMessage()); } } }
public EvolutionMonitor(final Renderer<? super T, JComponent> renderer) { if (SwingUtilities.isEventDispatchThread()) { init(renderer); } else { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { init(renderer); } }); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } catch (InvocationTargetException ex) { throw new IllegalStateException(ex); } } }
diff --git a/quercus/src/main/java/com/caucho/quercus/env/Post.java b/quercus/src/main/java/com/caucho/quercus/env/Post.java index 70c3420..036e75a 100644 --- a/quercus/src/main/java/com/caucho/quercus/env/Post.java +++ b/quercus/src/main/java/com/caucho/quercus/env/Post.java @@ -1,743 +1,743 @@ /* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.env; import com.caucho.quercus.lib.string.StringModule; import com.caucho.quercus.lib.string.StringUtility; import com.caucho.quercus.lib.file.FileModule; import com.caucho.util.L10N; import com.caucho.vfs.FilePath; import com.caucho.vfs.MultipartStream; import com.caucho.vfs.Path; import com.caucho.vfs.ReadStream; import com.caucho.vfs.VfsStream; import com.caucho.vfs.WriteStream; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Map; /** * Handling of POST requests. */ public class Post { private static final L10N L = new L10N(Post.class); private static StringValue MAX_FILE_SIZE = new ConstStringValue("MAX_FILE_SIZE"); private static StringValue MAX_FILE_SIZE_U = new UnicodeBuilderValue("MAX_FILE_SIZE"); static void fillPost(Env env, ArrayValue postArray, ArrayValue files, HttpServletRequest request, boolean addSlashesToValues, boolean isAllowUploads) { InputStream is = null; try { String encoding = request.getCharacterEncoding(); String contentType = request.getHeader("Content-Type"); is = request.getInputStream(); fillPost(env, postArray, files, is, contentType, encoding, Integer.MAX_VALUE, addSlashesToValues, isAllowUploads); if (postArray.getSize() == 0) { // needs to be last or else this function will consume the inputstream putRequestMap(env, postArray, files, request, addSlashesToValues, isAllowUploads); } } catch (IOException e) { env.warning(e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { } } } static void fillPost(Env env, ArrayValue postArray, ArrayValue files, InputStream is, String contentType, String encoding, int contentLength, boolean addSlashesToValues, boolean isAllowUploads) { long maxPostSize = env.getIniBytes("post_max_size", 0); try { if (encoding == null) { encoding = env.getHttpInputEncoding(); } if (contentType != null && contentType.startsWith("multipart/form-data")) { String boundary = getBoundary(contentType); ReadStream rs = new ReadStream(new VfsStream(is, null)); if (boundary == null) { env.warning(L.l("multipart/form-data POST is missing boundary")); return; } MultipartStream ms = new MultipartStream(rs, boundary); if (encoding != null) { ms.setEncoding(encoding); } readMultipartStream(env, ms, postArray, files, addSlashesToValues, isAllowUploads); rs.close(); if (rs.getLength() > maxPostSize) { env.warning(L.l("POST length of {0} exceeds max size of {1}", rs.getLength(), maxPostSize)); postArray.clear(); files.clear(); return; } } else { StringValue bb = env.createBinaryBuilder(); bb.appendReadAll(is, Integer.MAX_VALUE); if (bb.length() > maxPostSize) { env.warning(L.l("POST length of {0} exceeds max size of {1}", bb.length(), maxPostSize)); return; } env.setInputData(bb); if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")) { StringUtility.parseStr(env, bb, postArray, false, encoding); } } } catch (IOException e) { env.warning(e); } finally { } } private static void readMultipartStream(Env env, MultipartStream ms, ArrayValue postArray, ArrayValue files, boolean addSlashesToValues, boolean isAllowUploads) throws IOException { ReadStream is; while ((is = ms.openRead()) != null) { String attr = (String) ms.getAttribute("content-disposition"); if (attr == null || !attr.startsWith("form-data")) { // TODO: is this an error? continue; } String name = getAttribute(attr, "name", addSlashesToValues); String filename = getAttribute(attr, "filename", addSlashesToValues); if (filename != null) { int slashIndex = filename.lastIndexOf('/'); int slashIndex2 = filename.lastIndexOf('\\'); slashIndex = Math.max(slashIndex, slashIndex2); if (slashIndex >= 0) { filename = filename.substring(slashIndex + 1); } } int bracketIndex = -1; if (name != null) { bracketIndex = name.lastIndexOf(']'); } if (bracketIndex >= 0 && bracketIndex < name.length() - 1) { // php/085c } else if (filename == null) { - StringValue value = env.createStringBuilder(); + StringValue value = env.createBinaryBuilder(); value.appendReadAll(is, Integer.MAX_VALUE); if (name != null) { addFormValue(env, postArray, name, value, null, addSlashesToValues); } else { env.warning(L.l("file upload is missing name and filename")); } } else { if (!isAllowUploads) { continue; } String tmpName = ""; long tmpLength = 0; // A POST file upload with an empty string as the filename does not // create a temp file in the upload directory. if (filename.length() > 0) { Path tmpPath = env.getUploadDirectory().createTempFile("php", ".tmp"); env.addRemovePath(tmpPath); WriteStream os = tmpPath.openWrite(); try { os.writeStream(is); } finally { os.close(); } tmpName = tmpPath.getFullPath(); tmpLength = tmpPath.getLength(); } // php/0865 // // A header like "Content-Type: image/gif" indicates the mime type // for an uploaded file. String mimeType = getAttribute(attr, "mime-type", addSlashesToValues); if (mimeType == null) { mimeType = (String) ms.getAttribute("content-type"); // php/085f if (mimeType != null && mimeType.endsWith(";")) { mimeType = mimeType.substring(0, mimeType.length() - 1); } } // php/0864 // // mime type is empty string when no file is uploaded. if (filename.length() == 0) { mimeType = ""; } long maxFileSize = Long.MAX_VALUE; Value maxFileSizeV = postArray.get(MAX_FILE_SIZE); if (!maxFileSizeV.isNull()) { maxFileSize = maxFileSizeV.toLong(); } if (name != null) { addFormFile(env, files, name, filename, tmpName, mimeType, tmpLength, addSlashesToValues, maxFileSize); } else { addFormFile(env, files, filename, tmpName, mimeType, tmpLength, addSlashesToValues, maxFileSize); } } } } private static void addFormFile(Env env, ArrayValue files, String fileName, String tmpName, String mimeType, long fileLength, boolean addSlashesToValues, long maxFileSize) { ArrayValue entry = new ArrayValueImpl(); int error; // php/1667 long uploadMaxFilesize = env.getIniBytes("upload_max_filesize", 2 * 1024 * 1024); if (fileName.length() == 0) // php/0864 { error = FileModule.UPLOAD_ERR_NO_FILE; } else if (fileLength > uploadMaxFilesize) { error = FileModule.UPLOAD_ERR_INI_SIZE; } else if (fileLength > maxFileSize) { error = FileModule.UPLOAD_ERR_FORM_SIZE; } else { error = FileModule.UPLOAD_ERR_OK; } addFormValue(env, entry, "name", env.createString(fileName), null, addSlashesToValues); long size; if (error != FileModule.UPLOAD_ERR_INI_SIZE) { size = fileLength; } else { mimeType = ""; tmpName = ""; size = 0; } if (mimeType != null) { addFormValue(env, entry, "type", env.createString(mimeType), null, addSlashesToValues); entry.put("type", mimeType); } addFormValue(env, entry, "tmp_name", env.createString(tmpName), null, addSlashesToValues); addFormValue(env, entry, "error", LongValue.create(error), null, addSlashesToValues); addFormValue(env, entry, "size", LongValue.create(size), null, addSlashesToValues); addFormValue(env, files, null, entry, null, addSlashesToValues); } private static void addFormFile(Env env, ArrayValue files, String name, String fileName, String tmpName, String mimeType, long fileLength, boolean addSlashesToValues, long maxFileSize) { int p = name.indexOf('['); String index = ""; if (p >= 0) { index = name.substring(p); name = name.substring(0, p); } StringValue nameValue = env.createString(name); Value v = files.get(nameValue).toValue(); ArrayValue entry = null; if (v instanceof ArrayValue) { entry = (ArrayValue) v; } if (entry == null) { entry = new ArrayValueImpl(); files.put(nameValue, entry); } int error; // php/1667 long uploadMaxFilesize = env.getIniBytes("upload_max_filesize", 2 * 1024 * 1024); if (fileName.length() == 0) // php/0864 { error = FileModule.UPLOAD_ERR_NO_FILE; } else if (fileLength > uploadMaxFilesize) { error = FileModule.UPLOAD_ERR_INI_SIZE; } else if (fileLength > maxFileSize) { error = FileModule.UPLOAD_ERR_FORM_SIZE; } else { error = FileModule.UPLOAD_ERR_OK; } addFormValue(env, entry, "name" + index, env.createString(fileName), null, addSlashesToValues); long size; if (error == FileModule.UPLOAD_ERR_OK) { size = fileLength; } else { mimeType = ""; tmpName = ""; size = 0; } if (mimeType != null) { addFormValue(env, entry, "type" + index, env.createString(mimeType), null, addSlashesToValues); } addFormValue(env, entry, "tmp_name" + index, env.createString(tmpName), null, addSlashesToValues); addFormValue(env, entry, "error" + index, LongValue.create(error), null, addSlashesToValues); addFormValue(env, entry, "size" + index, LongValue.create(size), null, addSlashesToValues); addFormValue(env, files, name, entry, null, addSlashesToValues); } public static void addFormValue(Env env, ArrayValue array, String key, String[] formValueList, boolean addSlashesToValues) { // php/081b String formValue = formValueList[formValueList.length - 1]; Value value; if (formValue != null) { value = env.createString(formValue); } else { value = NullValue.NULL; } addFormValue(env, array, key, value, formValueList, addSlashesToValues); } public static void addFormValue(Env env, ArrayValue array, String key, Value formValue, String[] formValueList, boolean addSlashesToValues) { int p = -1; int q = -1; if (key != null) { p = key.indexOf('['); q = key.indexOf(']', p); } if (p >= 0 && p < q) { String index = key; Value keyValue; Value existingValue; if (p > 0) { key = key.substring(0, p); key = key.replaceAll("\\.", "_"); keyValue = env.createString(key); existingValue = array.get(keyValue); if (existingValue == null || !existingValue.isset()) { existingValue = new ArrayValueImpl(); array.put(keyValue, existingValue); } else if (!existingValue.isArray()) { //existing is overwritten // php/115g existingValue = new ArrayValueImpl(); array.put(keyValue, existingValue); } array = (ArrayValue) existingValue; } int p1; while ((p1 = index.indexOf('[', q)) > 0) { key = index.substring(p + 1, q); if (key.equals("")) { existingValue = new ArrayValueImpl(); array.put(existingValue); } else { keyValue = env.createString(key); existingValue = array.get(keyValue); if (existingValue == null || !existingValue.isset()) { existingValue = new ArrayValueImpl(); array.put(keyValue, existingValue); } else if (!existingValue.isArray()) { existingValue = new ArrayValueImpl().put(existingValue); array.put(keyValue, existingValue); } } array = (ArrayValue) existingValue; p = p1; q = index.indexOf(']', p); } if (q > 0) { index = index.substring(p + 1, q); } else { index = index.substring(p + 1); } if (index.equals("")) { if (formValueList != null) { for (int i = 0; i < formValueList.length; i++) { Value value; if (formValueList[i] != null) { value = env.createString(formValueList[i]); } else { value = NullValue.NULL; } put(array, null, value, addSlashesToValues); } } else { array.put(formValue); } } else if ('0' <= index.charAt(0) && index.charAt(0) <= '9') { put(array, LongValue.create(StringValue.toLong(index)), formValue, addSlashesToValues); } else { put(array, env.createString(index), formValue, addSlashesToValues); } } else { if (key != null) { key = key.replaceAll("\\.", "_"); put(array, env.createString(key), formValue, addSlashesToValues); } else { put(array, null, formValue, addSlashesToValues); } } } private static void put(ArrayValue array, Value key, Value value, boolean addSlashes) { if (addSlashes && value.isString()) { value = StringModule.addslashes(value.toStringValue()); } if (key == null) { array.put(value); } else { array.put(key, value); } } private static String getBoundary(String contentType) { int i = contentType.indexOf("boundary="); if (i < 0) { return null; } i += "boundary=".length(); int length = contentType.length(); char ch; if (length <= i) { return null; } else if ((ch = contentType.charAt(i)) == '\'') { StringBuilder sb = new StringBuilder(); for (i++; i < length && (ch = contentType.charAt(i)) != '\''; i++) { sb.append(ch); } return sb.toString(); } else if (ch == '"') { StringBuilder sb = new StringBuilder(); for (i++; i < length && (ch = contentType.charAt(i)) != '"'; i++) { sb.append(ch); } return sb.toString(); } else { StringBuilder sb = new StringBuilder(); for (/* intentionally left empty */; i < length && (ch = contentType.charAt(i)) != ' ' && ch != ';' && ch != ','; i++) { sb.append(ch); } return sb.toString(); } } private static String getAttribute(String attr, String name, boolean addSlashesToValues) { if (attr == null) { return null; } int length = attr.length(); int i = attr.indexOf(name); if (i < 0) { return null; } while (true) { char ch = attr.charAt(i - 1); if (i > 0 && ch != ' ' && ch != ';') { i = attr.indexOf(name, i + name.length()); } else { break; } if (i < 0) { return null; } } for (i += name.length(); i < length && attr.charAt(i) != '='; i++) { } for (i++; i < length && attr.charAt(i) == ' '; i++) { } StringBuilder value = new StringBuilder(); if (i < length && attr.charAt(i) == '\'') { for (i++; i < length && attr.charAt(i) != '\''; i++) { char ch = attr.charAt(i); if (ch == '"' && addSlashesToValues) { break; } value.append(ch); } } else if (i < length && attr.charAt(i) == '"') { for (i++; i < length && attr.charAt(i) != '"'; i++) { char ch = attr.charAt(i); if (ch == '\'' && addSlashesToValues) { break; } value.append(ch); } } else if (i < length) { char ch; for (; i < length && (ch = attr.charAt(i)) != ' ' && ch != ';'; i++) { value.append(ch); } } return value.toString(); } private static void putRequestMap(Env env, ArrayValue post, ArrayValue files, HttpServletRequest request, boolean addSlashesToValues, boolean isAllowUploads) { // this call consumes the inputstream Map<String, String[]> map = request.getParameterMap(); if (map == null) { return; } long maxFileSize = Long.MAX_VALUE; Value maxFileSizeV = post.get(MAX_FILE_SIZE); if (maxFileSizeV.isNull()) { maxFileSize = maxFileSizeV.toLong(); } if (isAllowUploads) { for (Map.Entry<String, String[]> entry : map.entrySet()) { String key = entry.getKey(); int len = key.length(); if (len < 10 || !key.endsWith(".filename")) { continue; } String name = key.substring(0, len - 9); String[] fileNames = request.getParameterValues(name + ".filename"); String[] tmpNames = request.getParameterValues(name + ".file"); String[] mimeTypes = request.getParameterValues(name + ".content-type"); for (int i = 0; i < fileNames.length; i++) { long fileLength = new FilePath(tmpNames[i]).getLength(); addFormFile(env, files, name, fileNames[i], tmpNames[i], mimeTypes[i], fileLength, addSlashesToValues, maxFileSize); } } } ArrayList<String> keys = new ArrayList<String>(); keys.addAll(request.getParameterMap().keySet()); Collections.sort(keys); for (String key : keys) { String[] value = request.getParameterValues(key); Post.addFormValue(env, post, key, value, addSlashesToValues); } } }
true
true
private static void readMultipartStream(Env env, MultipartStream ms, ArrayValue postArray, ArrayValue files, boolean addSlashesToValues, boolean isAllowUploads) throws IOException { ReadStream is; while ((is = ms.openRead()) != null) { String attr = (String) ms.getAttribute("content-disposition"); if (attr == null || !attr.startsWith("form-data")) { // TODO: is this an error? continue; } String name = getAttribute(attr, "name", addSlashesToValues); String filename = getAttribute(attr, "filename", addSlashesToValues); if (filename != null) { int slashIndex = filename.lastIndexOf('/'); int slashIndex2 = filename.lastIndexOf('\\'); slashIndex = Math.max(slashIndex, slashIndex2); if (slashIndex >= 0) { filename = filename.substring(slashIndex + 1); } } int bracketIndex = -1; if (name != null) { bracketIndex = name.lastIndexOf(']'); } if (bracketIndex >= 0 && bracketIndex < name.length() - 1) { // php/085c } else if (filename == null) { StringValue value = env.createStringBuilder(); value.appendReadAll(is, Integer.MAX_VALUE); if (name != null) { addFormValue(env, postArray, name, value, null, addSlashesToValues); } else { env.warning(L.l("file upload is missing name and filename")); } } else { if (!isAllowUploads) { continue; } String tmpName = ""; long tmpLength = 0; // A POST file upload with an empty string as the filename does not // create a temp file in the upload directory. if (filename.length() > 0) { Path tmpPath = env.getUploadDirectory().createTempFile("php", ".tmp"); env.addRemovePath(tmpPath); WriteStream os = tmpPath.openWrite(); try { os.writeStream(is); } finally { os.close(); } tmpName = tmpPath.getFullPath(); tmpLength = tmpPath.getLength(); } // php/0865 // // A header like "Content-Type: image/gif" indicates the mime type // for an uploaded file. String mimeType = getAttribute(attr, "mime-type", addSlashesToValues); if (mimeType == null) { mimeType = (String) ms.getAttribute("content-type"); // php/085f if (mimeType != null && mimeType.endsWith(";")) { mimeType = mimeType.substring(0, mimeType.length() - 1); } } // php/0864 // // mime type is empty string when no file is uploaded. if (filename.length() == 0) { mimeType = ""; } long maxFileSize = Long.MAX_VALUE; Value maxFileSizeV = postArray.get(MAX_FILE_SIZE); if (!maxFileSizeV.isNull()) { maxFileSize = maxFileSizeV.toLong(); } if (name != null) { addFormFile(env, files, name, filename, tmpName, mimeType, tmpLength, addSlashesToValues, maxFileSize); } else { addFormFile(env, files, filename, tmpName, mimeType, tmpLength, addSlashesToValues, maxFileSize); } } } }
private static void readMultipartStream(Env env, MultipartStream ms, ArrayValue postArray, ArrayValue files, boolean addSlashesToValues, boolean isAllowUploads) throws IOException { ReadStream is; while ((is = ms.openRead()) != null) { String attr = (String) ms.getAttribute("content-disposition"); if (attr == null || !attr.startsWith("form-data")) { // TODO: is this an error? continue; } String name = getAttribute(attr, "name", addSlashesToValues); String filename = getAttribute(attr, "filename", addSlashesToValues); if (filename != null) { int slashIndex = filename.lastIndexOf('/'); int slashIndex2 = filename.lastIndexOf('\\'); slashIndex = Math.max(slashIndex, slashIndex2); if (slashIndex >= 0) { filename = filename.substring(slashIndex + 1); } } int bracketIndex = -1; if (name != null) { bracketIndex = name.lastIndexOf(']'); } if (bracketIndex >= 0 && bracketIndex < name.length() - 1) { // php/085c } else if (filename == null) { StringValue value = env.createBinaryBuilder(); value.appendReadAll(is, Integer.MAX_VALUE); if (name != null) { addFormValue(env, postArray, name, value, null, addSlashesToValues); } else { env.warning(L.l("file upload is missing name and filename")); } } else { if (!isAllowUploads) { continue; } String tmpName = ""; long tmpLength = 0; // A POST file upload with an empty string as the filename does not // create a temp file in the upload directory. if (filename.length() > 0) { Path tmpPath = env.getUploadDirectory().createTempFile("php", ".tmp"); env.addRemovePath(tmpPath); WriteStream os = tmpPath.openWrite(); try { os.writeStream(is); } finally { os.close(); } tmpName = tmpPath.getFullPath(); tmpLength = tmpPath.getLength(); } // php/0865 // // A header like "Content-Type: image/gif" indicates the mime type // for an uploaded file. String mimeType = getAttribute(attr, "mime-type", addSlashesToValues); if (mimeType == null) { mimeType = (String) ms.getAttribute("content-type"); // php/085f if (mimeType != null && mimeType.endsWith(";")) { mimeType = mimeType.substring(0, mimeType.length() - 1); } } // php/0864 // // mime type is empty string when no file is uploaded. if (filename.length() == 0) { mimeType = ""; } long maxFileSize = Long.MAX_VALUE; Value maxFileSizeV = postArray.get(MAX_FILE_SIZE); if (!maxFileSizeV.isNull()) { maxFileSize = maxFileSizeV.toLong(); } if (name != null) { addFormFile(env, files, name, filename, tmpName, mimeType, tmpLength, addSlashesToValues, maxFileSize); } else { addFormFile(env, files, filename, tmpName, mimeType, tmpLength, addSlashesToValues, maxFileSize); } } } }
diff --git a/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java b/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java index 05065325..2b06cf47 100644 --- a/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java +++ b/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java @@ -1,216 +1,217 @@ /* Copyright 2005-2006 Tim Fennell * * 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 net.sourceforge.stripes.controller.multipart; import net.sourceforge.stripes.action.FileBean; import net.sourceforge.stripes.controller.FileUploadLimitExceededException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileUploadBase; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Iterator; import java.util.regex.Pattern; /** * An implementation of MultipartWrapper that uses Jakarta Commons FileUpload (from apache) * to parse the request parts. This implementation requires that both commons-fileupload and * commons-io be present in the classpath. While this implementation does introduce additional * dependencies, it's licensing (ASL 2.0) is significantly less restrictive than the licensing * for COS - the other alternative provided by Stripes. * * @author Tim Fennell * @since Stripes 1.4 */ public class CommonsMultipartWrapper implements MultipartWrapper { private static final Pattern WINDOWS_PATH_PREFIX_PATTERN = Pattern.compile("(?i:^[A-Z]:\\\\)"); /** Ensure this class will not load unless Commons FileUpload is on the classpath. */ static { FileUploadException.class.getName(); } private Map<String,FileItem> files = new HashMap<String,FileItem>(); private Map<String,String[]> parameters = new HashMap<String, String[]>(); private String charset; /** * Pseudo-constructor that allows the class to perform any initialization necessary. * * @param request an HttpServletRequest that has a content-type of multipart. * @param tempDir a File representing the temporary directory that can be used to store * file parts as they are uploaded if this is desirable * @param maxPostSize the size in bytes beyond which the request should not be read, and a * FileUploadLimitExceeded exception should be thrown * @throws IOException if a problem occurs processing the request of storing temporary * files * @throws FileUploadLimitExceededException if the POST content is longer than the * maxPostSize supplied. */ @SuppressWarnings("unchecked") public void build(HttpServletRequest request, File tempDir, long maxPostSize) throws IOException, FileUploadLimitExceededException { try { this.charset = request.getCharacterEncoding(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); List<FileItem> items = upload.parseRequest(request); Map<String,List<String>> params = new HashMap<String, List<String>>(); for (FileItem item : items) { // If it's a form field, add the string value to the list if (item.isFormField()) { List<String> values = params.get(item.getFieldName()); if (values == null) { values = new ArrayList<String>(); params.put(item.getFieldName(), values); } values.add(charset == null ? item.getString() : item.getString(charset)); } // Else store the file param else { files.put(item.getFieldName(), item); } } // Now convert them down into the usual map of String->String[] for (Map.Entry<String,List<String>> entry : params.entrySet()) { List<String> values = entry.getValue(); this.parameters.put(entry.getKey(), values.toArray(new String[values.size()])); } } catch (FileUploadBase.SizeLimitExceededException slee) { throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize()); } catch (FileUploadException fue) { IOException ioe = new IOException("Could not parse and cache file upload data."); ioe.initCause(fue); throw ioe; } } /** * Fetches the names of all non-file parameters in the request. Directly analogous to the * method of the same name in HttpServletRequest when the request is non-multipart. * * @return an Enumeration of all non-file parameter names in the request */ public Enumeration<String> getParameterNames() { return new IteratorEnumeration(this.parameters.keySet().iterator()); } /** * Fetches all values of a specific parameter in the request. To simulate the HTTP request * style, the array should be null for non-present parameters, and values in the array should * never be null - the empty String should be used when there is value. * * @param name the name of the request parameter * @return an array of non-null parameters or null */ public String[] getParameterValues(String name) { return this.parameters.get(name); } /** * Fetches the names of all file parameters in the request. Note that these are not the file * names, but the names given to the form fields in which the files are specified. * * @return the names of all file parameters in the request. */ public Enumeration<String> getFileParameterNames() { return new IteratorEnumeration(this.files.keySet().iterator()); } /** * Responsible for constructing a FileBean object for the named file parameter. If there is no * file parameter with the specified name this method should return null. * * @param name the name of the file parameter * @return a FileBean object wrapping the uploaded file */ public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); - String filename = item.getName(); - if (item == null || ((filename == null || filename.length() == 0) && item.getSize() == 0)) { + if (item == null + || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included + String filename = item.getName(); int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) index = filename.lastIndexOf('\\'); else index = filename.lastIndexOf('/'); if (index >= 0 && index + 1 < filename.length() - 1) filename = filename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } } /** Little helper class to create an enumeration as per the interface. */ private static class IteratorEnumeration implements Enumeration<String> { Iterator<String> iterator; /** Constructs an enumeration that consumes from the underlying iterator. */ IteratorEnumeration(Iterator<String> iterator) { this.iterator = iterator; } /** Returns true if more elements can be consumed, false otherwise. */ public boolean hasMoreElements() { return this.iterator.hasNext(); } /** Gets the next element out of the iterator. */ public String nextElement() { return this.iterator.next(); } } }
false
true
public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); String filename = item.getName(); if (item == null || ((filename == null || filename.length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) index = filename.lastIndexOf('\\'); else index = filename.lastIndexOf('/'); if (index >= 0 && index + 1 < filename.length() - 1) filename = filename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); if (item == null || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included String filename = item.getName(); int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) index = filename.lastIndexOf('\\'); else index = filename.lastIndexOf('/'); if (index >= 0 && index + 1 < filename.length() - 1) filename = filename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
diff --git a/Mobile/BukuDroid/src/org/csie/mpp/buku/view/StreamManager.java b/Mobile/BukuDroid/src/org/csie/mpp/buku/view/StreamManager.java index b215e84..b5671b4 100644 --- a/Mobile/BukuDroid/src/org/csie/mpp/buku/view/StreamManager.java +++ b/Mobile/BukuDroid/src/org/csie/mpp/buku/view/StreamManager.java @@ -1,180 +1,178 @@ package org.csie.mpp.buku.view; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.csie.mpp.buku.App; import org.csie.mpp.buku.BookActivity; import org.csie.mpp.buku.R; import org.csie.mpp.buku.Util; import org.csie.mpp.buku.db.DBHelper; import org.csie.mpp.buku.db.FriendEntry; import org.json.JSONArray; import org.json.JSONObject; import com.facebook.android.BaseRequestListener; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class StreamManager extends ViewManager implements OnItemClickListener { private List<Stream> streams; private ArrayAdapter<Stream> adapter; public StreamManager(Activity activity, DBHelper helper) { super(activity, helper); } private static class Stream { private String id; private String source; private String message; private String book; private String author; private String link; private Bitmap pic; private Date time; } private void createView(LinearLayout frame) { if(streams.size() == 0) { TextView text = (TextView)frame.findViewById(R.id.text); text.setText("You have no streams. QQ"); // TODO: change to strings.xml } else { TextView text = (TextView)frame.findViewById(R.id.text); text.setText(""); adapter = new ArrayAdapter<Stream>(activity, R.layout.list_item_stream, streams) { @Override public View getView(int position, View convertView, ViewGroup parent) { Stream stream = streams.get(position); LayoutInflater inflater = activity.getLayoutInflater(); View view = inflater.inflate(R.layout.list_item_stream, null); if(stream.message != null) ((TextView)view.findViewById(R.id.list_message)).setText(stream.message); if(stream.pic != null) ((ImageView)view.findViewById(R.id.list_image)).setImageBitmap(stream.pic); ((TextView)view.findViewById(R.id.list_name)).setText(stream.book); ((TextView)view.findViewById(R.id.list_author)).setText(stream.author); ((TextView)view.findViewById(R.id.list_time)).setText(stream.time.toLocaleString()); return view; } }; ListView list = (ListView)frame.findViewById(R.id.list); list.setAdapter(adapter); list.setOnItemClickListener(this); } } @Override protected void updateView() { final LinearLayout frame = getFrame(); if(streams != null) createView(frame); else { StringBuilder builder = new StringBuilder(); for(FriendEntry friend: FriendEntry.queryAll(rdb)) { if(builder.length() > 0) builder.append(","); builder.append(friend.id); } String friends = builder.toString(); Bundle params = new Bundle(); - params.putString("q", "SELECT post_id,actor_id,message,attachment,created_time FROM stream WHERE source_id IN (" + friends - + ") AND app_id = " + App.FB_APP_ID); - Log.d("Yi", "SELECT post_id,actor_id,message,attachment,created_time FROM stream WHERE source_id IN (" + friends + params.putString("q", "SELECT post_id,actor_id,message,attachment,created_time FROM stream WHERE source_id = me() OR source_id IN (" + friends + ") AND app_id = " + App.FB_APP_ID); // TODO: change to AsyncTask App.fb_runner.request("fql", params, new BaseRequestListener() { @Override public void onComplete(String response, Object state) { Log.d("Yi", response); streams = new ArrayList<Stream>(); try { JSONObject json = new JSONObject(response); JSONArray data = json.getJSONArray("data"); for(int i = 0; i < data.length(); i++) { try { JSONObject item = data.getJSONObject(i); Stream stream = new Stream(); stream.id = item.getString("post_id"); stream.source = item.getString("actor_id"); stream.message = item.getString("message"); stream.time = new Date(Long.parseLong(item.getString("created_time")) + 1000); item = item.getJSONObject("attachment"); if(item.has("name")) { stream.book = item.getString("name"); stream.author = item.getString("caption"); stream.link = item.getString("href"); } else { stream.book = item.getString("caption"); stream.author = item.getString("description"); } try { stream.pic = Util.urlToImage(new URL(item.getJSONArray("media").getJSONObject(0).getString("src"))); } catch(Exception e) { // No icon found. } streams.add(stream); } catch(Exception e) { Log.e(App.TAG, e.toString()); } } } catch(Exception e) { Log.e(App.TAG, e.toString()); } activity.runOnUiThread(new Runnable() { @Override public void run() { createView(frame); } }); } }); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Stream stream = streams.get(position); if(stream.link == null) { // TODO: display error message } else { Intent intent = new Intent(activity, BookActivity.class); intent.putExtra(BookActivity.LINK, stream.link); activity.startActivity(intent); } } }
true
true
protected void updateView() { final LinearLayout frame = getFrame(); if(streams != null) createView(frame); else { StringBuilder builder = new StringBuilder(); for(FriendEntry friend: FriendEntry.queryAll(rdb)) { if(builder.length() > 0) builder.append(","); builder.append(friend.id); } String friends = builder.toString(); Bundle params = new Bundle(); params.putString("q", "SELECT post_id,actor_id,message,attachment,created_time FROM stream WHERE source_id IN (" + friends + ") AND app_id = " + App.FB_APP_ID); Log.d("Yi", "SELECT post_id,actor_id,message,attachment,created_time FROM stream WHERE source_id IN (" + friends + ") AND app_id = " + App.FB_APP_ID); // TODO: change to AsyncTask App.fb_runner.request("fql", params, new BaseRequestListener() { @Override public void onComplete(String response, Object state) { Log.d("Yi", response); streams = new ArrayList<Stream>(); try { JSONObject json = new JSONObject(response); JSONArray data = json.getJSONArray("data"); for(int i = 0; i < data.length(); i++) { try { JSONObject item = data.getJSONObject(i); Stream stream = new Stream(); stream.id = item.getString("post_id"); stream.source = item.getString("actor_id"); stream.message = item.getString("message"); stream.time = new Date(Long.parseLong(item.getString("created_time")) + 1000); item = item.getJSONObject("attachment"); if(item.has("name")) { stream.book = item.getString("name"); stream.author = item.getString("caption"); stream.link = item.getString("href"); } else { stream.book = item.getString("caption"); stream.author = item.getString("description"); } try { stream.pic = Util.urlToImage(new URL(item.getJSONArray("media").getJSONObject(0).getString("src"))); } catch(Exception e) { // No icon found. } streams.add(stream); } catch(Exception e) { Log.e(App.TAG, e.toString()); } } } catch(Exception e) { Log.e(App.TAG, e.toString()); } activity.runOnUiThread(new Runnable() { @Override public void run() { createView(frame); } }); } }); } }
protected void updateView() { final LinearLayout frame = getFrame(); if(streams != null) createView(frame); else { StringBuilder builder = new StringBuilder(); for(FriendEntry friend: FriendEntry.queryAll(rdb)) { if(builder.length() > 0) builder.append(","); builder.append(friend.id); } String friends = builder.toString(); Bundle params = new Bundle(); params.putString("q", "SELECT post_id,actor_id,message,attachment,created_time FROM stream WHERE source_id = me() OR source_id IN (" + friends + ") AND app_id = " + App.FB_APP_ID); // TODO: change to AsyncTask App.fb_runner.request("fql", params, new BaseRequestListener() { @Override public void onComplete(String response, Object state) { Log.d("Yi", response); streams = new ArrayList<Stream>(); try { JSONObject json = new JSONObject(response); JSONArray data = json.getJSONArray("data"); for(int i = 0; i < data.length(); i++) { try { JSONObject item = data.getJSONObject(i); Stream stream = new Stream(); stream.id = item.getString("post_id"); stream.source = item.getString("actor_id"); stream.message = item.getString("message"); stream.time = new Date(Long.parseLong(item.getString("created_time")) + 1000); item = item.getJSONObject("attachment"); if(item.has("name")) { stream.book = item.getString("name"); stream.author = item.getString("caption"); stream.link = item.getString("href"); } else { stream.book = item.getString("caption"); stream.author = item.getString("description"); } try { stream.pic = Util.urlToImage(new URL(item.getJSONArray("media").getJSONObject(0).getString("src"))); } catch(Exception e) { // No icon found. } streams.add(stream); } catch(Exception e) { Log.e(App.TAG, e.toString()); } } } catch(Exception e) { Log.e(App.TAG, e.toString()); } activity.runOnUiThread(new Runnable() { @Override public void run() { createView(frame); } }); } }); } }
diff --git a/maven-junithelper-plugin/src/main/java/org/junithelper/mavenplugin/AbstractJUnitHelperMojo.java b/maven-junithelper-plugin/src/main/java/org/junithelper/mavenplugin/AbstractJUnitHelperMojo.java index 3557642..afe8b93 100644 --- a/maven-junithelper-plugin/src/main/java/org/junithelper/mavenplugin/AbstractJUnitHelperMojo.java +++ b/maven-junithelper-plugin/src/main/java/org/junithelper/mavenplugin/AbstractJUnitHelperMojo.java @@ -1,180 +1,180 @@ package org.junithelper.mavenplugin; import org.apache.maven.plugin.AbstractMojo; import org.junithelper.core.Version; import org.junithelper.core.config.Configuration; import org.junithelper.core.config.JUnitVersion; import org.junithelper.core.config.MockObjectFramework; import org.junithelper.core.config.TestingPatternExplicitComment; import org.junithelper.core.util.Stdout; public abstract class AbstractJUnitHelperMojo extends AbstractMojo { /** * @parameter */ protected String language = "en"; /** * @parameter */ protected String outputFileEncoding = "UTF-8"; /** * @parameter */ protected String directoryPathOfProductSourceCode = "src/main/java"; /** * @parameter */ protected String directoryPathOfTestSourceCode = "src/test/java"; /** * @parameter */ protected String junitVersion = "version4"; /** * @parameter */ protected String testCaseClassNameToExtend = "junit.framework.TestCase"; /** * @parameter */ protected boolean isTemplateImplementationRequired = true; /** * @parameter */ protected boolean target_isAccessorExcluded = true; /** * @parameter */ protected boolean target_isExceptionPatternRequired = false; /** * @parameter */ protected boolean target_isPackageLocalMethodRequired = true; /** * @parameter */ protected boolean target_isProtectedMethodRequired = true; /** * @parameter */ protected boolean target_isPublicMethodRequired = true; /** * @parameter */ protected String target_regexpCsvForExclusion = ""; /** * @parameter */ protected boolean testMethodName_isArgsRequired = true; /** * @parameter */ protected boolean testMethodName_isReturnRequired = false; /** * @parameter */ protected String testMethodName_basicDelimiter = "_"; /** * @parameter */ protected String testMethodName_argsAreaPrefix = "A"; /** * @parameter */ protected String testMethodName_argsAreaDelimiter = "$"; /** * @parameter */ protected String testMethodName_returnAreaPrefix = "R"; /** * @parameter */ protected String testMethodName_returnAreaDelimiter = "$"; /** * @parameter */ protected String testMethodName_exceptionAreaPrefix = "T"; /** * @parameter */ protected String testMethodName_exceptionAreaDelimiter = "$"; /** * @parameter */ protected String mockObjectFramework = ""; /** * @parameter */ protected String testingPatternExplicitComment = ""; /** * @parameter */ protected boolean isExtensionEnabled = false; /** * @parameter */ protected String extensionConfigXML = "junithelper-extension.xml"; protected Configuration loadConfig() { Configuration config = new Configuration(); config.language = language; config.outputFileEncoding = outputFileEncoding; config.directoryPathOfProductSourceCode = directoryPathOfProductSourceCode; config.directoryPathOfTestSourceCode = directoryPathOfTestSourceCode; try { config.junitVersion = JUnitVersion.valueOf(junitVersion); } catch (Exception e) { config.junitVersion = JUnitVersion.version4; } config.testCaseClassNameToExtend = testCaseClassNameToExtend; config.isTemplateImplementationRequired = isTemplateImplementationRequired; config.target.isAccessorExcluded = target_isAccessorExcluded; config.target.isExceptionPatternRequired = target_isExceptionPatternRequired; config.target.isPackageLocalMethodRequired = target_isPackageLocalMethodRequired; config.target.isProtectedMethodRequired = target_isProtectedMethodRequired; config.target.isPublicMethodRequired = target_isPublicMethodRequired; config.target.regexpCsvForExclusion = target_regexpCsvForExclusion; config.testMethodName.isArgsRequired = testMethodName_isArgsRequired; config.testMethodName.isReturnRequired = testMethodName_isReturnRequired; config.testMethodName.basicDelimiter = testMethodName_basicDelimiter; config.testMethodName.argsAreaPrefix = testMethodName_argsAreaPrefix; config.testMethodName.argsAreaDelimiter = testMethodName_argsAreaDelimiter; config.testMethodName.returnAreaPrefix = testMethodName_returnAreaPrefix; config.testMethodName.returnAreaDelimiter = testMethodName_returnAreaDelimiter; config.testMethodName.exceptionAreaPrefix = testMethodName_exceptionAreaPrefix; config.testMethodName.exceptionAreaDelimiter = testMethodName_exceptionAreaDelimiter; try { config.mockObjectFramework = MockObjectFramework.valueOf(mockObjectFramework); } catch (Exception e) { config.mockObjectFramework = null; } try { config.testingPatternExplicitComment = TestingPatternExplicitComment.valueOf(testingPatternExplicitComment); } catch (Exception e) { - config.testingPatternExplicitComment = null; + config.testingPatternExplicitComment = TestingPatternExplicitComment.None; } config.isExtensionEnabled = isExtensionEnabled; config.extensionConfigXML = extensionConfigXML; return config; } protected static void printLogoAndVersion() { Stdout.p(" _ "); Stdout.p(" / _ ._/_/_/_ /_ _ _"); Stdout.p("(_//_// // / / //_'//_//_'/ "); Stdout.p(" / "); Stdout.p("JUnit Helper version " + Version.get()); Stdout.p(""); } }
true
true
protected Configuration loadConfig() { Configuration config = new Configuration(); config.language = language; config.outputFileEncoding = outputFileEncoding; config.directoryPathOfProductSourceCode = directoryPathOfProductSourceCode; config.directoryPathOfTestSourceCode = directoryPathOfTestSourceCode; try { config.junitVersion = JUnitVersion.valueOf(junitVersion); } catch (Exception e) { config.junitVersion = JUnitVersion.version4; } config.testCaseClassNameToExtend = testCaseClassNameToExtend; config.isTemplateImplementationRequired = isTemplateImplementationRequired; config.target.isAccessorExcluded = target_isAccessorExcluded; config.target.isExceptionPatternRequired = target_isExceptionPatternRequired; config.target.isPackageLocalMethodRequired = target_isPackageLocalMethodRequired; config.target.isProtectedMethodRequired = target_isProtectedMethodRequired; config.target.isPublicMethodRequired = target_isPublicMethodRequired; config.target.regexpCsvForExclusion = target_regexpCsvForExclusion; config.testMethodName.isArgsRequired = testMethodName_isArgsRequired; config.testMethodName.isReturnRequired = testMethodName_isReturnRequired; config.testMethodName.basicDelimiter = testMethodName_basicDelimiter; config.testMethodName.argsAreaPrefix = testMethodName_argsAreaPrefix; config.testMethodName.argsAreaDelimiter = testMethodName_argsAreaDelimiter; config.testMethodName.returnAreaPrefix = testMethodName_returnAreaPrefix; config.testMethodName.returnAreaDelimiter = testMethodName_returnAreaDelimiter; config.testMethodName.exceptionAreaPrefix = testMethodName_exceptionAreaPrefix; config.testMethodName.exceptionAreaDelimiter = testMethodName_exceptionAreaDelimiter; try { config.mockObjectFramework = MockObjectFramework.valueOf(mockObjectFramework); } catch (Exception e) { config.mockObjectFramework = null; } try { config.testingPatternExplicitComment = TestingPatternExplicitComment.valueOf(testingPatternExplicitComment); } catch (Exception e) { config.testingPatternExplicitComment = null; } config.isExtensionEnabled = isExtensionEnabled; config.extensionConfigXML = extensionConfigXML; return config; }
protected Configuration loadConfig() { Configuration config = new Configuration(); config.language = language; config.outputFileEncoding = outputFileEncoding; config.directoryPathOfProductSourceCode = directoryPathOfProductSourceCode; config.directoryPathOfTestSourceCode = directoryPathOfTestSourceCode; try { config.junitVersion = JUnitVersion.valueOf(junitVersion); } catch (Exception e) { config.junitVersion = JUnitVersion.version4; } config.testCaseClassNameToExtend = testCaseClassNameToExtend; config.isTemplateImplementationRequired = isTemplateImplementationRequired; config.target.isAccessorExcluded = target_isAccessorExcluded; config.target.isExceptionPatternRequired = target_isExceptionPatternRequired; config.target.isPackageLocalMethodRequired = target_isPackageLocalMethodRequired; config.target.isProtectedMethodRequired = target_isProtectedMethodRequired; config.target.isPublicMethodRequired = target_isPublicMethodRequired; config.target.regexpCsvForExclusion = target_regexpCsvForExclusion; config.testMethodName.isArgsRequired = testMethodName_isArgsRequired; config.testMethodName.isReturnRequired = testMethodName_isReturnRequired; config.testMethodName.basicDelimiter = testMethodName_basicDelimiter; config.testMethodName.argsAreaPrefix = testMethodName_argsAreaPrefix; config.testMethodName.argsAreaDelimiter = testMethodName_argsAreaDelimiter; config.testMethodName.returnAreaPrefix = testMethodName_returnAreaPrefix; config.testMethodName.returnAreaDelimiter = testMethodName_returnAreaDelimiter; config.testMethodName.exceptionAreaPrefix = testMethodName_exceptionAreaPrefix; config.testMethodName.exceptionAreaDelimiter = testMethodName_exceptionAreaDelimiter; try { config.mockObjectFramework = MockObjectFramework.valueOf(mockObjectFramework); } catch (Exception e) { config.mockObjectFramework = null; } try { config.testingPatternExplicitComment = TestingPatternExplicitComment.valueOf(testingPatternExplicitComment); } catch (Exception e) { config.testingPatternExplicitComment = TestingPatternExplicitComment.None; } config.isExtensionEnabled = isExtensionEnabled; config.extensionConfigXML = extensionConfigXML; return config; }
diff --git a/src/main/java/org/jahia/modules/myconnections/workflow/jbpm/UserConnectionTaskLifeCycleEventListener.java b/src/main/java/org/jahia/modules/myconnections/workflow/jbpm/UserConnectionTaskLifeCycleEventListener.java index 062efbc..b304640 100644 --- a/src/main/java/org/jahia/modules/myconnections/workflow/jbpm/UserConnectionTaskLifeCycleEventListener.java +++ b/src/main/java/org/jahia/modules/myconnections/workflow/jbpm/UserConnectionTaskLifeCycleEventListener.java @@ -1,109 +1,109 @@ /** * This file is part of Jahia, next-generation open source CMS: * Jahia's next-generation, open source CMS stems from a widely acknowledged vision * of enterprise application convergence - web, search, document, social and portal - * unified by the simplicity of web content management. * * For more information, please visit http://www.jahia.com. * * Copyright (C) 2002-2012 Jahia Solutions Group SA. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * As a special exception to the terms and conditions of version 2.0 of * the GPL (or any later version), you may redistribute this Program in connection * with Free/Libre and Open Source Software ("FLOSS") applications as described * in Jahia's FLOSS exception. You should have received a copy of the text * describing the FLOSS exception, and it is also available here: * http://www.jahia.com/license * * Commercial and Supported Versions of the program (dual licensing): * alternatively, commercial and supported versions of the program may be used * in accordance with the terms and conditions contained in a separate * written agreement between you and Jahia Solutions Group SA. * * If you are unsure which license is appropriate for your use, * please contact the sales department at [email protected]. */ package org.jahia.modules.myconnections.workflow.jbpm; import org.apache.commons.lang.StringUtils; import org.jahia.registries.ServicesRegistry; import org.jahia.services.usermanager.JahiaPrincipal; import org.jahia.services.usermanager.JahiaUser; import org.jahia.services.workflow.jbpm.JBPMTaskLifeCycleEventListener; import org.jbpm.runtime.manager.impl.task.SynchronizedTaskService; import org.jbpm.services.task.events.AfterTaskAddedEvent; import org.jbpm.services.task.impl.model.GroupImpl; import org.jbpm.services.task.impl.model.PeopleAssignmentsImpl; import org.jbpm.services.task.impl.model.UserImpl; import org.kie.api.task.model.OrganizationalEntity; import org.kie.api.task.model.PeopleAssignments; import org.kie.api.task.model.Task; import javax.enterprise.event.Observes; import javax.enterprise.event.Reception; import javax.jcr.RepositoryException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Assignment handler for user connection task. * * @author Serge Huber */ public class UserConnectionTaskLifeCycleEventListener extends JBPMTaskLifeCycleEventListener { private static final long serialVersionUID = 3356236148908996978L; /** * sets the actorId and candidates for the given task. */ @Override public void afterTaskAddedEvent(@Observes(notifyObserver = Reception.IF_EXISTS) @AfterTaskAddedEvent Task task) { Map<String, Object> taskInputParameters = getTaskInputParameters(task); Map<String, Object> taskOutputParameters = getTaskOutputParameters(task, taskInputParameters); PeopleAssignments peopleAssignments = new PeopleAssignmentsImpl(); List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>(); String to = (String) taskInputParameters.get("to"); JahiaUser jahiaUser = null; if (StringUtils.isNotEmpty(to)) { jahiaUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUserByKey(to); potentialOwners.add(new UserImpl((jahiaUser).getUserKey())); } List<OrganizationalEntity> administrators = new ArrayList<OrganizationalEntity>(); administrators.add(new GroupImpl(ServicesRegistry.getInstance().getJahiaGroupManagerService().getAdministratorGroup(null).getGroupKey())); - peopleAssignments.getBusinessAdministrators().addAll(administrators); - peopleAssignments.getPotentialOwners().addAll(potentialOwners); +// peopleAssignments.getBusinessAdministrators().addAll(administrators); +// peopleAssignments.getPotentialOwners().addAll(potentialOwners); if (jahiaUser != null) { List<JahiaPrincipal> jahiaPrincipals = new ArrayList<JahiaPrincipal>(); jahiaPrincipals.add(jahiaUser); try { createTask(task, taskInputParameters, taskOutputParameters, jahiaPrincipals); ((SynchronizedTaskService) taskService).addContent(task.getId(), taskOutputParameters); } catch (RepositoryException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } }
true
true
public void afterTaskAddedEvent(@Observes(notifyObserver = Reception.IF_EXISTS) @AfterTaskAddedEvent Task task) { Map<String, Object> taskInputParameters = getTaskInputParameters(task); Map<String, Object> taskOutputParameters = getTaskOutputParameters(task, taskInputParameters); PeopleAssignments peopleAssignments = new PeopleAssignmentsImpl(); List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>(); String to = (String) taskInputParameters.get("to"); JahiaUser jahiaUser = null; if (StringUtils.isNotEmpty(to)) { jahiaUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUserByKey(to); potentialOwners.add(new UserImpl((jahiaUser).getUserKey())); } List<OrganizationalEntity> administrators = new ArrayList<OrganizationalEntity>(); administrators.add(new GroupImpl(ServicesRegistry.getInstance().getJahiaGroupManagerService().getAdministratorGroup(null).getGroupKey())); peopleAssignments.getBusinessAdministrators().addAll(administrators); peopleAssignments.getPotentialOwners().addAll(potentialOwners); if (jahiaUser != null) { List<JahiaPrincipal> jahiaPrincipals = new ArrayList<JahiaPrincipal>(); jahiaPrincipals.add(jahiaUser); try { createTask(task, taskInputParameters, taskOutputParameters, jahiaPrincipals); ((SynchronizedTaskService) taskService).addContent(task.getId(), taskOutputParameters); } catch (RepositoryException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
public void afterTaskAddedEvent(@Observes(notifyObserver = Reception.IF_EXISTS) @AfterTaskAddedEvent Task task) { Map<String, Object> taskInputParameters = getTaskInputParameters(task); Map<String, Object> taskOutputParameters = getTaskOutputParameters(task, taskInputParameters); PeopleAssignments peopleAssignments = new PeopleAssignmentsImpl(); List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>(); String to = (String) taskInputParameters.get("to"); JahiaUser jahiaUser = null; if (StringUtils.isNotEmpty(to)) { jahiaUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUserByKey(to); potentialOwners.add(new UserImpl((jahiaUser).getUserKey())); } List<OrganizationalEntity> administrators = new ArrayList<OrganizationalEntity>(); administrators.add(new GroupImpl(ServicesRegistry.getInstance().getJahiaGroupManagerService().getAdministratorGroup(null).getGroupKey())); // peopleAssignments.getBusinessAdministrators().addAll(administrators); // peopleAssignments.getPotentialOwners().addAll(potentialOwners); if (jahiaUser != null) { List<JahiaPrincipal> jahiaPrincipals = new ArrayList<JahiaPrincipal>(); jahiaPrincipals.add(jahiaUser); try { createTask(task, taskInputParameters, taskOutputParameters, jahiaPrincipals); ((SynchronizedTaskService) taskService).addContent(task.getId(), taskOutputParameters); } catch (RepositoryException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
diff --git a/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/CodeGenUIPlugin.java b/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/CodeGenUIPlugin.java index 671383b36..f75165544 100644 --- a/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/CodeGenUIPlugin.java +++ b/plugins/org.eclipse.gmf.codegen.ui/src/org/eclipse/gmf/internal/codegen/CodeGenUIPlugin.java @@ -1,96 +1,99 @@ /* * Copyright (c) 2005 Borland Software Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Artem Tikhomirov (Borland) - initial API and implementation */ package org.eclipse.gmf.internal.codegen; import java.text.MessageFormat; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.emf.ecore.EPackage; import org.eclipse.gmf.codegen.gmfgen.GMFGenPackage; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; public class CodeGenUIPlugin extends AbstractUIPlugin { private static CodeGenUIPlugin plugin; public CodeGenUIPlugin() { plugin = this; } public void start(BundleContext context) throws Exception { super.start(context); if (null == EPackage.Registry.INSTANCE.getEPackage(GMFGenPackage.eNS_URI)) { EPackage.Registry.INSTANCE.put(GMFGenPackage.eNS_URI, new EPackage.Descriptor() { public EPackage getEPackage() { return GMFGenPackage.eINSTANCE; } }); } } public void stop(BundleContext context) throws Exception { super.stop(context); plugin = null; } public static CodeGenUIPlugin getDefault() { return plugin; } public static String getBundleString(String key) { return Platform.getResourceBundle(getDefault().getBundle()).getString(key); } public static String getBundleString(String key, Object[] args) { String val = getBundleString(key); if (val == null) { return key; } return MessageFormat.format(val, args); } public static IStatus createStatus(int statusCode, String message, Exception ex) { return new Status(statusCode, getPluginID(), 0, message, ex); } public static IStatus createError(String message, Exception ex) { return createStatus(IStatus.ERROR, message, ex); } public static IStatus createWarning(String message) { return createStatus(IStatus.WARNING, message, null); } public static IStatus createInfo(String message) { return createStatus(IStatus.INFO, message, null); } public static String getPluginID() { return getDefault().getBundle().getSymbolicName(); } public static String formatMessage(String bundleStringKey, IStatus status) { if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); StringBuffer sb = new StringBuffer(); // don't care about too nested statuses just because will switch to // jobs soon, with // required support already in place - for (int i = 0; i < children.length; i++) { + for (int i = 0; i < children.length && i < 10; i++) { sb.append(children[i].getMessage()); sb.append('\n'); } + if (children.length > 10) { + sb.append("..."); + } return CodeGenUIPlugin.getBundleString(bundleStringKey, new Object[] { sb.toString() }); } else { return CodeGenUIPlugin.getBundleString(bundleStringKey, new Object[] { status.getMessage() }); } } }
false
true
public static String formatMessage(String bundleStringKey, IStatus status) { if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); StringBuffer sb = new StringBuffer(); // don't care about too nested statuses just because will switch to // jobs soon, with // required support already in place for (int i = 0; i < children.length; i++) { sb.append(children[i].getMessage()); sb.append('\n'); } return CodeGenUIPlugin.getBundleString(bundleStringKey, new Object[] { sb.toString() }); } else { return CodeGenUIPlugin.getBundleString(bundleStringKey, new Object[] { status.getMessage() }); } }
public static String formatMessage(String bundleStringKey, IStatus status) { if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); StringBuffer sb = new StringBuffer(); // don't care about too nested statuses just because will switch to // jobs soon, with // required support already in place for (int i = 0; i < children.length && i < 10; i++) { sb.append(children[i].getMessage()); sb.append('\n'); } if (children.length > 10) { sb.append("..."); } return CodeGenUIPlugin.getBundleString(bundleStringKey, new Object[] { sb.toString() }); } else { return CodeGenUIPlugin.getBundleString(bundleStringKey, new Object[] { status.getMessage() }); } }
diff --git a/src/main/java/com/mmakowski/maven/plugins/specs2/Specs2RunnerMojo.java b/src/main/java/com/mmakowski/maven/plugins/specs2/Specs2RunnerMojo.java index 2eb5834..0a9ad0f 100644 --- a/src/main/java/com/mmakowski/maven/plugins/specs2/Specs2RunnerMojo.java +++ b/src/main/java/com/mmakowski/maven/plugins/specs2/Specs2RunnerMojo.java @@ -1,32 +1,32 @@ package com.mmakowski.maven.plugins.specs2; import java.io.File; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; /** * Executes specs2 runner for all specifications in the current project. A thing * wrapper for {@link Specs2Runner}, which is implemented in Scala. * * @author Maciek Makowski * @requiresDependencyResolution test * @goal run-specs * @phase verify * @since 1.0.0 */ public class Specs2RunnerMojo extends AbstractMojo { /** @parameter default-value="${project}" */ private MavenProject mavenProject; /** @parameter default-value="${project.build.testOutputDirectory}" */ private File testClassesDirectory; /** @parameter default-value="${project.build.outputDirectory}" */ private File classesDirectory; public void execute() throws MojoExecutionException, MojoFailureException { - if (!(new Specs2Runner().runSpecs(getLog(), mavenProject, classesDirectory, testClassesDirectory))) + if (!(new Specs2Runner().runSpecs(getLog(), mavenProject, classesDirectory, testClassesDirectory).booleanValue())) throw new MojoFailureException("there have been errors/failures"); } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { if (!(new Specs2Runner().runSpecs(getLog(), mavenProject, classesDirectory, testClassesDirectory))) throw new MojoFailureException("there have been errors/failures"); }
public void execute() throws MojoExecutionException, MojoFailureException { if (!(new Specs2Runner().runSpecs(getLog(), mavenProject, classesDirectory, testClassesDirectory).booleanValue())) throw new MojoFailureException("there have been errors/failures"); }
diff --git a/dry-validator/src/test/java/com/google/codes/dryvalidator/ValidationFromStruts.java b/dry-validator/src/test/java/com/google/codes/dryvalidator/ValidationFromStruts.java index ca80060..98bacfa 100644 --- a/dry-validator/src/test/java/com/google/codes/dryvalidator/ValidationFromStruts.java +++ b/dry-validator/src/test/java/com/google/codes/dryvalidator/ValidationFromStruts.java @@ -1,74 +1,75 @@ package com.google.codes.dryvalidator; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import junit.framework.Assert; import org.apache.commons.lang.StringUtils; import org.apache.commons.validator.Field; import org.apache.commons.validator.Form; import org.apache.commons.validator.ValidatorResources; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; import com.google.codes.dryvalidator.dto.FormItem; import com.google.codes.dryvalidator.dto.Validation; public class ValidationFromStruts { protected static ValidationEngine validationEngine; @BeforeClass public static void initailizeValidationEngine() { validationEngine = new ValidationEngine(); validationEngine.setup(); } @AfterClass public static void disposeValidationEngine() { validationEngine.dispose(); } @SuppressWarnings("unchecked") @Test public void test() throws IOException, SAXException { InputStream in = this.getClass().getResourceAsStream("/validation.xml"); ValidatorResources resources = new ValidatorResources(in); Form form = resources.getForm(Locale.JAPANESE, "MemberForm"); for(Field field : (List<Field>)form.getFields()) { FormItem formItem = new FormItem(); formItem.setId(field.getProperty()); formItem.setLabel(field.getKey()); for(String depend : (List<String>)field.getDependencyList()) { String value = null; if(StringUtils.equals(depend, "required")) { value="true"; } else { value=field.getVarValue(depend); } if(StringUtils.equals(depend, "maxlength")) { depend = "maxLength"; } Validation validation = new Validation(depend, value); formItem.getValidations().addValidation(validation); } System.out.println(formItem); validationEngine.register(formItem); } Map<String, Object> formValues = new HashMap<String, Object>(); formValues.put("hasSpouse", true); formValues.put("familyName", "01234567890"); formValues.put("childrenNum", ""); + formValues.put("genderCd", false); Map<String, List<String>> messages = validationEngine.exec(formValues); List<String> childrenNumMessages = messages.get("childrenNum"); Assert.assertTrue("配偶者がありのときは、子供の人数が必須になる", childrenNumMessages != null && childrenNumMessages.size() == 1); validationEngine.unregisterAll(); } }
true
true
public void test() throws IOException, SAXException { InputStream in = this.getClass().getResourceAsStream("/validation.xml"); ValidatorResources resources = new ValidatorResources(in); Form form = resources.getForm(Locale.JAPANESE, "MemberForm"); for(Field field : (List<Field>)form.getFields()) { FormItem formItem = new FormItem(); formItem.setId(field.getProperty()); formItem.setLabel(field.getKey()); for(String depend : (List<String>)field.getDependencyList()) { String value = null; if(StringUtils.equals(depend, "required")) { value="true"; } else { value=field.getVarValue(depend); } if(StringUtils.equals(depend, "maxlength")) { depend = "maxLength"; } Validation validation = new Validation(depend, value); formItem.getValidations().addValidation(validation); } System.out.println(formItem); validationEngine.register(formItem); } Map<String, Object> formValues = new HashMap<String, Object>(); formValues.put("hasSpouse", true); formValues.put("familyName", "01234567890"); formValues.put("childrenNum", ""); Map<String, List<String>> messages = validationEngine.exec(formValues); List<String> childrenNumMessages = messages.get("childrenNum"); Assert.assertTrue("配偶者がありのときは、子供の人数が必須になる", childrenNumMessages != null && childrenNumMessages.size() == 1); validationEngine.unregisterAll(); }
public void test() throws IOException, SAXException { InputStream in = this.getClass().getResourceAsStream("/validation.xml"); ValidatorResources resources = new ValidatorResources(in); Form form = resources.getForm(Locale.JAPANESE, "MemberForm"); for(Field field : (List<Field>)form.getFields()) { FormItem formItem = new FormItem(); formItem.setId(field.getProperty()); formItem.setLabel(field.getKey()); for(String depend : (List<String>)field.getDependencyList()) { String value = null; if(StringUtils.equals(depend, "required")) { value="true"; } else { value=field.getVarValue(depend); } if(StringUtils.equals(depend, "maxlength")) { depend = "maxLength"; } Validation validation = new Validation(depend, value); formItem.getValidations().addValidation(validation); } System.out.println(formItem); validationEngine.register(formItem); } Map<String, Object> formValues = new HashMap<String, Object>(); formValues.put("hasSpouse", true); formValues.put("familyName", "01234567890"); formValues.put("childrenNum", ""); formValues.put("genderCd", false); Map<String, List<String>> messages = validationEngine.exec(formValues); List<String> childrenNumMessages = messages.get("childrenNum"); Assert.assertTrue("配偶者がありのときは、子供の人数が必須になる", childrenNumMessages != null && childrenNumMessages.size() == 1); validationEngine.unregisterAll(); }
diff --git a/src/main/java/org/apache/tapestry5/contextmenu/services/ContextMenuModule.java b/src/main/java/org/apache/tapestry5/contextmenu/services/ContextMenuModule.java index 0f4d001..2c325f9 100644 --- a/src/main/java/org/apache/tapestry5/contextmenu/services/ContextMenuModule.java +++ b/src/main/java/org/apache/tapestry5/contextmenu/services/ContextMenuModule.java @@ -1,29 +1,29 @@ package org.apache.tapestry5.contextmenu.services; import org.apache.tapestry5.contextmenu.internal.GridCellWorker; import org.apache.tapestry5.ioc.Configuration; import org.apache.tapestry5.ioc.OrderedConfiguration; import org.apache.tapestry5.ioc.annotations.Contribute; import org.apache.tapestry5.ioc.annotations.Primary; import org.apache.tapestry5.services.ComponentClassResolver; import org.apache.tapestry5.services.Environment; import org.apache.tapestry5.services.LibraryMapping; import org.apache.tapestry5.services.transform.ComponentClassTransformWorker2; public class ContextMenuModule { @Contribute(ComponentClassResolver.class) public void provideComponentClassResolver(Configuration<LibraryMapping> configuration) { configuration.add(new LibraryMapping("core", "org.apache.tapestry5.contextmenu")); } @Contribute(ComponentClassTransformWorker2.class) @Primary public static void provideGridCellWorker( OrderedConfiguration<ComponentClassTransformWorker2> configuration, Environment environment) { - configuration.add("GridCellWorker", new GridCellWorker(environment), "after:*"); + configuration.add("GridCellWorker", new GridCellWorker(environment)); } }
true
true
public static void provideGridCellWorker( OrderedConfiguration<ComponentClassTransformWorker2> configuration, Environment environment) { configuration.add("GridCellWorker", new GridCellWorker(environment), "after:*"); }
public static void provideGridCellWorker( OrderedConfiguration<ComponentClassTransformWorker2> configuration, Environment environment) { configuration.add("GridCellWorker", new GridCellWorker(environment)); }
diff --git a/wikAPIdia-loader/src/main/java/org/wikapidia/dao/load/PhraseLoader.java b/wikAPIdia-loader/src/main/java/org/wikapidia/dao/load/PhraseLoader.java index e57542d4..be8d3f58 100644 --- a/wikAPIdia-loader/src/main/java/org/wikapidia/dao/load/PhraseLoader.java +++ b/wikAPIdia-loader/src/main/java/org/wikapidia/dao/load/PhraseLoader.java @@ -1,69 +1,69 @@ package org.wikapidia.dao.load; import org.apache.commons.cli.*; import org.wikapidia.conf.Configuration; import org.wikapidia.conf.ConfigurationException; import org.wikapidia.conf.DefaultOptionBuilder; import org.wikapidia.core.WikapidiaException; import org.wikapidia.core.cmd.Env; import org.wikapidia.core.dao.DaoException; import org.wikapidia.phrases.NormalizedStringPruner; import org.wikapidia.phrases.PhraseAnalyzer; import org.wikapidia.phrases.SimplePruner; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** */ public class PhraseLoader { private static final Logger LOG = Logger.getLogger(PhraseLoader.class.getName()); public static void main(String args[]) throws ClassNotFoundException, SQLException, IOException, ConfigurationException, WikapidiaException, DaoException { Options options = new Options(); options.addOption( new DefaultOptionBuilder() .hasArg() .isRequired() .withLongOpt("analyzer") .withDescription("the name of the phrase analyzer to use") .create("p")); Env.addStandardOptions(options); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println( "Invalid option usage: " + e.getMessage()); new HelpFormatter().printHelp("ConceptLoader", options); return; } Map<String, String> confOverrides = new HashMap<String, String>(); confOverrides.put("phrases.loading", "true"); Env env = new Env(cmd, confOverrides); - String name = cmd.getOptionValue("n"); + String name = cmd.getOptionValue("p"); PhraseAnalyzer analyzer = env.getConfigurator().get(PhraseAnalyzer.class, name); LOG.log(Level.INFO, "LOADING PHRASE CORPUS FOR " + name); Configuration c = env.getConfiguration(); int minCount = c.get().getInt("phrases.pruning.minCount"); int maxRank = c.get().getInt("phrases.pruning.maxRank"); double minFraction = c.get().getDouble("phrases.pruning.minFraction"); analyzer.loadCorpus( env.getLanguages(), new NormalizedStringPruner(minCount, maxRank, minFraction), new SimplePruner<Integer>(minCount, maxRank, minFraction) ); LOG.log(Level.INFO, "DONE"); } }
true
true
public static void main(String args[]) throws ClassNotFoundException, SQLException, IOException, ConfigurationException, WikapidiaException, DaoException { Options options = new Options(); options.addOption( new DefaultOptionBuilder() .hasArg() .isRequired() .withLongOpt("analyzer") .withDescription("the name of the phrase analyzer to use") .create("p")); Env.addStandardOptions(options); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println( "Invalid option usage: " + e.getMessage()); new HelpFormatter().printHelp("ConceptLoader", options); return; } Map<String, String> confOverrides = new HashMap<String, String>(); confOverrides.put("phrases.loading", "true"); Env env = new Env(cmd, confOverrides); String name = cmd.getOptionValue("n"); PhraseAnalyzer analyzer = env.getConfigurator().get(PhraseAnalyzer.class, name); LOG.log(Level.INFO, "LOADING PHRASE CORPUS FOR " + name); Configuration c = env.getConfiguration(); int minCount = c.get().getInt("phrases.pruning.minCount"); int maxRank = c.get().getInt("phrases.pruning.maxRank"); double minFraction = c.get().getDouble("phrases.pruning.minFraction"); analyzer.loadCorpus( env.getLanguages(), new NormalizedStringPruner(minCount, maxRank, minFraction), new SimplePruner<Integer>(minCount, maxRank, minFraction) ); LOG.log(Level.INFO, "DONE"); }
public static void main(String args[]) throws ClassNotFoundException, SQLException, IOException, ConfigurationException, WikapidiaException, DaoException { Options options = new Options(); options.addOption( new DefaultOptionBuilder() .hasArg() .isRequired() .withLongOpt("analyzer") .withDescription("the name of the phrase analyzer to use") .create("p")); Env.addStandardOptions(options); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println( "Invalid option usage: " + e.getMessage()); new HelpFormatter().printHelp("ConceptLoader", options); return; } Map<String, String> confOverrides = new HashMap<String, String>(); confOverrides.put("phrases.loading", "true"); Env env = new Env(cmd, confOverrides); String name = cmd.getOptionValue("p"); PhraseAnalyzer analyzer = env.getConfigurator().get(PhraseAnalyzer.class, name); LOG.log(Level.INFO, "LOADING PHRASE CORPUS FOR " + name); Configuration c = env.getConfiguration(); int minCount = c.get().getInt("phrases.pruning.minCount"); int maxRank = c.get().getInt("phrases.pruning.maxRank"); double minFraction = c.get().getDouble("phrases.pruning.minFraction"); analyzer.loadCorpus( env.getLanguages(), new NormalizedStringPruner(minCount, maxRank, minFraction), new SimplePruner<Integer>(minCount, maxRank, minFraction) ); LOG.log(Level.INFO, "DONE"); }
diff --git a/src/com/reeltwo/jumble/fast/JumbleTestSuite.java b/src/com/reeltwo/jumble/fast/JumbleTestSuite.java index dd27510..baf09ae 100644 --- a/src/com/reeltwo/jumble/fast/JumbleTestSuite.java +++ b/src/com/reeltwo/jumble/fast/JumbleTestSuite.java @@ -1,205 +1,205 @@ package com.reeltwo.jumble.fast; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.Test; import junit.framework.TestCase; /** * A test suite which runs tests in order and inverts the result. Remembers the * tests that failed last time and does those first. * * @author Tin * @version $Revision$ */ public class JumbleTestSuite extends FlatTestSuite { /** Cache of previously failed tests */ private FailedTestMap mCache; /** Order of tests */ private TestOrder mOrder; /** Mutated class */ private String mClass; /** Mutated method */ private String mMethod; /** Mutation Point */ private int mMethodRelativeMutationPoint; /** Should we dump extra output from the test runs? */ private boolean mVerbose; /** * Constructs test suite from the given order of tests. * * @param order * the order to run the tests in * @throws ClassNotFoundException * if <CODE>order</CODE> is malformed. */ public JumbleTestSuite(ClassLoader loader, TestOrder order, FailedTestMap cache, String mutatedClass, String mutatedMethod, int mutationPoint, boolean verbose) throws ClassNotFoundException { super(); mCache = cache; mOrder = order; mClass = mutatedClass; mMethod = mutatedMethod; mVerbose = verbose; mMethodRelativeMutationPoint = mutationPoint; // Create the test suites from the order String[] classNames = mOrder.getTestClasses(); for (int i = 0; i < classNames.length; i++) { addTestSuite(loader.loadClass(classNames[i])); } // for (int i = 0; i < testCount(); i++) { // System.err.println("Test " + i + " is " + ((TestCase)testAt(i)).getName()); // } // System.err.println("Total tests: " + testCount()); } /** * Runs the tests returning the result as a string. If any of the individual * tests fail then the run is aborted and "PASS" is returned (recall with a * mutation we expect the test to fail). If all tests run correctly then * "FAIL" is returned. */ protected String run() { final JUnitTestResult result = new JUnitTestResult(); Test[] tests = getOrder(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream newOut = new PrintStream(bos); PrintStream oldOut = System.out; for (int i = 0; i < testCount(); i++) { TestCase t = (TestCase) tests[i]; System.setOut(newOut); try { bos.reset(); t.run(result); } finally { System.setOut(oldOut); } if (mVerbose) { // Debugging to allow seeing how the tests picked up the mutation String rstr = result.toString(); if (rstr.length() > 0) { System.err.println(result); } if (bos.size() > 0) { System.err.println("CAPTURED OUTPUT: " + bos.toString()); } System.err.flush(); try { Thread.sleep(50); } catch (InterruptedException e) { ; // Don't care } } if (result.errorCount() > 0 || result.failureCount() > 0) { return "PASS: " + t.getName(); } if (result.shouldStop()) { break; } } // all tests passed, this mutation is a problem, report it as a FAIL return "FAIL"; } /** * Run the tests for the given class. * * @param order the order in which to run the tests. * @param cache the cache * @param mutatedClassName the name of the class which was mutated * @param mutatedMethodName the name of the method which was mutated * @param relativeMutationPoint the mutation point location relative to the mutated method * @see TestOrder */ public static String run(ClassLoader loader, TestOrder order, FailedTestMap cache, String mutatedClassName, String mutatedMethodName, int relativeMutationPoint, boolean verbose) { try { ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(loader); try { JumbleTestSuite suite = new JumbleTestSuite(loader, order, cache, mutatedClassName, mutatedMethodName, relativeMutationPoint, verbose); String ret = suite.run(); return ret; } finally { Thread.currentThread().setContextClassLoader(oldLoader); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); // Should have been picked up before now. } } /** * Basically separates out the tests for the current method so that they are * run first. Still keeps them in the same order. * * @return array of tests in the order of timing but the ones that failed * previously get run first. */ private Test[] getOrder() { Test first = null; String firstTestName = null; Set frontTestNames = new HashSet(); if (mCache != null) { firstTestName = mCache.getLastFailure(mClass, mMethod, mMethodRelativeMutationPoint); frontTestNames = mCache.getFailedTests(mClass, mMethod); } - List front = new ArrayList(); - List back = new ArrayList(); + List<TestCase> front = new ArrayList<TestCase>(); + List<TestCase> back = new ArrayList<TestCase>(); for (int i = 0; i < testCount(); i++) { int indx = mOrder.getTestIndex(i); TestCase curTest = (TestCase) testAt(indx); - if (first != null && curTest.getName().equals(firstTestName)) { + if (first == null && curTest.getName().equals(firstTestName)) { first = curTest; } else if (frontTestNames.contains(curTest.getName())) { front.add(curTest); } else { back.add(curTest); } } Test[] ret = new Test[testCount()]; int i; if (first == null) { i = 0; } else { i = 1; ret[0] = first; } for (int j = 0; j < front.size(); j++) { ret[i] = (Test) front.get(j); i++; } for (int j = 0; j < back.size(); j++) { ret[i] = (Test) back.get(j); i++; } return ret; } }
false
true
private Test[] getOrder() { Test first = null; String firstTestName = null; Set frontTestNames = new HashSet(); if (mCache != null) { firstTestName = mCache.getLastFailure(mClass, mMethod, mMethodRelativeMutationPoint); frontTestNames = mCache.getFailedTests(mClass, mMethod); } List front = new ArrayList(); List back = new ArrayList(); for (int i = 0; i < testCount(); i++) { int indx = mOrder.getTestIndex(i); TestCase curTest = (TestCase) testAt(indx); if (first != null && curTest.getName().equals(firstTestName)) { first = curTest; } else if (frontTestNames.contains(curTest.getName())) { front.add(curTest); } else { back.add(curTest); } } Test[] ret = new Test[testCount()]; int i; if (first == null) { i = 0; } else { i = 1; ret[0] = first; } for (int j = 0; j < front.size(); j++) { ret[i] = (Test) front.get(j); i++; } for (int j = 0; j < back.size(); j++) { ret[i] = (Test) back.get(j); i++; } return ret; }
private Test[] getOrder() { Test first = null; String firstTestName = null; Set frontTestNames = new HashSet(); if (mCache != null) { firstTestName = mCache.getLastFailure(mClass, mMethod, mMethodRelativeMutationPoint); frontTestNames = mCache.getFailedTests(mClass, mMethod); } List<TestCase> front = new ArrayList<TestCase>(); List<TestCase> back = new ArrayList<TestCase>(); for (int i = 0; i < testCount(); i++) { int indx = mOrder.getTestIndex(i); TestCase curTest = (TestCase) testAt(indx); if (first == null && curTest.getName().equals(firstTestName)) { first = curTest; } else if (frontTestNames.contains(curTest.getName())) { front.add(curTest); } else { back.add(curTest); } } Test[] ret = new Test[testCount()]; int i; if (first == null) { i = 0; } else { i = 1; ret[0] = first; } for (int j = 0; j < front.size(); j++) { ret[i] = (Test) front.get(j); i++; } for (int j = 0; j < back.size(); j++) { ret[i] = (Test) back.get(j); i++; } return ret; }
diff --git a/debug/org.eclipse.ptp.debug.core/src/org/eclipse/ptp/debug/internal/core/aif/AIFValueArray.java b/debug/org.eclipse.ptp.debug.core/src/org/eclipse/ptp/debug/internal/core/aif/AIFValueArray.java index b69262a48..5b6e44407 100644 --- a/debug/org.eclipse.ptp.debug.core/src/org/eclipse/ptp/debug/internal/core/aif/AIFValueArray.java +++ b/debug/org.eclipse.ptp.debug.core/src/org/eclipse/ptp/debug/internal/core/aif/AIFValueArray.java @@ -1,44 +1,44 @@ /******************************************************************************* * Copyright (c) 2005 The Regents of the University of California. * This material was produced under U.S. Government contract W-7405-ENG-36 * for Los Alamos National Laboratory, which is operated by the University * of California for the U.S. Department of Energy. The U.S. Government has * rights to use, reproduce, and distribute this software. NEITHER THE * GOVERNMENT NOR THE UNIVERSITY MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified * to produce derivative works, such modified software should be clearly marked, * so as not to confuse it with the version available from LANL. * * Additionally, 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 * * LA-CC 04-115 *******************************************************************************/ package org.eclipse.ptp.debug.internal.core.aif; import org.eclipse.ptp.debug.core.aif.IAIFValue; /** * @author Clement chu * */ public class AIFValueArray implements IAIFValue { private IAIFValue[] vals; public AIFValueArray(IAIFValue[] vals) { this.vals = vals; } public String toString() { - String output = ""; + String output = "["; for (int i=0; i<vals.length; i++) { if (vals[i] != null) { + if (i > 0) + output += ", "; output += vals[i].toString(); - if (i < vals.length - 1) - output += " "; } } - return output; + return output + "]"; } }
false
true
public String toString() { String output = ""; for (int i=0; i<vals.length; i++) { if (vals[i] != null) { output += vals[i].toString(); if (i < vals.length - 1) output += " "; } } return output; }
public String toString() { String output = "["; for (int i=0; i<vals.length; i++) { if (vals[i] != null) { if (i > 0) output += ", "; output += vals[i].toString(); } } return output + "]"; }
diff --git a/src/java/soc/game/SOCBoard.java b/src/java/soc/game/SOCBoard.java index a984a5e8..d7446582 100644 --- a/src/java/soc/game/SOCBoard.java +++ b/src/java/soc/game/SOCBoard.java @@ -1,1752 +1,1759 @@ /** * Java Settlers - An online multiplayer version of the game Settlers of Catan * Copyright (C) 2003 Robert S. Thomas * Portions of this file Copyright (C) 2007-2009 Jeremy D. Monin <[email protected]> * * 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. * * The author of this program can be reached at [email protected] **/ package soc.game; import java.io.Serializable; import java.util.Enumeration; import java.util.Hashtable; import java.util.Random; import java.util.Vector; /** * This is a representation of the board in Settlers of Catan. * Board initialization is done in {@link #makeNewBoard(Hashtable)}; that method * has some internal comments on structures, coordinates, layout and values. *<P> * Other methods to examine the board: {@link SOCGame#getPlayersOnHex(int)}, * {@link SOCGame#putPiece(SOCPlayingPiece)}, etc. *<P> * <b>Coordinate system,</b> as seen in appendix A of Robert S Thomas' dissertation: *<P> * <b>Hexes</b> (represented as coordinate of their centers), * <b>nodes</b> (corners of hexes; where settlements/cities are placed), * and <b>edges</b> (between nodes; where roads are placed), * share the same grid of coordinates. * Each hex is 2 units wide, in a 2-D coordinate system. * The first axis runs northwest to southeast; the second runs southwest to northeast. * Having six sides, hexes run in a straight line west to east, separated by vertical edges; * both coordinates increase along a west-to-east line. *<P> * Current coordinate encoding: ({@link #BOARD_ENCODING_ORIGINAL}) *<BR> * All coordinates are encoded as two-digit hex integers, one digit per axis (thus 00 to FF). * The center hex is encoded as 77; see the dissertation PDF's appendix for diagrams. * Unfortunately this format means the board can't be expanded without changing its * encoding, which is used across the network. *<P> * @author Robert S Thomas */ public class SOCBoard implements Serializable, Cloneable { // // Hex types // /** Desert; lowest-numbered hex type */ public static final int DESERT_HEX = 0; public static final int CLAY_HEX = 1; public static final int ORE_HEX = 2; public static final int SHEEP_HEX = 3; public static final int WHEAT_HEX = 4; /** Wood; highest-numbered land hex type (also MAX_LAND_HEX, MAX_ROBBER_HEX) */ public static final int WOOD_HEX = 5; /** Highest-numbered land hex type (currently wood; also currently MAX_ROBBER_HEX) @since 1.1.07 */ public static final int MAX_LAND_HEX = 5; // Also MAX_ROBBER_HEX /** Water hex; higher-numbered than all land hex types */ public static final int WATER_HEX = 6; /** Misc (3-for-1) port type; lowest-numbered port-hextype integer */ public static final int MISC_PORT_HEX = 7; // Must be first port-hextype integer public static final int CLAY_PORT_HEX = 8; public static final int ORE_PORT_HEX = 9; public static final int SHEEP_PORT_HEX = 10; public static final int WHEAT_PORT_HEX = 11; /** Wood port type; highest-numbered port-hextype integer */ public static final int WOOD_PORT_HEX = 12; // Must be last port-hextype integer /** Misc (3-for-1) port; lowest-numbered port-type integer */ public static final int MISC_PORT = 0; // Must be first port-type integer; must be 0 (hardcoded in places here) /** Clay port type */ public static final int CLAY_PORT = 1; /** Ore port type */ public static final int ORE_PORT = 2; /** Sheep port type */ public static final int SHEEP_PORT = 3; /** Wheat port type */ public static final int WHEAT_PORT = 4; /** Wood port type; highest-numbered port-type integer */ public static final int WOOD_PORT = 5; // Must be last port-type integer /** Highest-numbered hex type which may hold a robber: highest land: {@link #MAX_LAND_HEX}. */ public static final int MAX_ROBBER_HEX = MAX_LAND_HEX; /** * Board Encoding fields begin here * ------------------------------------------------------------------------------------ */ /** * Original format (1) for {@link #getBoardEncodingFormat()}: * Hexadecimal 0x00 to 0xFF along 2 diagonal axes. * Coordinate range on each axis is 0 to 15 decimal. In hex:<pre> * Hexes: 11 to DD * Nodes: 01 or 10, to FE or EF * Edges: 00 to EE </pre> *<P> * See the Dissertation PDF for details. * @since 1.1.06 */ public static final int BOARD_ENCODING_ORIGINAL = 1; /** * Size of board in coordinates (not in number of hexes across). * Default size per BOARD_ENCODING_ORIGINAL is: <pre> * Hexes: 11 to DD * Nodes: 01 or 10, to FE or EF * Edges: 00 to EE </pre> * @since 1.1.06 */ private int boardWidth, boardHeight; /** * The encoding format of board coordinates, * or {@link #BOARD_ENCODING_ORIGINAL} (default, original). * The board size determines the required encoding format. *<UL> *<LI> 1 - Original format: hexadecimal 0x00 to 0xFF. * Coordinate range is 0 to 15 (in decimal). *</UL> * @since 1.1.06 */ private int boardEncodingFormat; /** * Board Encoding fields end here * ------------------------------------------------------------------------------------ */ /** * largest coordinate value for a hex, in the current encoding. */ public static final int MAXHEX = 0xDD; // See also hardcoded checks in {@link #getAdjacentHexes_AddIfOK. /** * smallest coordinate value for a hex, in the current encoding. */ public static final int MINHEX = 0x11; /** * largest coordinate value for an edge, in the current encoding */ public static final int MAXEDGE = 0xCC; /** * smallest coordinate value for an edge, in the current encoding */ public static final int MINEDGE = 0x22; /** * largest coordinate value for a node, in the current encoding */ public static final int MAXNODE = 0xDC; /** * smallest coordinate value for a node, in the current encoding */ public static final int MINNODE = 0x23; /** * largest coordinate value for a node plus one, in the current encoding */ public static final int MAXNODEPLUSONE = MAXNODE + 1; /*************************************** * Hex data array, one element per water or land (or port, which is special water) hex. * Each element's coordinates on the board ("hex ID") is {@link #numToHexID}[i]. * Each element's value encodes hex type and (if a * port) facing. (Facing is defined just below.) *<P> * Key to the hexLayout[] values: <pre> 0 : desert {@link #DESERT_HEX} 1 : clay {@link #CLAY_HEX} 2 : ore {@link #ORE_HEX} 3 : sheep {@link #SHEEP_HEX} 4 : wheat {@link #WHEAT_HEX} 5 : wood {@link #WOOD_HEX} also: {@link #MAX_LAND_HEX} {@link #MAX_ROBBER_HEX} 6 : water {@link #WATER_HEX} 7 : misc port ("3:1") facing 1 ({@link #MISC_PORT} in {@link #getPortTypeFromHex(int)}) 8 : misc port facing 2 9 : misc port facing 3 10 : misc port facing 4 11 : misc port facing 5 12 : misc port facing 6 16+: non-misc ("2:1") encoded port </pre> Non-misc ports are encoded here in binary like this:<pre> (port facing, 1-6) (kind of port) \--> [0 0 0][0 0 0 0] <--/ </pre> Kind of port:<pre> 1 : clay ({@link #CLAY_PORT} in {@link #getPortTypeFromHex(int)}) 2 : ore {@link #ORE_PORT} 3 : sheep {@link #SHEEP_PORT} 4 : wheat {@link #WHEAT_PORT} 5 : wood {@link #WOOD_PORT} </pre> <em>Port facing</em> is the edge of the port's hex that contains 2 nodes where player can build a port settlement/city; facing is a number 1-6. <pre> 6___ ___1 \/\/ / \ 5___| |___2 | | \ / 4___/\/\___3 </pre> @see #getHexTypeFromNumber(int) * **/ private int[] hexLayout = // initially all WATER_HEX { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, WATER_HEX }; /** * Map of dice rolls to values in {@link #numberLayout} */ private int[] boardNum2Num = { -1, -1, 0, 1, 2, 3, 4, -1, 5, 6, 7, 8, 9 }; /** * Map of values in {@link #numberLayout} to dice rolls:<pre> * -1 : robber * 0 : 2 * 1 : 3 * 2 : 4 * 3 : 5 * 4 : 6 * 5 : 8 (7 is skipped) * 6 : 9 * 7 : 10 * 8 : 11 * 9 : 12 </pre> */ private int[] num2BoardNum = { 2, 3, 4, 5, 6, 8, 9, 10, 11, 12 }; /* private int numberLayout[] = { -1, -1, -1, -1, -1, 8, 9, 6, -1, -1, 2, 4, 3, 7, -1, -1, -1, 1, 8, 2, 5, -1, -1, 5, 7, 6, 1, -1, -1, 3, 0, 4, -1, -1, -1, -1, -1 }; */ /** Dice number from hex numbers. * For number value mapping, see {@link #num2BoardNum}. * For coord mapping, see {@link #numToHexID} */ private int[] numberLayout = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; /** Hex coordinates ("IDs") of each hex number (number is index within * {@link #hexLayout}). The hexes in here are the board's land hexes and also * the surrounding ring of water/port hexes. * @see #hexIDtoNum * @see #nodesOnBoard */ private int[] numToHexID = { 0x17, 0x39, 0x5B, 0x7D, 0x15, 0x37, 0x59, 0x7B, 0x9D, 0x13, 0x35, 0x57, 0x79, 0x9B, 0xBD, 0x11, 0x33, 0x55, 0x77, 0x99, 0xBB, 0xDD, 0x31, 0x53, 0x75, 0x97, 0xB9, 0xDB, 0x51, 0x73, 0x95, 0xB7, 0xD9, 0x71, 0x93, 0xB5, 0xD7 }; /** * translate hex ID (hex coordinate) to an array index within {@link #hexLayout}. * The non-zero values in here are the board's land hexes and also the surrounding * ring of water/port hexes. Initialized in constructor. Length is >= {@link #MAXHEX}. * A value of 0 means the ID isn't a valid hex number on the board, because 0x00 * isn't a valid hex coordinate. * @see #numToHexID */ private int[] hexIDtoNum; /** * offset to add to hex coord to get all node coords * -- see getAdjacent* methods instead * private int[] hexNodes = { 0x01, 0x12, 0x21, 0x10, -0x01, -0x10 }; */ /** * offset of all hexes adjacent to a node * -- @see #getAdjacentHexesToNode(int) instead * private int[] nodeToHex = { -0x21, 0x01, -0x01, -0x10, 0x10, -0x12 }; */ /** * the hex coordinate that the robber is in; placed on desert in constructor */ private int robberHex; /** * where the ports are; coordinates per port type. * Indexes are port types, {@link #MISC_PORT} to {@link #WOOD_PORT}. */ private Vector[] ports; /** * pieces on the board; Vector of SOCPlayingPiece */ private Vector pieces; /** * roads on the board; Vector of SOCPlayingPiece */ private Vector roads; /** * settlements on the board; Vector of SOCPlayingPiece */ private Vector settlements; /** * cities on the board; Vector of SOCPlayingPiece */ private Vector cities; /** * random number generator */ private Random rand = new Random(); /** * a list of nodes on the board; key is node's Integer coordinate, value is Boolean. * nodes on outer edges of surrounding water/ports are not on the board. * See dissertation figure A.2. */ protected Hashtable nodesOnBoard; /** * Create a new Settlers of Catan Board */ public SOCBoard() { boardWidth = 0x10; boardHeight = 0x10; boardEncodingFormat = BOARD_ENCODING_ORIGINAL; // See javadoc of boardEncodingFormat robberHex = -1; // Soon placed on desert /** * generic counter */ int i; /** * initialize the pieces vectors */ pieces = new Vector(96); roads = new Vector(60); settlements = new Vector(20); cities = new Vector(16); /** * initialize the port vector */ ports = new Vector[6]; ports[MISC_PORT] = new Vector(8); for (i = CLAY_PORT; i <= WOOD_PORT; i++) { ports[i] = new Vector(2); } /** * initialize the hexIDtoNum array; * see dissertation figure A.1 for coordinates */ hexIDtoNum = new int[0xEE]; // Length must be >= MAXHEX for (i = 0; i < 0xEE; i++) { hexIDtoNum[i] = 0; // 0 means off the board (assumes coordinate 0x00 is never a valid hex) } // Sets up the board as land hexes with surrounding ring of water/port hexes. initHexIDtoNumAux(0x17, 0x7D, 0); // Top horizontal row: 4 hexes across initHexIDtoNumAux(0x15, 0x9D, 4); // Next horiz row: 5 hexes initHexIDtoNumAux(0x13, 0xBD, 9); // Next: 6 initHexIDtoNumAux(0x11, 0xDD, 15); // Middle horizontal row: 7 initHexIDtoNumAux(0x31, 0xDB, 22); // Next: 6 initHexIDtoNumAux(0x51, 0xD9, 28); // Next: 5 initHexIDtoNumAux(0x71, 0xD7, 33); // Bottom horizontal row: 4 hexes across nodesOnBoard = new Hashtable(); /** * initialize the list of nodes on the board; * nodes on outer edges of surrounding water/ports are not on the board. * See dissertation figure A.2. */ Boolean t = new Boolean(true); for (i = 0x27; i <= 0x8D; i += 0x11) // Top horizontal row: each top corner across 3 hexes { nodesOnBoard.put(new Integer(i), t); } for (i = 0x25; i <= 0xAD; i += 0x11) // Next: each top corner of row of 4 / bottom corner of the top 3 hexes { nodesOnBoard.put(new Integer(i), t); } for (i = 0x23; i <= 0xCD; i += 0x11) // Next: top corners of middle row of 5 hexes { nodesOnBoard.put(new Integer(i), t); } for (i = 0x32; i <= 0xDC; i += 0x11) // Next: bottom corners of middle row of 5 hexes { nodesOnBoard.put(new Integer(i), t); } for (i = 0x52; i <= 0xDA; i += 0x11) // Bottom corners of row of 4 / top corners of the bottom 3 hexes { nodesOnBoard.put(new Integer(i), t); } for (i = 0x72; i <= 0xD8; i += 0x11) // Last horizontal row: each bottom corner across 3 hexes { nodesOnBoard.put(new Integer(i), t); } } /** * Auxiliary method for initializing part of the hexIDtoNum array. * Between begin and end, increment coord by 0x22, which moves 1 hex to the right. * See dissertation figure A.1. * @param begin Beginning of coordinate range * @param end Ending coordinate - same horizontal row as begin * @param num Number to assign to first {@link #hexIDtoNum}[] within this coordinate range; * corresponds to hex's index ("hex number") within {@link #hexLayout}. */ private final void initHexIDtoNumAux(int begin, int end, int num) { int i; for (i = begin; i <= end; i += 0x22) { hexIDtoNum[i] = num; num++; } } /** * Shuffle the hex tiles and layout a board * @param opts {@link SOCGameOption Game options}, which may affect board layout, or null */ public void makeNewBoard(Hashtable opts) { int[] landHex = { 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; int[] portHex = { 0, 0, 0, 0, 1, 2, 3, 4, 5 }; int[] number = { 3, 0, 4, 1, 5, 7, 6, 9, 8, 2, 5, 7, 6, 2, 3, 4, 1, 8 }; int[] numPath = { 29, 30, 31, 26, 20, 13, 7, 6, 5, 10, 16, 23, 24, 25, 19, 12, 11, 17, 18 }; SOCGameOption opt_breakClumps = (opts != null ? (SOCGameOption)opts.get("BC") : null); // shuffle and place the land hexes, numbers, and robber: // sets robberHex, contents of hexLayout[] and numberLayout[]. // Also checks vs game option BC: Break up clumps of # or more same-type hexes/ports makeNewBoard_placeHexes (landHex, numPath, number, opt_breakClumps); // shuffle the ports, and check vs game option BC makeNewBoard_shufflePorts (portHex, opt_breakClumps); // place the ports (hex numbers and facing) within hexLayout; // for their corresponding node coordinates, // see comments just below. placePort(portHex[0], 0, 3); // Facing 3 is SE: see hexLayout's javadoc. // 0 is hex number (index within hexLayout) placePort(portHex[1], 2, 4); // Facing 4 is SW, at hex number 2 placePort(portHex[2], 8, 4); // SW placePort(portHex[3], 21, 5); // W placePort(portHex[4], 32, 6); // NW placePort(portHex[5], 35, 6); // NW placePort(portHex[6], 33, 1); // NE placePort(portHex[7], 22, 2); // E placePort(portHex[8], 9, 2); // E // fill out the ports[] vectors with node coordinates // where a trade port can be placed ports[portHex[0]].addElement(new Integer(0x27)); // Port touches the upper-left land hex, port facing SE ports[portHex[0]].addElement(new Integer(0x38)); // [port's hex is NW of the upper-left land hex] ports[portHex[1]].addElement(new Integer(0x5A)); // Touches middle land hex of top row, port facing SW ports[portHex[1]].addElement(new Integer(0x6B)); // [The port hex itself is 2 to right of prev port hex.] ports[portHex[2]].addElement(new Integer(0x9C)); // Touches rightmost land hex of row above middle, SW ports[portHex[2]].addElement(new Integer(0xAD)); ports[portHex[3]].addElement(new Integer(0xCD)); // Rightmost of middle-row land hex, W ports[portHex[3]].addElement(new Integer(0xDC)); ports[portHex[4]].addElement(new Integer(0xC9)); // Rightmost land hex below middle, NW ports[portHex[4]].addElement(new Integer(0xDA)); ports[portHex[5]].addElement(new Integer(0xA5)); // Port touches middle hex of bottom row, facing NW ports[portHex[5]].addElement(new Integer(0xB6)); // [The port hex itself is 2 to right of next port hex.] ports[portHex[6]].addElement(new Integer(0x72)); // Leftmost of bottom row, NE ports[portHex[6]].addElement(new Integer(0x83)); ports[portHex[7]].addElement(new Integer(0x43)); // Leftmost land hex of row below middle, E ports[portHex[7]].addElement(new Integer(0x52)); ports[portHex[8]].addElement(new Integer(0x25)); // Leftmost land hex above middle, facing E ports[portHex[8]].addElement(new Integer(0x34)); } /** * For makeNewBoard, place the land hexes, number, and robber, * after shuffling landHex[]. * Sets robberHex, contents of hexLayout[] and numberLayout[]. * Also checks vs game option BC: Break up clumps of # or more same-type hexes/ports * (for land hex resource types). */ private final void makeNewBoard_placeHexes (int[] landHex, final int[] numPath, final int[] number, SOCGameOption optBC) { final boolean checkClumps = (optBC != null) && optBC.getBoolValue(); final int clumpSize = checkClumps ? optBC.getIntValue() : 0; boolean clumpsNotOK = checkClumps; do // will re-do placement until clumpsNotOK is false { // shuffle the land hexes 10x for (int j = 0; j < 10; j++) { int idx, tmp; for (int i = 0; i < landHex.length; i++) { // Swap a random card below the ith card with the ith card idx = Math.abs(rand.nextInt() % (landHex.length - i)); tmp = landHex[idx]; landHex[idx] = landHex[i]; landHex[i] = tmp; } } int cnt = 0; for (int i = 0; i < landHex.length; i++) { // place the land hexes hexLayout[numPath[i]] = landHex[i]; // place the robber on the desert if (landHex[i] == 0) { robberHex = numToHexID[numPath[i]]; numberLayout[numPath[i]] = -1; } else { // place the numbers numberLayout[numPath[i]] = number[cnt]; cnt++; } } // for(i in landHex) if (checkClumps) { /** * Depth-first search to check land hexes for resource clumps. * * Start with the set of all land hexes, and consider them 'unvisited'. * Look at each hex in the set, marking them as visited and moving * them into new subsets ("clumps") composed of adjacent hexes of the * same resource type. Build clumps by immediately visiting those adjacent * hexes, and their unvisited same-type adjacents, etc. * Once we've visited each hex, check if any clump subset's * size is larger than the allowed size. * * Pseudocode: // Using vectors to represent sets. // Sets will contain each hex's index within hexLayout. // // - clumps := new empty set (will be a vector of vectors) // At end of search, each element of this set will be // a subset (a vector) of adjacent hexes // - clumpsNotOK := false // - unvisited-set := new set (vector) of all land hexes // - iterate through unvisited-set; for each hex: // - remove this from unvisited-set // - look at its adjacent hexes of same type // assertion: they are all unvisited, because this hex was unvisited // and this is the top-level loop // - if none, done looking at this hex // - remove all adj-of-same-type from unvisited-set // - build a new clump-vector of this + all adj of same type - // - iterate through each hex in clump-vector (skip its first hex, + // - grow the clump: iterate through each hex in clump-vector (skip its first hex, // because we already have its adjacent hexes) // precondition: each hex already in the clump set, is not in unvisited-vec // - look at its adjacent unvisited hexes of same type // - if none, done looking at this hex // - remove same-type adjacents from unvisited-set // - insert them into clump-vector (will continue the iteration with them) // - add clump-vector to set-of-all-clumps // OR, immediately check its size vs clumpSize // postcondition: have visited each hex // - iterate through set-of-all-clumps // if size >= clumpSize then clumpsNotOK := true. Stop. // - read clumpsNotOK. */ // Actual code along with pseudocode: // Using vectors to represent sets. // Sets will contain each hex's index within hexLayout. // We're operating on Integer instances, which is okay because // vector methods such as contains() and remove() test obj.equals() // to determine if the Integer is a member. // (getAdjacent() returns new Integer objs with the same value // as unvisited's members.) // - unvisited-set := new set (vector) of all land hexes clumpsNotOK = false; // will set true in while-loop body Vector unvisited = new Vector(); for (int i = 0; i < landHex.length; ++i) { unvisited.addElement(new Integer(numPath[i])); } // - iterate through unvisited-set while (unvisited.size() > 0) { // for each hex: // - remove this from unvisited-set Integer hexIdxObj = (Integer) unvisited.elementAt(0); int hexIdx = hexIdxObj.intValue(); int resource = hexLayout[hexIdx]; unvisited.removeElementAt(0); // - look at its adjacent hexes of same type // assertion: they are all unvisited, because this hex was unvisited // and this is the top-level loop // - if none, done looking at this hex // - build a new clump-vector of this + all adj of same type // - remove all adj-of-same-type from unvisited-set // set of adjacent will become the clump, or be emptied completely Vector adjacent = getAdjacentHexesToHex(numToHexID[hexIdx], false); if (adjacent == null) continue; Vector clump = null; for (int i = 0; i < adjacent.size(); ++i) { Integer adjCoordObj = (Integer) adjacent.elementAt(i); int adjIdx = hexIDtoNum[adjCoordObj.intValue()]; if (resource == hexLayout[adjIdx]) { // keep this one if (clump == null) clump = new Vector(); Integer adjIdxObj = new Integer(adjIdx); clump.addElement(adjIdxObj); unvisited.remove(adjIdxObj); } } if (clump == null) continue; clump.insertElementAt(hexIdxObj, 0); // put the first hex into clump - // - iterate through each hex in clump-vector (skip its first hex, + // - grow the clump: iterate through each hex in clump-vector (skip its first hex, // because we already have its adjacent hexes) - for (int ic = 1; ic < clump.size(); ++ic) + for (int ic = 1; ic < clump.size(); ) // ++ic is within loop body, if nothing inserted { // precondition: each hex already in clump set, is not in unvisited-vec Integer chexIdxObj = (Integer) clump.elementAt(ic); int chexIdx = chexIdxObj.intValue(); // - look at its adjacent unvisited hexes of same type // - if none, done looking at this hex // - remove same-type adjacents from unvisited-set // - insert them into clump-vector // (will continue the iteration with them) Vector adjacent2 = getAdjacentHexesToHex(numToHexID[chexIdx], false); if (adjacent2 == null) + { + ++ic; continue; + } + boolean didInsert = false; for (int ia = 0; ia < adjacent2.size(); ++ia) { Integer adjCoordObj = (Integer) adjacent2.elementAt(ia); int adjIdx = hexIDtoNum[adjCoordObj.intValue()]; Integer adjIdxObj = new Integer(adjIdx); if ((resource == hexLayout[adjIdx]) && unvisited.contains(adjIdxObj)) { // keep this one clump.insertElementAt(adjIdxObj, ic); unvisited.remove(adjIdxObj); + didInsert = true; } } + if (! didInsert) + ++ic; } // for each in clump // - immediately check clump's size vs clumpSize if (clump.size() >= clumpSize) { clumpsNotOK = true; break; } } // for each in unvisited } // if (checkClumps) } while (clumpsNotOK); } // makeNewBoard_placeHexes /** * For makeNewBoard, shuffle portHex[]. * Sets no fields, only rearranges the contents of that array. * Also checks vs game option BC: Break up clumps of # or more same-type hexes/ports * (for ports, the types here are: 3-for-1, or 2-for-1). * @param portHex Contains port types, 1 per port, as they will appear in clockwise * order around the edge of the board. Must not all be the same type. * {@link #MISC_PORT} is the 3-for-1 port type value. * @param opt_breakClumps Game option "BC", or null * @throws IllegalStateException if opt_breakClumps is set, and all portHex[] elements have the same value */ private void makeNewBoard_shufflePorts(int[] portHex, SOCGameOption opt_breakClumps) throws IllegalStateException { boolean portsOK = true; do { int count, i; for (count = 0; count < 10; count++) { int idx, tmp; for (i = 1; i < portHex.length; i++) // don't swap 0 with 0! { // Swap a random card below the ith card with the ith card idx = Math.abs(rand.nextInt() % (portHex.length - i)); tmp = portHex[idx]; portHex[idx] = portHex[i]; portHex[i] = tmp; } } if ((opt_breakClumps != null) && opt_breakClumps.getBoolValue()) { // Start with port 0, and go around the circle; after that, // check type of highest-index vs 0, for wrap-around. portsOK = true; int clumpsize = opt_breakClumps.getIntValue(); boolean ptype = (0 == portHex[0]); count = 1; // # in a row for (i = 1; i < portHex.length; ++i) { if (ptype != (0 == portHex[i])) { ptype = (0 == portHex[i]); count = 1; } else { ++count; if (count >= clumpsize) portsOK = false; // don't break: need to check them all, // in case all portHex[i] are same value } } // for(i) if (ptype == (0 == portHex[0])) { // check wrap-around if (count == portHex.length) throw new IllegalStateException("portHex types all same"); if (! portsOK) continue; for (i = 0; i < portHex.length; ++i) { if (ptype != (0 == portHex[i])) { break; } else { ++count; if (count >= clumpsize) { portsOK = false; break; } } } } } // if opt("BC") } while (! portsOK); } /** * Auxiliary method for placing the port hexes, changing an element of {@link #hexLayout}. * @param port Port type; in range {@link #MISC_PORT} to {@link #WOOD_PORT}. * @param hex Hex coordinate within {@link #hexLayout} * @param face Facing of port; 1 to 6; for facing direction, see {@link #hexLayout} */ private final void placePort(int port, int hex, int face) { if (port == MISC_PORT) { // generic port == 6 + facing hexLayout[hex] = face + 6; } else { hexLayout[hex] = (face << 4) + port; } } /** * @return the hex layout; meaning of values same as {@link #hexLayout}. */ public int[] getHexLayout() { return hexLayout; } /** * @return the number layout */ public int[] getNumberLayout() { return numberLayout; } /** * @return coordinate where the robber is */ public int getRobberHex() { return robberHex; } /** * set the hexLayout * * @param hl the hex layout */ public void setHexLayout(int[] hl) { hexLayout = hl; if (hl[0] == 6) { /** * this is a blank board */ return; } /** * fill in the port node information */ ports[getPortTypeFromHex(hexLayout[0])].addElement(new Integer(0x27)); ports[getPortTypeFromHex(hexLayout[0])].addElement(new Integer(0x38)); ports[getPortTypeFromHex(hexLayout[2])].addElement(new Integer(0x5A)); ports[getPortTypeFromHex(hexLayout[2])].addElement(new Integer(0x6B)); ports[getPortTypeFromHex(hexLayout[8])].addElement(new Integer(0x9C)); ports[getPortTypeFromHex(hexLayout[8])].addElement(new Integer(0xAD)); ports[getPortTypeFromHex(hexLayout[9])].addElement(new Integer(0x25)); ports[getPortTypeFromHex(hexLayout[9])].addElement(new Integer(0x34)); ports[getPortTypeFromHex(hexLayout[21])].addElement(new Integer(0xCD)); ports[getPortTypeFromHex(hexLayout[21])].addElement(new Integer(0xDC)); ports[getPortTypeFromHex(hexLayout[22])].addElement(new Integer(0x43)); ports[getPortTypeFromHex(hexLayout[22])].addElement(new Integer(0x52)); ports[getPortTypeFromHex(hexLayout[32])].addElement(new Integer(0xC9)); ports[getPortTypeFromHex(hexLayout[32])].addElement(new Integer(0xDA)); ports[getPortTypeFromHex(hexLayout[33])].addElement(new Integer(0x72)); ports[getPortTypeFromHex(hexLayout[33])].addElement(new Integer(0x83)); ports[getPortTypeFromHex(hexLayout[35])].addElement(new Integer(0xA5)); ports[getPortTypeFromHex(hexLayout[35])].addElement(new Integer(0xB6)); } /** * @return the type of port given a hex type; * in range {@link #MISC_PORT} to {@link #WOOD_PORT} * @param hex the hex type, as in {@link #hexLayout} * @see #getHexTypeFromCoord(int) */ public int getPortTypeFromHex(int hex) { int portType = 0; if ((hex >= 7) && (hex <= 12)) { portType = 0; } else { portType = hex & 0xF; } return portType; } /** * set the number layout * * @param nl the number layout */ public void setNumberLayout(int[] nl) { numberLayout = nl; } /** * set where the robber is * * @param rh the robber hex coordinate */ public void setRobberHex(int rh) { robberHex = rh; } /** * @return the list of coordinates for a type of port; * each element is an Integer * * @param portType the type of port; * in range {@link #MISC_PORT} to {@link #WOOD_PORT}. */ public Vector getPortCoordinates(int portType) { return ports[portType]; } /** * Given a hex coordinate, return the number on that hex * * @param hex the coordinates for a hex * * @return the number on that hex, or 0 if not a hex coordinate */ public int getNumberOnHexFromCoord(int hex) { if ((hex >= 0) && (hex < hexIDtoNum.length)) return getNumberOnHexFromNumber(hexIDtoNum[hex]); else return 0; } /** * Given a hex number, return the (dice-roll) number on that hex * * @param hex the number of a hex * * @return the dice-roll number on that hex, or 0 */ public int getNumberOnHexFromNumber(int hex) { int num = numberLayout[hex]; if (num < 0) { return 0; } else { return num2BoardNum[num]; } } /** * Given a hex coordinate, return the type of hex * * @param hex the coordinates ("ID") for a hex * @return the type of hex: * Land in range {@link #CLAY_HEX} to {@link #WOOD_HEX}, * {@link #DESERT_HEX}, or {@link #MISC_PORT_HEX} for any port. * * @see #getPortTypeFromHex(int) */ public int getHexTypeFromCoord(int hex) { return getHexTypeFromNumber(hexIDtoNum[hex]); } /** * Given a hex number, return the type of hex * * @param hex the number of a hex (its index in {@link #hexLayout}, not its coordinate) * @return the type of hex: * Land in range {@link #CLAY_HEX} to {@link #WOOD_HEX}, * {@link #DESERT_HEX}, or {@link #MISC_PORT_HEX} for any port. * * @see #getPortTypeFromHex(int) */ public int getHexTypeFromNumber(int hex) { int hexType = hexLayout[hex]; if (hexType < 7) { return hexType; } else if ((hexType >= 7) && (hexType <= 12)) { return MISC_PORT_HEX; } else { switch (hexType & 7) { case 1: return CLAY_PORT_HEX; case 2: return ORE_PORT_HEX; case 3: return SHEEP_PORT_HEX; case 4: return WHEAT_PORT_HEX; case 5: return WOOD_PORT_HEX; } } return -1; } /** * put a piece on the board */ public void putPiece(SOCPlayingPiece pp) { pieces.addElement(pp); switch (pp.getType()) { case SOCPlayingPiece.ROAD: roads.addElement(pp); break; case SOCPlayingPiece.SETTLEMENT: settlements.addElement(pp); break; case SOCPlayingPiece.CITY: cities.addElement(pp); break; } } /** * remove a piece from the board */ public void removePiece(SOCPlayingPiece piece) { Enumeration pEnum = pieces.elements(); while (pEnum.hasMoreElements()) { SOCPlayingPiece p = (SOCPlayingPiece) pEnum.nextElement(); if ((piece.getType() == p.getType()) && (piece.getCoordinates() == p.getCoordinates())) { pieces.removeElement(p); switch (piece.getType()) { case SOCPlayingPiece.ROAD: roads.removeElement(p); break; case SOCPlayingPiece.SETTLEMENT: settlements.removeElement(p); break; case SOCPlayingPiece.CITY: cities.removeElement(p); break; } break; } } } /** * get the list of pieces on the board */ public Vector getPieces() { return pieces; } /** * get the list of roads */ public Vector getRoads() { return roads; } /** * get the list of settlements */ public Vector getSettlements() { return settlements; } /** * get the list of cities */ public Vector getCities() { return cities; } /** * Width of this board in coordinates (not in number of hexes across.) * For the default size, see {@link #BOARD_ENCODING_ORIGINAL}. * @since 1.1.06 */ public int getBoardWidth() { return boardWidth; } /** * Height of this board in coordinates (not in number of hexes across.) * For the default size, see {@link #BOARD_ENCODING_ORIGINAL}. * @since 1.1.06 */ public int getBoardHeight() { return boardHeight; } /** * Get the encoding format of this board (for coordinates, etc). * See the encoding constants' javadocs for more documentation. * @return board coordinate-encoding format, such as {@link #BOARD_ENCODING_ORIGINAL} * @since 1.1.06 */ public int getBoardEncodingFormat() { return boardEncodingFormat; } /** * @return the nodes that touch this edge, as a Vector of Integer coordinates */ public static Vector getAdjacentNodesToEdge(int coord) { Vector nodes = new Vector(2); int tmp; /** * if the coords are (even, even), then * the road is '|'. */ if ((((coord & 0x0F) + (coord >> 4)) % 2) == 0) { tmp = coord + 0x01; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer(tmp)); } tmp = coord + 0x10; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer(tmp)); } } else { /* otherwise the road is either '/' or '\' */ tmp = coord; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer(tmp)); } tmp = coord + 0x11; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer(tmp)); } } return nodes; } /** * @return the adjacent edges to this edge, as a Vector of Integer coordinates */ public static Vector getAdjacentEdgesToEdge(int coord) { Vector edges = new Vector(4); int tmp; /** * if the coords are (even, even), then * the road is '|'. */ if ((((coord & 0x0F) + (coord >> 4)) % 2) == 0) { tmp = coord - 0x10; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord + 0x01; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord + 0x10; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord - 0x01; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } } /** * if the coords are (even, odd), then * the road is '/'. */ else if (((coord >> 4) % 2) == 0) { tmp = coord - 0x11; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord + 0x01; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord + 0x11; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord - 0x01; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } } else { /** * otherwise the coords are (odd, even), * and the road is '\' */ tmp = coord - 0x10; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord + 0x11; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord + 0x10; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord - 0x11; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } } return edges; } /** * @return the coordinates (Integers) of the 1 to 3 hexes touching this node */ public static Vector getAdjacentHexesToNode(int coord) { Vector hexes = new Vector(3); int tmp; /** * if the coords are (even, odd), then * the node is 'Y'. */ if (((coord >> 4) % 2) == 0) { tmp = coord - 0x10; if ((tmp >= MINHEX) && (tmp <= MAXHEX)) { hexes.addElement(new Integer(tmp)); } tmp = coord + 0x10; if ((tmp >= MINHEX) && (tmp <= MAXHEX)) { hexes.addElement(new Integer(tmp)); } tmp = coord - 0x12; if ((tmp >= MINHEX) && (tmp <= MAXHEX)) { hexes.addElement(new Integer(tmp)); } } else { /** * otherwise the coords are (odd, even), * and the node is 'upside down Y'. */ tmp = coord - 0x21; if ((tmp >= MINHEX) && (tmp <= MAXHEX)) { hexes.addElement(new Integer(tmp)); } tmp = coord + 0x01; if ((tmp >= MINHEX) && (tmp <= MAXHEX)) { hexes.addElement(new Integer(tmp)); } tmp = coord - 0x01; if ((tmp >= MINHEX) && (tmp <= MAXHEX)) { hexes.addElement(new Integer(tmp)); } } return hexes; } /** * @return the edges touching this node, as a Vector of Integer coordinates */ public static Vector getAdjacentEdgesToNode(int coord) { Vector edges = new Vector(3); int tmp; /** * if the coords are (even, odd), then * the node is 'Y'. */ if (((coord >> 4) % 2) == 0) { tmp = coord - 0x11; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord - 0x01; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } } else { /** * otherwise the coords are (odd, even), * and the EDGE is 'upside down Y'. */ tmp = coord - 0x10; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } tmp = coord - 0x11; if ((tmp >= MINEDGE) && (tmp <= MAXEDGE)) { edges.addElement(new Integer(tmp)); } } return edges; } /** * @return the nodes adjacent to this node, as a Vector of Integer coordinates */ public static Vector getAdjacentNodesToNode(int coord) { Vector nodes = new Vector(3); int tmp; tmp = coord - 0x11; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer(tmp)); } tmp = coord + 0x11; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer(tmp)); } /** * if the coords are (even, odd), then * the node is 'Y'. */ if (((coord >> 4) % 2) == 0) { tmp = (coord + 0x10) - 0x01; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer((coord + 0x10) - 0x01)); } } else { /** * otherwise the coords are (odd, even), * and the node is 'upside down Y'. */ tmp = coord - 0x10 + 0x01; if ((tmp >= MINNODE) && (tmp <= MAXNODE)) { nodes.addElement(new Integer(coord - 0x10 + 0x01)); } } return nodes; } /** * Make a list of all valid hex coordinates (or, only land) adjacent to this hex. * Valid coordinates are those within the board data structures, * within {@link #MINHEX} to {@link #MAXHEX}, and valid according to {@link #hexIDtoNum}. *<P> * Coordinate offsets, from Dissertation figure A.4 - adjacent hexes to hex:<PRE> * (-2,0) (0,+2) * * (-2,-2) x (+2,+2) * * (0,-2) (+2,0) </PRE> * * @param hexCoord Coordinate ("ID") of this hex * @param includeWater Should water hexes be returned (not only land ones)? * Port hexes are water hexes. * @return the hexes that touch this hex, as a Vector of Integer coordinates, * or null if none are adjacent (will <b>not</b> return a 0-length vector) * @since 1.1.07 */ public Vector getAdjacentHexesToHex(final int hexCoord, final boolean includeWater) { Vector hexes = new Vector(); getAdjacentHexes_AddIfOK(hexes, includeWater, hexCoord, -2, 0); // NW (northwest) getAdjacentHexes_AddIfOK(hexes, includeWater, hexCoord, 0, +2); // NE getAdjacentHexes_AddIfOK(hexes, includeWater, hexCoord, -2, -2); // W getAdjacentHexes_AddIfOK(hexes, includeWater, hexCoord, +2, +2); // E getAdjacentHexes_AddIfOK(hexes, includeWater, hexCoord, 0, -2); // SW getAdjacentHexes_AddIfOK(hexes, includeWater, hexCoord, 2, 0); // SE if (hexes.size() > 0) return hexes; else return null; } /** * Check one possible coordinate for getAdjacentHexesToHex. * @param addTo the list we're building of hexes that touch this hex, as a Vector of Integer coordinates. * @param includeWater Should water hexes be returned (not only land ones)? * Port hexes are water hexes. * @param hexCoord Coordinate ("ID") of this hex * @param d1 Delta along axis 1 * @param d2 Delta along axis 2 * @since 1.1.07 */ private final void getAdjacentHexes_AddIfOK (Vector addTo, final boolean includeWater, int hexCoord, final int d1, final int d2) { int a1 = ((hexCoord & 0xF0) >> 4) + d1; // Axis-1 coordinate int a2 = (hexCoord & 0x0F) + d2; // Axis-2 coordinate if ((a1 < 1) || (a1 > 0xD) || (a2 < 1) || (a2 > 0xD)) return; // <--- Off the board in one coordinate ---- hexCoord += (d1 << 4); // this shift works for both + and - (confirmed by testing) hexCoord += d2; if ((hexCoord >= MINHEX) && (hexCoord <= MAXHEX) && (hexIDtoNum[hexCoord] > 0) && (includeWater || hexLayout[hexIDtoNum[hexCoord]] <= MAX_LAND_HEX)) addTo.addElement(new Integer(hexCoord)); } /** * If there's a settlement or city at this node, find it. * * @param nodeCoord Location coordinate (as returned by SOCBoardPanel.findNode) * @return Settlement or city or null */ public SOCPlayingPiece settlementAtNode(int nodeCoord) { Enumeration pEnum = pieces.elements(); while (pEnum.hasMoreElements()) { SOCPlayingPiece p = (SOCPlayingPiece) pEnum.nextElement(); int typ = p.getType(); if ((nodeCoord == p.getCoordinates()) && ( (typ == SOCPlayingPiece.SETTLEMENT) || (typ == SOCPlayingPiece.CITY) )) { return p; // <-- Early return: Found it --- } } return null; } /** * If there's a road placed at this node, find it. * * @param edgeCoord Location coordinate (as returned by SOCBoardPanel.findEdge) * @return road or null */ public SOCPlayingPiece roadAtEdge(int edgeCoord) { Enumeration pEnum = roads.elements(); while (pEnum.hasMoreElements()) { SOCPlayingPiece p = (SOCPlayingPiece) pEnum.nextElement(); if (edgeCoord == p.getCoordinates()) { return p; // <-- Early return: Found it --- } } return null; } /** * @return true if the node is on the board * @param node Node coordinate */ public boolean isNodeOnBoard(int node) { return nodesOnBoard.containsKey(new Integer(node)); } /** * @return a string representation of a node coordinate */ public String nodeCoordToString(int node) { String str; Enumeration hexes = getAdjacentHexesToNode(node).elements(); Integer hex = (Integer) hexes.nextElement(); int number = getNumberOnHexFromCoord(hex.intValue()); if (number == 0) { str = "-"; } else { str = Integer.toString(number); } while (hexes.hasMoreElements()) { hex = (Integer) hexes.nextElement(); number = getNumberOnHexFromCoord(hex.intValue()); if (number == 0) { str += "/-"; } else { str += ("/" + number); } } return str; } /** * @return a string representation of an edge coordinate */ public String edgeCoordToString(int edge) { String str; int number1; int number2; /** * if the coords are (even, even), then * the road is '|'. */ if ((((edge & 0x0F) + (edge >> 4)) % 2) == 0) { number1 = getNumberOnHexFromCoord(edge - 0x11); number2 = getNumberOnHexFromCoord(edge + 0x11); } /** * if the coords are (even, odd), then * the road is '/'. */ else if (((edge >> 4) % 2) == 0) { number1 = getNumberOnHexFromCoord(edge - 0x10); number2 = getNumberOnHexFromCoord(edge + 0x10); } else { /** * otherwise the coords are (odd, even), * and the road is '\' */ number1 = getNumberOnHexFromCoord(edge - 0x01); number2 = getNumberOnHexFromCoord(edge + 0x01); } str = number1 + "/" + number2; return str; } }
false
true
private final void makeNewBoard_placeHexes (int[] landHex, final int[] numPath, final int[] number, SOCGameOption optBC) { final boolean checkClumps = (optBC != null) && optBC.getBoolValue(); final int clumpSize = checkClumps ? optBC.getIntValue() : 0; boolean clumpsNotOK = checkClumps; do // will re-do placement until clumpsNotOK is false { // shuffle the land hexes 10x for (int j = 0; j < 10; j++) { int idx, tmp; for (int i = 0; i < landHex.length; i++) { // Swap a random card below the ith card with the ith card idx = Math.abs(rand.nextInt() % (landHex.length - i)); tmp = landHex[idx]; landHex[idx] = landHex[i]; landHex[i] = tmp; } } int cnt = 0; for (int i = 0; i < landHex.length; i++) { // place the land hexes hexLayout[numPath[i]] = landHex[i]; // place the robber on the desert if (landHex[i] == 0) { robberHex = numToHexID[numPath[i]]; numberLayout[numPath[i]] = -1; } else { // place the numbers numberLayout[numPath[i]] = number[cnt]; cnt++; } } // for(i in landHex) if (checkClumps) { /** * Depth-first search to check land hexes for resource clumps. * * Start with the set of all land hexes, and consider them 'unvisited'. * Look at each hex in the set, marking them as visited and moving * them into new subsets ("clumps") composed of adjacent hexes of the * same resource type. Build clumps by immediately visiting those adjacent * hexes, and their unvisited same-type adjacents, etc. * Once we've visited each hex, check if any clump subset's * size is larger than the allowed size. * * Pseudocode: // Using vectors to represent sets. // Sets will contain each hex's index within hexLayout. // // - clumps := new empty set (will be a vector of vectors) // At end of search, each element of this set will be // a subset (a vector) of adjacent hexes // - clumpsNotOK := false // - unvisited-set := new set (vector) of all land hexes // - iterate through unvisited-set; for each hex: // - remove this from unvisited-set // - look at its adjacent hexes of same type // assertion: they are all unvisited, because this hex was unvisited // and this is the top-level loop // - if none, done looking at this hex // - remove all adj-of-same-type from unvisited-set // - build a new clump-vector of this + all adj of same type // - iterate through each hex in clump-vector (skip its first hex, // because we already have its adjacent hexes) // precondition: each hex already in the clump set, is not in unvisited-vec // - look at its adjacent unvisited hexes of same type // - if none, done looking at this hex // - remove same-type adjacents from unvisited-set // - insert them into clump-vector (will continue the iteration with them) // - add clump-vector to set-of-all-clumps // OR, immediately check its size vs clumpSize // postcondition: have visited each hex // - iterate through set-of-all-clumps // if size >= clumpSize then clumpsNotOK := true. Stop. // - read clumpsNotOK. */ // Actual code along with pseudocode: // Using vectors to represent sets. // Sets will contain each hex's index within hexLayout. // We're operating on Integer instances, which is okay because // vector methods such as contains() and remove() test obj.equals() // to determine if the Integer is a member. // (getAdjacent() returns new Integer objs with the same value // as unvisited's members.) // - unvisited-set := new set (vector) of all land hexes clumpsNotOK = false; // will set true in while-loop body Vector unvisited = new Vector(); for (int i = 0; i < landHex.length; ++i) { unvisited.addElement(new Integer(numPath[i])); } // - iterate through unvisited-set while (unvisited.size() > 0) { // for each hex: // - remove this from unvisited-set Integer hexIdxObj = (Integer) unvisited.elementAt(0); int hexIdx = hexIdxObj.intValue(); int resource = hexLayout[hexIdx]; unvisited.removeElementAt(0); // - look at its adjacent hexes of same type // assertion: they are all unvisited, because this hex was unvisited // and this is the top-level loop // - if none, done looking at this hex // - build a new clump-vector of this + all adj of same type // - remove all adj-of-same-type from unvisited-set // set of adjacent will become the clump, or be emptied completely Vector adjacent = getAdjacentHexesToHex(numToHexID[hexIdx], false); if (adjacent == null) continue; Vector clump = null; for (int i = 0; i < adjacent.size(); ++i) { Integer adjCoordObj = (Integer) adjacent.elementAt(i); int adjIdx = hexIDtoNum[adjCoordObj.intValue()]; if (resource == hexLayout[adjIdx]) { // keep this one if (clump == null) clump = new Vector(); Integer adjIdxObj = new Integer(adjIdx); clump.addElement(adjIdxObj); unvisited.remove(adjIdxObj); } } if (clump == null) continue; clump.insertElementAt(hexIdxObj, 0); // put the first hex into clump // - iterate through each hex in clump-vector (skip its first hex, // because we already have its adjacent hexes) for (int ic = 1; ic < clump.size(); ++ic) { // precondition: each hex already in clump set, is not in unvisited-vec Integer chexIdxObj = (Integer) clump.elementAt(ic); int chexIdx = chexIdxObj.intValue(); // - look at its adjacent unvisited hexes of same type // - if none, done looking at this hex // - remove same-type adjacents from unvisited-set // - insert them into clump-vector // (will continue the iteration with them) Vector adjacent2 = getAdjacentHexesToHex(numToHexID[chexIdx], false); if (adjacent2 == null) continue; for (int ia = 0; ia < adjacent2.size(); ++ia) { Integer adjCoordObj = (Integer) adjacent2.elementAt(ia); int adjIdx = hexIDtoNum[adjCoordObj.intValue()]; Integer adjIdxObj = new Integer(adjIdx); if ((resource == hexLayout[adjIdx]) && unvisited.contains(adjIdxObj)) { // keep this one clump.insertElementAt(adjIdxObj, ic); unvisited.remove(adjIdxObj); } } } // for each in clump // - immediately check clump's size vs clumpSize if (clump.size() >= clumpSize) { clumpsNotOK = true; break; } } // for each in unvisited } // if (checkClumps) } while (clumpsNotOK); } // makeNewBoard_placeHexes
private final void makeNewBoard_placeHexes (int[] landHex, final int[] numPath, final int[] number, SOCGameOption optBC) { final boolean checkClumps = (optBC != null) && optBC.getBoolValue(); final int clumpSize = checkClumps ? optBC.getIntValue() : 0; boolean clumpsNotOK = checkClumps; do // will re-do placement until clumpsNotOK is false { // shuffle the land hexes 10x for (int j = 0; j < 10; j++) { int idx, tmp; for (int i = 0; i < landHex.length; i++) { // Swap a random card below the ith card with the ith card idx = Math.abs(rand.nextInt() % (landHex.length - i)); tmp = landHex[idx]; landHex[idx] = landHex[i]; landHex[i] = tmp; } } int cnt = 0; for (int i = 0; i < landHex.length; i++) { // place the land hexes hexLayout[numPath[i]] = landHex[i]; // place the robber on the desert if (landHex[i] == 0) { robberHex = numToHexID[numPath[i]]; numberLayout[numPath[i]] = -1; } else { // place the numbers numberLayout[numPath[i]] = number[cnt]; cnt++; } } // for(i in landHex) if (checkClumps) { /** * Depth-first search to check land hexes for resource clumps. * * Start with the set of all land hexes, and consider them 'unvisited'. * Look at each hex in the set, marking them as visited and moving * them into new subsets ("clumps") composed of adjacent hexes of the * same resource type. Build clumps by immediately visiting those adjacent * hexes, and their unvisited same-type adjacents, etc. * Once we've visited each hex, check if any clump subset's * size is larger than the allowed size. * * Pseudocode: // Using vectors to represent sets. // Sets will contain each hex's index within hexLayout. // // - clumps := new empty set (will be a vector of vectors) // At end of search, each element of this set will be // a subset (a vector) of adjacent hexes // - clumpsNotOK := false // - unvisited-set := new set (vector) of all land hexes // - iterate through unvisited-set; for each hex: // - remove this from unvisited-set // - look at its adjacent hexes of same type // assertion: they are all unvisited, because this hex was unvisited // and this is the top-level loop // - if none, done looking at this hex // - remove all adj-of-same-type from unvisited-set // - build a new clump-vector of this + all adj of same type // - grow the clump: iterate through each hex in clump-vector (skip its first hex, // because we already have its adjacent hexes) // precondition: each hex already in the clump set, is not in unvisited-vec // - look at its adjacent unvisited hexes of same type // - if none, done looking at this hex // - remove same-type adjacents from unvisited-set // - insert them into clump-vector (will continue the iteration with them) // - add clump-vector to set-of-all-clumps // OR, immediately check its size vs clumpSize // postcondition: have visited each hex // - iterate through set-of-all-clumps // if size >= clumpSize then clumpsNotOK := true. Stop. // - read clumpsNotOK. */ // Actual code along with pseudocode: // Using vectors to represent sets. // Sets will contain each hex's index within hexLayout. // We're operating on Integer instances, which is okay because // vector methods such as contains() and remove() test obj.equals() // to determine if the Integer is a member. // (getAdjacent() returns new Integer objs with the same value // as unvisited's members.) // - unvisited-set := new set (vector) of all land hexes clumpsNotOK = false; // will set true in while-loop body Vector unvisited = new Vector(); for (int i = 0; i < landHex.length; ++i) { unvisited.addElement(new Integer(numPath[i])); } // - iterate through unvisited-set while (unvisited.size() > 0) { // for each hex: // - remove this from unvisited-set Integer hexIdxObj = (Integer) unvisited.elementAt(0); int hexIdx = hexIdxObj.intValue(); int resource = hexLayout[hexIdx]; unvisited.removeElementAt(0); // - look at its adjacent hexes of same type // assertion: they are all unvisited, because this hex was unvisited // and this is the top-level loop // - if none, done looking at this hex // - build a new clump-vector of this + all adj of same type // - remove all adj-of-same-type from unvisited-set // set of adjacent will become the clump, or be emptied completely Vector adjacent = getAdjacentHexesToHex(numToHexID[hexIdx], false); if (adjacent == null) continue; Vector clump = null; for (int i = 0; i < adjacent.size(); ++i) { Integer adjCoordObj = (Integer) adjacent.elementAt(i); int adjIdx = hexIDtoNum[adjCoordObj.intValue()]; if (resource == hexLayout[adjIdx]) { // keep this one if (clump == null) clump = new Vector(); Integer adjIdxObj = new Integer(adjIdx); clump.addElement(adjIdxObj); unvisited.remove(adjIdxObj); } } if (clump == null) continue; clump.insertElementAt(hexIdxObj, 0); // put the first hex into clump // - grow the clump: iterate through each hex in clump-vector (skip its first hex, // because we already have its adjacent hexes) for (int ic = 1; ic < clump.size(); ) // ++ic is within loop body, if nothing inserted { // precondition: each hex already in clump set, is not in unvisited-vec Integer chexIdxObj = (Integer) clump.elementAt(ic); int chexIdx = chexIdxObj.intValue(); // - look at its adjacent unvisited hexes of same type // - if none, done looking at this hex // - remove same-type adjacents from unvisited-set // - insert them into clump-vector // (will continue the iteration with them) Vector adjacent2 = getAdjacentHexesToHex(numToHexID[chexIdx], false); if (adjacent2 == null) { ++ic; continue; } boolean didInsert = false; for (int ia = 0; ia < adjacent2.size(); ++ia) { Integer adjCoordObj = (Integer) adjacent2.elementAt(ia); int adjIdx = hexIDtoNum[adjCoordObj.intValue()]; Integer adjIdxObj = new Integer(adjIdx); if ((resource == hexLayout[adjIdx]) && unvisited.contains(adjIdxObj)) { // keep this one clump.insertElementAt(adjIdxObj, ic); unvisited.remove(adjIdxObj); didInsert = true; } } if (! didInsert) ++ic; } // for each in clump // - immediately check clump's size vs clumpSize if (clump.size() >= clumpSize) { clumpsNotOK = true; break; } } // for each in unvisited } // if (checkClumps) } while (clumpsNotOK); } // makeNewBoard_placeHexes
diff --git a/awsy-data-generator/Dumper.java b/awsy-data-generator/Dumper.java index 10f0377..5789aad 100644 --- a/awsy-data-generator/Dumper.java +++ b/awsy-data-generator/Dumper.java @@ -1,70 +1,70 @@ import java.io.InputStreamReader; import java.io.Reader; import java.math.BigInteger; import java.util.Map; import java.util.TreeMap; import com.staktrace.util.conv.json.JsonArray; import com.staktrace.util.conv.json.JsonObject; import com.staktrace.util.conv.json.JsonReader; public class Dumper { private final Map<String, Long> _data; Dumper( Reader in ) throws Exception { JsonObject data = new JsonReader( in ).readObject(); _data = toMap( data ); _data.put( "explicit/heap-unclassified", calculateHeapUnclassified( data ) ); } private void add( Map<String, Long> map, String path, long value ) { Long old = map.get( path ); if (old == null) { map.put( path, value ); } else { map.put( path, value + old ); } } private Map<String, Long> toMap( JsonObject memDump ) { Map<String, Long> map = new TreeMap<String, Long>(); JsonArray reports = (JsonArray)memDump.getValue( "reports" ); for (int i = reports.size() - 1; i >= 0; i--) { JsonObject report = (JsonObject)reports.getValue( i ); if (( (BigInteger)report.getValue( "units" ) ).intValue() != 0) { continue; } String path = (String)report.getValue( "path" ); long value = ( (BigInteger)report.getValue( "amount" ) ).longValue(); add( map, path, value ); } return map; } private long calculateHeapUnclassified( JsonObject memDump ) { long knownHeap = 0; JsonArray reports = (JsonArray)memDump.getValue( "reports" ); for (int i = reports.size() - 1; i >= 0; i--) { JsonObject report = (JsonObject)reports.getValue( i ); String path = (String)report.getValue( "path" ); if (path.startsWith( "explicit/" ) && ( (BigInteger)report.getValue( "units" ) ).intValue() == 0 && ( (BigInteger)report.getValue( "kind" ) ).intValue() == 1) { - knownHeap += _data.get( path ); + knownHeap += ( (BigInteger)report.getValue( "amount" ) ).longValue(); } } return _data.get( "heap-allocated" ) - knownHeap; } public void dumpData( String prefix ) { for (String path : _data.keySet()) { System.out.println( prefix + path ); System.out.println( _data.get( path ) ); } } public static void main( String[] args ) throws Exception { new Dumper( new InputStreamReader( System.in ) ).dumpData( args[0] ); } }
true
true
private long calculateHeapUnclassified( JsonObject memDump ) { long knownHeap = 0; JsonArray reports = (JsonArray)memDump.getValue( "reports" ); for (int i = reports.size() - 1; i >= 0; i--) { JsonObject report = (JsonObject)reports.getValue( i ); String path = (String)report.getValue( "path" ); if (path.startsWith( "explicit/" ) && ( (BigInteger)report.getValue( "units" ) ).intValue() == 0 && ( (BigInteger)report.getValue( "kind" ) ).intValue() == 1) { knownHeap += _data.get( path ); } } return _data.get( "heap-allocated" ) - knownHeap; }
private long calculateHeapUnclassified( JsonObject memDump ) { long knownHeap = 0; JsonArray reports = (JsonArray)memDump.getValue( "reports" ); for (int i = reports.size() - 1; i >= 0; i--) { JsonObject report = (JsonObject)reports.getValue( i ); String path = (String)report.getValue( "path" ); if (path.startsWith( "explicit/" ) && ( (BigInteger)report.getValue( "units" ) ).intValue() == 0 && ( (BigInteger)report.getValue( "kind" ) ).intValue() == 1) { knownHeap += ( (BigInteger)report.getValue( "amount" ) ).longValue(); } } return _data.get( "heap-allocated" ) - knownHeap; }
diff --git a/usermanagement/hibernate/src/main/java/woko/ext/usermanagement/hibernate/HibernateUserManager.java b/usermanagement/hibernate/src/main/java/woko/ext/usermanagement/hibernate/HibernateUserManager.java index 995642fe..eb642471 100644 --- a/usermanagement/hibernate/src/main/java/woko/ext/usermanagement/hibernate/HibernateUserManager.java +++ b/usermanagement/hibernate/src/main/java/woko/ext/usermanagement/hibernate/HibernateUserManager.java @@ -1,103 +1,103 @@ package woko.ext.usermanagement.hibernate; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import woko.ext.usermanagement.core.DatabaseUserManager; import woko.ext.usermanagement.core.User; import woko.hibernate.HibernateStore; import woko.persistence.ListResultIterator; import woko.persistence.ResultIterator; import java.util.ArrayList; import java.util.List; public class HibernateUserManager extends DatabaseUserManager { private final HibernateStore hibernateStore; private final Class<? extends User> userClass; public HibernateUserManager(HibernateStore hibernateStore) { this(hibernateStore, HbUser.class); } public HibernateUserManager(HibernateStore hibernateStore, Class<? extends User> userClass) { this.hibernateStore = hibernateStore; this.userClass = userClass; } public Class<? extends User> getUserClass() { return userClass; } public HibernateStore getHibernateStore() { return hibernateStore; } @Override public User getUserByUsername(String username) { Session s = hibernateStore.getSession(); List l = s.createCriteria(getUserClass()).add(Restrictions.eq("username", username)).list(); if (l.size()==0) { return null; } if (l.size()>1) { throw new IllegalStateException("more than 1 users with username==" + username); } return (User)l.get(0); } @Override public ResultIterator<User> listUsers(Integer start, Integer limit) { // TODO invoke store "list" Session s = hibernateStore.getSession(); Criteria crit = s.createCriteria(getUserClass()); int st = -1; if (start!=null && start!=-1) { crit.setFirstResult(start); st = start; } int lm = -1; if (limit!=null && limit!=-1) { crit.setMaxResults(limit); lm = limit; } @SuppressWarnings("unchecked") List<User> l = (List<User>)crit.list(); // second request (count) String query = new StringBuilder("select count(*) from ").append(getUserClass().getSimpleName()).toString(); Long count = (Long)s.createQuery(query).list().get(0); return new ListResultIterator<User>(l, st, lm, count.intValue()); } @Override protected User createUser(String username, String password, List<String> roles) { Session session = hibernateStore.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); try { User u = getUserByUsername(username); if (u==null) { User user = getUserClass().newInstance(); user.setUsername(username); user.setPassword(encodePassword(password)); ArrayList<String> rolesCopy = new ArrayList<String>(roles); user.setRoles(rolesCopy); hibernateStore.save(user); tx.commit(); return user; } tx.commit(); return null; } catch(Exception e) { tx.rollback(); - return null; + throw new RuntimeException(e); } finally { if (session.isOpen()) { session.close(); } } } }
true
true
protected User createUser(String username, String password, List<String> roles) { Session session = hibernateStore.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); try { User u = getUserByUsername(username); if (u==null) { User user = getUserClass().newInstance(); user.setUsername(username); user.setPassword(encodePassword(password)); ArrayList<String> rolesCopy = new ArrayList<String>(roles); user.setRoles(rolesCopy); hibernateStore.save(user); tx.commit(); return user; } tx.commit(); return null; } catch(Exception e) { tx.rollback(); return null; } finally { if (session.isOpen()) { session.close(); } } }
protected User createUser(String username, String password, List<String> roles) { Session session = hibernateStore.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); try { User u = getUserByUsername(username); if (u==null) { User user = getUserClass().newInstance(); user.setUsername(username); user.setPassword(encodePassword(password)); ArrayList<String> rolesCopy = new ArrayList<String>(roles); user.setRoles(rolesCopy); hibernateStore.save(user); tx.commit(); return user; } tx.commit(); return null; } catch(Exception e) { tx.rollback(); throw new RuntimeException(e); } finally { if (session.isOpen()) { session.close(); } } }
diff --git a/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker2.java b/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker2.java index f94b37583..675112062 100644 --- a/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker2.java +++ b/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker2.java @@ -1,396 +1,398 @@ package com.badlogic.gdx.tools.imagepacker; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; /** @author Nathan Sweet */ public class TexturePacker2 { private final Settings settings; private final MaxRectsPacker maxRectsPacker; private final ImageProcessor imageProcessor; public TexturePacker2 (File rootDir, Settings settings) { this.settings = settings; if (settings.pot) { if (settings.maxWidth != MathUtils.nextPowerOfTwo(settings.maxWidth)) throw new RuntimeException("If pot is true, maxWidth must be a power of two: " + settings.maxWidth); if (settings.maxHeight != MathUtils.nextPowerOfTwo(settings.maxHeight)) throw new RuntimeException("If pot is true, maxHeight must be a power of two: " + settings.maxHeight); } maxRectsPacker = new MaxRectsPacker(settings); imageProcessor = new ImageProcessor(rootDir, settings); } public void addImage (File file) { imageProcessor.addImage(file); } public void pack (File outputDir, String packFileName) { outputDir.mkdirs(); if (packFileName.indexOf('.') == -1) packFileName += ".atlas"; Array<Page> pages = maxRectsPacker.pack(imageProcessor.getImages()); writeImages(outputDir, pages, packFileName); try { writePackFile(outputDir, pages, packFileName); } catch (IOException ex) { throw new RuntimeException("Error writing pack file.", ex); } } private void writeImages (File outputDir, Array<Page> pages, String packFileName) { String imageName = packFileName; int dotIndex = imageName.lastIndexOf('.'); if (dotIndex != -1) imageName = imageName.substring(0, dotIndex); int fileIndex = 0; for (Page page : pages) { int width = page.width, height = page.height; int paddingX = settings.paddingX; int paddingY = settings.paddingY; if (settings.duplicatePadding) { paddingX /= 2; paddingY /= 2; } width -= settings.paddingX; height -= settings.paddingY; if (settings.edgePadding) { page.x = paddingX; page.y = paddingY; width += paddingX * 2; height += paddingY * 2; } if (settings.pot) { width = MathUtils.nextPowerOfTwo(width); height = MathUtils.nextPowerOfTwo(height); } + width = Math.max(settings.minWidth, width); + height = Math.max(settings.minHeight, height); File outputFile; while (true) { outputFile = new File(outputDir, imageName + (fileIndex++ == 0 ? "" : fileIndex) + "." + settings.outputFormat); if (!outputFile.exists()) break; } page.imageName = outputFile.getName(); BufferedImage canvas = new BufferedImage(width, height, getBufferedImageType(settings.format)); Graphics2D g = (Graphics2D)canvas.getGraphics(); System.out.println("Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile); for (Rect rect : page.outputRects) { int rectX = page.x + rect.x, rectY = page.y + page.height - rect.y - rect.height; if (rect.rotated) { g.translate(rectX, rectY); g.rotate(-90 * MathUtils.degreesToRadians); g.translate(-rectX, -rectY); g.translate(-(rect.height - settings.paddingY), 0); } BufferedImage image = rect.image; if (settings.duplicatePadding) { int amountX = settings.paddingX / 2; int amountY = settings.paddingY / 2; int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); // Copy corner pixels to fill corners of the padding. g.drawImage(image, rectX - amountX, rectY - amountY, rectX, rectY, 0, 0, 1, 1, null); g.drawImage(image, rectX + imageWidth, rectY - amountY, rectX + imageWidth + amountX, rectY, 0, 0, 1, 1, null); g.drawImage(image, rectX - amountX, rectY + imageHeight, rectX, rectY + imageHeight + amountY, 0, 0, 1, 1, null); g.drawImage(image, rectX + imageWidth, rectY + imageHeight, rectX + imageWidth + amountX, rectY + imageHeight + amountY, 0, 0, 1, 1, null); // Copy edge pixels into padding. g.drawImage(image, rectX, rectY - amountY, rectX + imageWidth, rectY, 0, 0, imageWidth, 1, null); g.drawImage(image, rectX, rectY + imageHeight, rectX + imageWidth, rectY + imageHeight + amountY, 0, imageHeight - 1, imageWidth, imageHeight, null); g.drawImage(image, rectX - amountX, rectY, rectX, rectY + imageHeight, 0, 0, 1, imageHeight, null); g.drawImage(image, rectX + imageWidth, rectY, rectX + imageWidth + amountX, rectY + imageHeight, imageWidth - 1, 0, imageWidth, imageHeight, null); } g.drawImage(image, rectX, rectY, null); if (rect.rotated) { g.translate(rect.height - settings.paddingY, 0); g.translate(rectX, rectY); g.rotate(90 * MathUtils.degreesToRadians); g.translate(-rectX, -rectY); } if (settings.debug) { g.setColor(Color.magenta); g.drawRect(rectX, rectY, rect.width - settings.paddingX - 1, rect.height - settings.paddingY - 1); } } if (settings.debug) { g.setColor(Color.magenta); g.drawRect(0, 0, width - 1, height - 1); } try { if (settings.outputFormat.equalsIgnoreCase("jpg")) { Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter)writers.next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(settings.jpegQuality); ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile); writer.setOutput(ios); writer.write(null, new IIOImage(canvas, null, null), param); } else ImageIO.write(canvas, "png", outputFile); } catch (IOException ex) { throw new RuntimeException("Error writing file: " + outputFile, ex); } } } private void writePackFile (File outputDir, Array<Page> pages, String packFileName) throws IOException { File packFile = new File(outputDir, packFileName); FileWriter writer = new FileWriter(packFile, true); for (Page page : pages) { writer.write("\n" + page.imageName + "\n"); writer.write("format: " + settings.format + "\n"); writer.write("filter: " + settings.filterMin + "," + settings.filterMag + "\n"); writer.write("repeat: " + getRepeatValue() + "\n"); for (Rect rect : page.outputRects) { writeRect(writer, page, rect); for (Rect alias : rect.aliases) { alias.setSize(rect); writeRect(writer, page, alias); } } } writer.close(); } private void writeRect (FileWriter writer, Page page, Rect rect) throws IOException { writer.write(rect.name + "\n"); writer.write(" rotate: " + rect.rotated + "\n"); writer.write(" xy: " + (page.x + rect.x) + ", " + (page.y + page.height - rect.height - rect.y) + "\n"); writer.write(" size: " + rect.image.getWidth() + ", " + rect.image.getHeight() + "\n"); if (rect.splits != null) { writer .write(" split: " + rect.splits[0] + ", " + rect.splits[1] + ", " + rect.splits[2] + ", " + rect.splits[3] + "\n"); } writer.write(" orig: " + rect.originalWidth + ", " + rect.originalHeight + "\n"); writer.write(" offset: " + rect.offsetX + ", " + (rect.originalHeight - rect.image.getHeight() - rect.offsetY) + "\n"); writer.write(" index: " + rect.index + "\n"); } private String getRepeatValue () { if (settings.wrapX == TextureWrap.Repeat && settings.wrapY == TextureWrap.Repeat) return "xy"; if (settings.wrapX == TextureWrap.Repeat && settings.wrapY == TextureWrap.ClampToEdge) return "x"; if (settings.wrapX == TextureWrap.ClampToEdge && settings.wrapY == TextureWrap.Repeat) return "y"; return "none"; } private int getBufferedImageType (Format format) { switch (settings.format) { case RGBA8888: case RGBA4444: return BufferedImage.TYPE_INT_ARGB; case RGB565: case RGB888: return BufferedImage.TYPE_INT_RGB; case Alpha: return BufferedImage.TYPE_BYTE_GRAY; default: throw new RuntimeException("Unsupported format: " + settings.format); } } /** @author Nathan Sweet */ static class Page { public String imageName; public Array<Rect> outputRects, remainingRects; public float occupancy; public int x, y, width, height; } /** @author Nathan Sweet */ static class Rect { public String name; public BufferedImage image; public int offsetX, offsetY, originalWidth, originalHeight; public int x, y, width, height; public int index; public boolean rotated; public ArrayList<Rect> aliases = new ArrayList(); public int[] splits; public boolean canRotate = true; int score1, score2; Rect (BufferedImage source, int left, int top, int newWidth, int newHeight) { image = new BufferedImage(source.getColorModel(), source.getRaster().createWritableChild(left, top, newWidth, newHeight, 0, 0, null), source.getColorModel().isAlphaPremultiplied(), null); offsetX = left; offsetY = top; originalWidth = source.getWidth(); originalHeight = source.getHeight(); width = newWidth; height = newHeight; } Rect () { } Rect (Rect rect) { setSize(rect); } void setSize (Rect rect) { x = rect.x; y = rect.y; width = rect.width; height = rect.height; } void set (Rect rect) { name = rect.name; image = rect.image; offsetX = rect.offsetX; offsetY = rect.offsetY; originalWidth = rect.originalWidth; originalHeight = rect.originalHeight; x = rect.x; y = rect.y; width = rect.width; height = rect.height; index = rect.index; rotated = rect.rotated; aliases = rect.aliases; splits = rect.splits; canRotate = rect.canRotate; score1 = rect.score1; score2 = rect.score2; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rect other = (Rect)obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String toString () { return name + "[" + x + "," + y + " " + width + "x" + height + "]"; } } /** @author Nathan Sweet */ static public class Settings { public boolean pot = true; public int paddingX = 2, paddingY = 2; public boolean edgePadding = true; public boolean duplicatePadding = true; public boolean rotation; public int minWidth = 16, minHeight = 16; public int maxWidth = 1024, maxHeight = 1024; public boolean stripWhitespaceX, stripWhitespaceY; public int alphaThreshold; public TextureFilter filterMin = TextureFilter.Nearest, filterMag = TextureFilter.Nearest; public TextureWrap wrapX = TextureWrap.ClampToEdge, wrapY = TextureWrap.ClampToEdge; public Format format = Format.RGBA8888; public boolean alias = true; public String outputFormat = "png"; public float jpegQuality = 0.9f; public boolean ignoreBlankImages = true; public boolean fast; public boolean debug; public Settings () { } public Settings (Settings settings) { fast = settings.fast; rotation = settings.rotation; pot = settings.pot; minWidth = settings.minWidth; minHeight = settings.minHeight; maxWidth = settings.maxWidth; maxHeight = settings.maxHeight; paddingX = settings.paddingX; paddingY = settings.paddingY; edgePadding = settings.edgePadding; alphaThreshold = settings.alphaThreshold; ignoreBlankImages = settings.ignoreBlankImages; stripWhitespaceX = settings.stripWhitespaceX; stripWhitespaceY = settings.stripWhitespaceY; alias = settings.alias; format = settings.format; jpegQuality = settings.jpegQuality; outputFormat = settings.outputFormat; filterMin = settings.filterMin; filterMag = settings.filterMag; wrapX = settings.wrapX; wrapY = settings.wrapY; duplicatePadding = settings.duplicatePadding; debug = settings.debug; } } static public void process (String input, String output, String packFileName) { try { new TexturePackerFileProcessor(new Settings(), packFileName).process(new File(input), new File(output)); } catch (Exception ex) { throw new RuntimeException("Error packing files.", ex); } } static public void process (Settings settings, String input, String output, String packFileName) { try { new TexturePackerFileProcessor(settings, packFileName).process(new File(input), new File(output)); } catch (Exception ex) { throw new RuntimeException("Error packing files.", ex); } } public static void main (String[] args) throws Exception { String input = null, output = null, packFileName = "pack.atlas"; switch (args.length) { case 3: packFileName = args[2]; case 2: output = args[1]; case 1: input = args[0]; break; default: System.out.println("Usage: inputDir [outputDir] [packFileName]"); System.exit(0); } if (output == null) { File inputFile = new File(input); output = new File(inputFile.getParentFile(), inputFile.getName() + "-packed").getAbsolutePath(); } process(input, output, packFileName); } }
true
true
private void writeImages (File outputDir, Array<Page> pages, String packFileName) { String imageName = packFileName; int dotIndex = imageName.lastIndexOf('.'); if (dotIndex != -1) imageName = imageName.substring(0, dotIndex); int fileIndex = 0; for (Page page : pages) { int width = page.width, height = page.height; int paddingX = settings.paddingX; int paddingY = settings.paddingY; if (settings.duplicatePadding) { paddingX /= 2; paddingY /= 2; } width -= settings.paddingX; height -= settings.paddingY; if (settings.edgePadding) { page.x = paddingX; page.y = paddingY; width += paddingX * 2; height += paddingY * 2; } if (settings.pot) { width = MathUtils.nextPowerOfTwo(width); height = MathUtils.nextPowerOfTwo(height); } File outputFile; while (true) { outputFile = new File(outputDir, imageName + (fileIndex++ == 0 ? "" : fileIndex) + "." + settings.outputFormat); if (!outputFile.exists()) break; } page.imageName = outputFile.getName(); BufferedImage canvas = new BufferedImage(width, height, getBufferedImageType(settings.format)); Graphics2D g = (Graphics2D)canvas.getGraphics(); System.out.println("Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile); for (Rect rect : page.outputRects) { int rectX = page.x + rect.x, rectY = page.y + page.height - rect.y - rect.height; if (rect.rotated) { g.translate(rectX, rectY); g.rotate(-90 * MathUtils.degreesToRadians); g.translate(-rectX, -rectY); g.translate(-(rect.height - settings.paddingY), 0); } BufferedImage image = rect.image; if (settings.duplicatePadding) { int amountX = settings.paddingX / 2; int amountY = settings.paddingY / 2; int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); // Copy corner pixels to fill corners of the padding. g.drawImage(image, rectX - amountX, rectY - amountY, rectX, rectY, 0, 0, 1, 1, null); g.drawImage(image, rectX + imageWidth, rectY - amountY, rectX + imageWidth + amountX, rectY, 0, 0, 1, 1, null); g.drawImage(image, rectX - amountX, rectY + imageHeight, rectX, rectY + imageHeight + amountY, 0, 0, 1, 1, null); g.drawImage(image, rectX + imageWidth, rectY + imageHeight, rectX + imageWidth + amountX, rectY + imageHeight + amountY, 0, 0, 1, 1, null); // Copy edge pixels into padding. g.drawImage(image, rectX, rectY - amountY, rectX + imageWidth, rectY, 0, 0, imageWidth, 1, null); g.drawImage(image, rectX, rectY + imageHeight, rectX + imageWidth, rectY + imageHeight + amountY, 0, imageHeight - 1, imageWidth, imageHeight, null); g.drawImage(image, rectX - amountX, rectY, rectX, rectY + imageHeight, 0, 0, 1, imageHeight, null); g.drawImage(image, rectX + imageWidth, rectY, rectX + imageWidth + amountX, rectY + imageHeight, imageWidth - 1, 0, imageWidth, imageHeight, null); } g.drawImage(image, rectX, rectY, null); if (rect.rotated) { g.translate(rect.height - settings.paddingY, 0); g.translate(rectX, rectY); g.rotate(90 * MathUtils.degreesToRadians); g.translate(-rectX, -rectY); } if (settings.debug) { g.setColor(Color.magenta); g.drawRect(rectX, rectY, rect.width - settings.paddingX - 1, rect.height - settings.paddingY - 1); } } if (settings.debug) { g.setColor(Color.magenta); g.drawRect(0, 0, width - 1, height - 1); } try { if (settings.outputFormat.equalsIgnoreCase("jpg")) { Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter)writers.next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(settings.jpegQuality); ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile); writer.setOutput(ios); writer.write(null, new IIOImage(canvas, null, null), param); } else ImageIO.write(canvas, "png", outputFile); } catch (IOException ex) { throw new RuntimeException("Error writing file: " + outputFile, ex); } } }
private void writeImages (File outputDir, Array<Page> pages, String packFileName) { String imageName = packFileName; int dotIndex = imageName.lastIndexOf('.'); if (dotIndex != -1) imageName = imageName.substring(0, dotIndex); int fileIndex = 0; for (Page page : pages) { int width = page.width, height = page.height; int paddingX = settings.paddingX; int paddingY = settings.paddingY; if (settings.duplicatePadding) { paddingX /= 2; paddingY /= 2; } width -= settings.paddingX; height -= settings.paddingY; if (settings.edgePadding) { page.x = paddingX; page.y = paddingY; width += paddingX * 2; height += paddingY * 2; } if (settings.pot) { width = MathUtils.nextPowerOfTwo(width); height = MathUtils.nextPowerOfTwo(height); } width = Math.max(settings.minWidth, width); height = Math.max(settings.minHeight, height); File outputFile; while (true) { outputFile = new File(outputDir, imageName + (fileIndex++ == 0 ? "" : fileIndex) + "." + settings.outputFormat); if (!outputFile.exists()) break; } page.imageName = outputFile.getName(); BufferedImage canvas = new BufferedImage(width, height, getBufferedImageType(settings.format)); Graphics2D g = (Graphics2D)canvas.getGraphics(); System.out.println("Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile); for (Rect rect : page.outputRects) { int rectX = page.x + rect.x, rectY = page.y + page.height - rect.y - rect.height; if (rect.rotated) { g.translate(rectX, rectY); g.rotate(-90 * MathUtils.degreesToRadians); g.translate(-rectX, -rectY); g.translate(-(rect.height - settings.paddingY), 0); } BufferedImage image = rect.image; if (settings.duplicatePadding) { int amountX = settings.paddingX / 2; int amountY = settings.paddingY / 2; int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); // Copy corner pixels to fill corners of the padding. g.drawImage(image, rectX - amountX, rectY - amountY, rectX, rectY, 0, 0, 1, 1, null); g.drawImage(image, rectX + imageWidth, rectY - amountY, rectX + imageWidth + amountX, rectY, 0, 0, 1, 1, null); g.drawImage(image, rectX - amountX, rectY + imageHeight, rectX, rectY + imageHeight + amountY, 0, 0, 1, 1, null); g.drawImage(image, rectX + imageWidth, rectY + imageHeight, rectX + imageWidth + amountX, rectY + imageHeight + amountY, 0, 0, 1, 1, null); // Copy edge pixels into padding. g.drawImage(image, rectX, rectY - amountY, rectX + imageWidth, rectY, 0, 0, imageWidth, 1, null); g.drawImage(image, rectX, rectY + imageHeight, rectX + imageWidth, rectY + imageHeight + amountY, 0, imageHeight - 1, imageWidth, imageHeight, null); g.drawImage(image, rectX - amountX, rectY, rectX, rectY + imageHeight, 0, 0, 1, imageHeight, null); g.drawImage(image, rectX + imageWidth, rectY, rectX + imageWidth + amountX, rectY + imageHeight, imageWidth - 1, 0, imageWidth, imageHeight, null); } g.drawImage(image, rectX, rectY, null); if (rect.rotated) { g.translate(rect.height - settings.paddingY, 0); g.translate(rectX, rectY); g.rotate(90 * MathUtils.degreesToRadians); g.translate(-rectX, -rectY); } if (settings.debug) { g.setColor(Color.magenta); g.drawRect(rectX, rectY, rect.width - settings.paddingX - 1, rect.height - settings.paddingY - 1); } } if (settings.debug) { g.setColor(Color.magenta); g.drawRect(0, 0, width - 1, height - 1); } try { if (settings.outputFormat.equalsIgnoreCase("jpg")) { Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter)writers.next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(settings.jpegQuality); ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile); writer.setOutput(ios); writer.write(null, new IIOImage(canvas, null, null), param); } else ImageIO.write(canvas, "png", outputFile); } catch (IOException ex) { throw new RuntimeException("Error writing file: " + outputFile, ex); } } }
diff --git a/src/main/java/com/trickl/crawler/robot/xslt/XsltWorker.java b/src/main/java/com/trickl/crawler/robot/xslt/XsltWorker.java index fba29cf..974e6ec 100644 --- a/src/main/java/com/trickl/crawler/robot/xslt/XsltWorker.java +++ b/src/main/java/com/trickl/crawler/robot/xslt/XsltWorker.java @@ -1,73 +1,77 @@ /* * 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.trickl.crawler.robot.xslt; import com.trickl.crawler.api.Parser; import com.trickl.crawler.api.Task; import com.trickl.crawler.api.Worker; import java.io.IOException; import java.net.URI; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.droids.api.ManagedContentEntity; import org.apache.droids.api.Parse; import org.apache.droids.api.Protocol; import org.apache.droids.exception.DroidsException; import org.w3c.dom.Document; public class XsltWorker<T extends Task> implements Worker<T> { public final static Logger logger = Logger.getLogger(XsltWorker.class.getCanonicalName()); private final XsltDroid<T> droid; public XsltWorker(XsltDroid<T> droid) { this.droid = droid; } @Override public void execute(T task) throws DroidsException, IOException { final String userAgent = this.getClass().getCanonicalName(); logger.log(Level.FINE, "Starting {0}", userAgent); URI uri = task.getURI(); final Protocol protocol = task.getProtocol(); if (droid.getForceAllow() || protocol.isAllowed(uri)) { logger.log(Level.INFO, "Loading {0}", uri); ManagedContentEntity entity = protocol.load(uri); try { String contentType = entity.getMimeType(); logger.log(Level.FINE, "Content type {0}", contentType); if (contentType == null) { logger.info("Missing content type... can't parse..."); } else { Parser parser = droid.getParserFactory().getParser(contentType); if (parser != null) { Parse parse = parser.parse(entity, task); droid.getLinkExtractor().handle(task, (Document) parse.getData()); droid.getXslTransformHandler().handle(task, (Document) parse.getData()); } } - } finally { + } + catch (Exception ex) { + logger.log(Level.WARNING, "XSL tranformation failed. Reason: {0}", ex.getMessage()); + } + finally { entity.finish(); } } else { logger.info("Stopping processing since" + " bots are not allowed for this url."); } } }
true
true
public void execute(T task) throws DroidsException, IOException { final String userAgent = this.getClass().getCanonicalName(); logger.log(Level.FINE, "Starting {0}", userAgent); URI uri = task.getURI(); final Protocol protocol = task.getProtocol(); if (droid.getForceAllow() || protocol.isAllowed(uri)) { logger.log(Level.INFO, "Loading {0}", uri); ManagedContentEntity entity = protocol.load(uri); try { String contentType = entity.getMimeType(); logger.log(Level.FINE, "Content type {0}", contentType); if (contentType == null) { logger.info("Missing content type... can't parse..."); } else { Parser parser = droid.getParserFactory().getParser(contentType); if (parser != null) { Parse parse = parser.parse(entity, task); droid.getLinkExtractor().handle(task, (Document) parse.getData()); droid.getXslTransformHandler().handle(task, (Document) parse.getData()); } } } finally { entity.finish(); } } else { logger.info("Stopping processing since" + " bots are not allowed for this url."); } }
public void execute(T task) throws DroidsException, IOException { final String userAgent = this.getClass().getCanonicalName(); logger.log(Level.FINE, "Starting {0}", userAgent); URI uri = task.getURI(); final Protocol protocol = task.getProtocol(); if (droid.getForceAllow() || protocol.isAllowed(uri)) { logger.log(Level.INFO, "Loading {0}", uri); ManagedContentEntity entity = protocol.load(uri); try { String contentType = entity.getMimeType(); logger.log(Level.FINE, "Content type {0}", contentType); if (contentType == null) { logger.info("Missing content type... can't parse..."); } else { Parser parser = droid.getParserFactory().getParser(contentType); if (parser != null) { Parse parse = parser.parse(entity, task); droid.getLinkExtractor().handle(task, (Document) parse.getData()); droid.getXslTransformHandler().handle(task, (Document) parse.getData()); } } } catch (Exception ex) { logger.log(Level.WARNING, "XSL tranformation failed. Reason: {0}", ex.getMessage()); } finally { entity.finish(); } } else { logger.info("Stopping processing since" + " bots are not allowed for this url."); } }
diff --git a/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java b/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java index fbaa3aa30..ddfaae322 100644 --- a/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java +++ b/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java @@ -1,133 +1,142 @@ /******************************************************************************* * Copyright (c) 2006-2013 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026 * * 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: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Berlin, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.resource.generators.mopp; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.CORE_EXCEPTION; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.INPUT_STREAM; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.IO_EXCEPTION; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_CONTAINER; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_FILE; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_MARKER; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_PROGRESS_MONITOR; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE_SET; import org.emftext.sdk.OptionManager; import org.emftext.sdk.codegen.annotations.SyntaxDependent; import org.emftext.sdk.codegen.composites.JavaComposite; import org.emftext.sdk.codegen.parameters.ArtifactParameter; import org.emftext.sdk.codegen.resource.GenerationContext; import org.emftext.sdk.codegen.resource.generators.JavaBaseGenerator; import org.emftext.sdk.concretesyntax.ConcreteSyntax; import org.emftext.sdk.concretesyntax.OptionTypes; @SyntaxDependent public class TaskItemBuilderGenerator extends JavaBaseGenerator<ArtifactParameter<GenerationContext>> { @Override public void generateJavaContents(JavaComposite sc) { ConcreteSyntax syntax = getContext().getConcreteSyntax(); boolean removeEclipseDependentCode = OptionManager.INSTANCE.getBooleanOptionValue(syntax, OptionTypes.REMOVE_ECLIPSE_DEPENDENT_CODE); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); if (removeEclipseDependentCode) { sc.addComment("This class is empty because option '" + OptionTypes.REMOVE_ECLIPSE_DEPENDENT_CODE.getLiteral() + "' is set to true."); } else { sc.addJavadoc( "The " + getResourceClassName() + " is used to find task items in " + "text documents. The current implementation uses the generated lexer " + "and the TaskItemDetector to detect task items. This class is called by " + "the BuilderAdapter, which runs both this builder and the default builder " + "that is intended to be customized." ); } sc.add("public class " + getResourceClassName() + " {"); sc.addLineBreak(); if (!removeEclipseDependentCode) { addMethods(sc); } sc.add("}"); } private void addMethods(JavaComposite sc) { addBuildMethod(sc); addGetBuilderMarkerIdMethod(sc); addIsInBinFolderMethod(sc); } private void addBuildMethod(JavaComposite sc) { sc.add("public void build(" + I_FILE + " resource, " + RESOURCE_SET + " resourceSet, " + I_PROGRESS_MONITOR + " monitor) {"); sc.add("monitor.setTaskName(\"Searching for task items\");"); sc.add("new " + markerHelperClassName + "().removeAllMarkers(resource, " + I_MARKER + ".TASK);"); sc.add("if (isInBinFolder(resource)) {"); sc.add("return;"); sc.add("}"); sc.add(sc.declareArrayList("taskItems", taskItemClassName)); sc.add(taskItemDetectorClassName + " taskItemDetector = new " + taskItemDetectorClassName + "();"); + sc.add(INPUT_STREAM + " inputStream = null;"); sc.add("try {"); - sc.add(INPUT_STREAM + " inputStream = resource.getContents();"); + sc.add("inputStream = resource.getContents();"); sc.add("String charset = resource.getCharset();"); sc.add("String content = " + streamUtilClassName + ".getContent(inputStream, charset);"); sc.add(iTextScannerClassName + " lexer = new " + metaInformationClassName + "().createLexer();"); sc.add("lexer.setText(content);"); sc.addLineBreak(); sc.add(iTextTokenClassName + " nextToken = lexer.getNextToken();"); sc.add("while (nextToken != null) {"); sc.add("String text = nextToken.getText();"); sc.add("taskItems.addAll(taskItemDetector.findTaskItems(text, nextToken.getLine(), nextToken.getOffset()));"); sc.add("nextToken = lexer.getNextToken();"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("} catch (" + CORE_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("}"); sc.addLineBreak(); + sc.add("try {"); + sc.add("if (inputStream != null) {"); + sc.add("inputStream.close();"); + sc.add("}"); + sc.add("} catch (" + IO_EXCEPTION + " e) {"); + sc.addComment("Ignore this"); + sc.add("}"); + sc.addLineBreak(); sc.add("for (" + taskItemClassName + " taskItem : taskItems) {"); sc.add(sc.declareLinkedHashMap("markerAttributes", "String", "Object")); sc.add("markerAttributes.put(" + I_MARKER + ".USER_EDITABLE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".DONE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".LINE_NUMBER, taskItem.getLine());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_START, taskItem.getCharStart());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_END, taskItem.getCharEnd());"); sc.add("markerAttributes.put(" + I_MARKER + ".MESSAGE, taskItem.getMessage());"); sc.add("new " + markerHelperClassName + "().createMarker(resource, " + I_MARKER + ".TASK, markerAttributes);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addGetBuilderMarkerIdMethod(JavaComposite sc) { sc.add("public String getBuilderMarkerId() {"); sc.add("return " + I_MARKER + ".TASK;"); sc.add("}"); sc.addLineBreak(); } private void addIsInBinFolderMethod(JavaComposite sc) { sc.add("public boolean isInBinFolder(" + I_FILE + " resource) {"); sc.add(I_CONTAINER + " parent = resource.getParent();"); sc.add("while (parent != null) {"); sc.add("if (\"bin\".equals(parent.getName())) {"); sc.add("return true;"); sc.add("}"); sc.add("parent = parent.getParent();"); sc.add("}"); sc.add("return false;"); sc.add("}"); sc.addLineBreak(); } }
false
true
private void addBuildMethod(JavaComposite sc) { sc.add("public void build(" + I_FILE + " resource, " + RESOURCE_SET + " resourceSet, " + I_PROGRESS_MONITOR + " monitor) {"); sc.add("monitor.setTaskName(\"Searching for task items\");"); sc.add("new " + markerHelperClassName + "().removeAllMarkers(resource, " + I_MARKER + ".TASK);"); sc.add("if (isInBinFolder(resource)) {"); sc.add("return;"); sc.add("}"); sc.add(sc.declareArrayList("taskItems", taskItemClassName)); sc.add(taskItemDetectorClassName + " taskItemDetector = new " + taskItemDetectorClassName + "();"); sc.add("try {"); sc.add(INPUT_STREAM + " inputStream = resource.getContents();"); sc.add("String charset = resource.getCharset();"); sc.add("String content = " + streamUtilClassName + ".getContent(inputStream, charset);"); sc.add(iTextScannerClassName + " lexer = new " + metaInformationClassName + "().createLexer();"); sc.add("lexer.setText(content);"); sc.addLineBreak(); sc.add(iTextTokenClassName + " nextToken = lexer.getNextToken();"); sc.add("while (nextToken != null) {"); sc.add("String text = nextToken.getText();"); sc.add("taskItems.addAll(taskItemDetector.findTaskItems(text, nextToken.getLine(), nextToken.getOffset()));"); sc.add("nextToken = lexer.getNextToken();"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("} catch (" + CORE_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("}"); sc.addLineBreak(); sc.add("for (" + taskItemClassName + " taskItem : taskItems) {"); sc.add(sc.declareLinkedHashMap("markerAttributes", "String", "Object")); sc.add("markerAttributes.put(" + I_MARKER + ".USER_EDITABLE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".DONE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".LINE_NUMBER, taskItem.getLine());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_START, taskItem.getCharStart());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_END, taskItem.getCharEnd());"); sc.add("markerAttributes.put(" + I_MARKER + ".MESSAGE, taskItem.getMessage());"); sc.add("new " + markerHelperClassName + "().createMarker(resource, " + I_MARKER + ".TASK, markerAttributes);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); }
private void addBuildMethod(JavaComposite sc) { sc.add("public void build(" + I_FILE + " resource, " + RESOURCE_SET + " resourceSet, " + I_PROGRESS_MONITOR + " monitor) {"); sc.add("monitor.setTaskName(\"Searching for task items\");"); sc.add("new " + markerHelperClassName + "().removeAllMarkers(resource, " + I_MARKER + ".TASK);"); sc.add("if (isInBinFolder(resource)) {"); sc.add("return;"); sc.add("}"); sc.add(sc.declareArrayList("taskItems", taskItemClassName)); sc.add(taskItemDetectorClassName + " taskItemDetector = new " + taskItemDetectorClassName + "();"); sc.add(INPUT_STREAM + " inputStream = null;"); sc.add("try {"); sc.add("inputStream = resource.getContents();"); sc.add("String charset = resource.getCharset();"); sc.add("String content = " + streamUtilClassName + ".getContent(inputStream, charset);"); sc.add(iTextScannerClassName + " lexer = new " + metaInformationClassName + "().createLexer();"); sc.add("lexer.setText(content);"); sc.addLineBreak(); sc.add(iTextTokenClassName + " nextToken = lexer.getNextToken();"); sc.add("while (nextToken != null) {"); sc.add("String text = nextToken.getText();"); sc.add("taskItems.addAll(taskItemDetector.findTaskItems(text, nextToken.getLine(), nextToken.getOffset()));"); sc.add("nextToken = lexer.getNextToken();"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("} catch (" + CORE_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("}"); sc.addLineBreak(); sc.add("try {"); sc.add("if (inputStream != null) {"); sc.add("inputStream.close();"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.addComment("Ignore this"); sc.add("}"); sc.addLineBreak(); sc.add("for (" + taskItemClassName + " taskItem : taskItems) {"); sc.add(sc.declareLinkedHashMap("markerAttributes", "String", "Object")); sc.add("markerAttributes.put(" + I_MARKER + ".USER_EDITABLE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".DONE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".LINE_NUMBER, taskItem.getLine());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_START, taskItem.getCharStart());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_END, taskItem.getCharEnd());"); sc.add("markerAttributes.put(" + I_MARKER + ".MESSAGE, taskItem.getMessage());"); sc.add("new " + markerHelperClassName + "().createMarker(resource, " + I_MARKER + ".TASK, markerAttributes);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GitHistoryPage.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GitHistoryPage.java index 47d10b85..efc5ea61 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GitHistoryPage.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GitHistoryPage.java @@ -1,1398 +1,1398 @@ /******************************************************************************* * Copyright (C) 2008, Roger C. Soares <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * Copyright (c) 2010, Stefan Lay <[email protected]> * Copyright (C) 2010, Mathias Kinzler <[email protected]> * Copyright (C) 2010, Matthias Sohn <[email protected]> * * 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.egit.ui.internal.history; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIIcons; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.UIUtils; import org.eclipse.egit.ui.internal.CompareUtils; import org.eclipse.egit.ui.internal.repository.tree.FileNode; import org.eclipse.egit.ui.internal.repository.tree.FolderNode; import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNode; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.preference.IPersistentPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.events.ListenerHandle; import org.eclipse.jgit.events.RefsChangedEvent; import org.eclipse.jgit.events.RefsChangedListener; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revplot.PlotCommit; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevFlag; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.AndTreeFilter; import org.eclipse.jgit.treewalk.filter.PathFilterGroup; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.MenuDetectEvent; import org.eclipse.swt.events.MenuDetectListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.team.ui.history.HistoryPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import org.eclipse.ui.progress.IWorkbenchSiteProgressService; /** Graphical commit history viewer. */ public class GitHistoryPage extends HistoryPage implements RefsChangedListener { /** actions used in GitHistoryPage **/ private static class GitHistoryPageActions { private abstract class BooleanPrefAction extends Action implements IPropertyChangeListener, IWorkbenchAction { private final String prefName; BooleanPrefAction(final String pn, final String text) { setText(text); prefName = pn; historyPage.store.addPropertyChangeListener(this); setChecked(historyPage.store.getBoolean(prefName)); } public void run() { historyPage.store.setValue(prefName, isChecked()); if (historyPage.store.needsSaving()) { try { historyPage.store.save(); } catch (IOException e) { Activator.handleError(e.getMessage(), e, false); } } } abstract void apply(boolean value); public void propertyChange(final PropertyChangeEvent event) { if (prefName.equals(event.getProperty())) { setChecked(historyPage.store.getBoolean(prefName)); apply(isChecked()); } } public void dispose() { // stop listening historyPage.store.removePropertyChangeListener(this); } } private class ShowFilterAction extends Action { private final ShowFilter filter; ShowFilterAction(ShowFilter filter, ImageDescriptor icon, String menuLabel, String toolTipText) { super(null, IAction.AS_CHECK_BOX); this.filter = filter; setImageDescriptor(icon); setText(menuLabel); setToolTipText(toolTipText); } @Override public void run() { String oldName = historyPage.getName(); String oldDescription = historyPage.getDescription(); if (!isChecked()) { if (historyPage.showAllFilter == filter) { historyPage.showAllFilter = ShowFilter.SHOWALLRESOURCE; showAllResourceVersionsAction.setChecked(true); historyPage.initAndStartRevWalk(false); } } if (isChecked() && historyPage.showAllFilter != filter) { historyPage.showAllFilter = filter; if (this != showAllRepoVersionsAction) showAllRepoVersionsAction.setChecked(false); if (this != showAllProjectVersionsAction) showAllProjectVersionsAction.setChecked(false); if (this != showAllFolderVersionsAction) showAllFolderVersionsAction.setChecked(false); if (this != showAllResourceVersionsAction) showAllResourceVersionsAction.setChecked(false); historyPage.initAndStartRevWalk(false); } historyPage.firePropertyChange(historyPage, P_NAME, oldName, historyPage.getName()); // even though this is currently ending nowhere (see bug // 324386), we // still create the event historyPage.firePropertyChange(historyPage, P_DESCRIPTION, oldDescription, historyPage.getDescription()); Activator .getDefault() .getPreferenceStore() .setValue(PREF_SHOWALLFILTER, historyPage.showAllFilter.toString()); } @Override public String toString() { return "ShowFilter[" + filter.toString() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } } List<IWorkbenchAction> actionsToDispose; BooleanPrefAction wrapCommentAction; BooleanPrefAction fillCommentAction; IAction findAction; IAction refreshAction; BooleanPrefAction showCommentAction; BooleanPrefAction showFilesAction; IWorkbenchAction compareModeAction; IWorkbenchAction showAllBranchesAction; IWorkbenchAction reuseCompareEditorAction; ShowFilterAction showAllRepoVersionsAction; ShowFilterAction showAllProjectVersionsAction; ShowFilterAction showAllFolderVersionsAction; ShowFilterAction showAllResourceVersionsAction; private GitHistoryPage historyPage; GitHistoryPageActions(GitHistoryPage historyPage) { actionsToDispose = new ArrayList<IWorkbenchAction>(); this.historyPage = historyPage; createActions(); } private void createActions() { createFindToolbarAction(); createRefreshAction(); createFilterActions(); createCompareModeAction(); createReuseCompareEditorAction(); createShowAllBranchesAction(); createShowCommentAction(); createShowFilesAction(); createWrapCommentAction(); createFillCommentAction(); wrapCommentAction.setEnabled(showCommentAction.isChecked()); fillCommentAction.setEnabled(showCommentAction.isChecked()); } private void createFindToolbarAction() { findAction = new Action(UIText.GitHistoryPage_FindMenuLabel, UIIcons.ELCL16_FIND) { public void run() { historyPage.store.setValue( UIPreferences.RESOURCEHISTORY_SHOW_FINDTOOLBAR, isChecked()); if (historyPage.store.needsSaving()) { try { historyPage.store.save(); } catch (IOException e) { Activator.handleError(e.getMessage(), e, false); } } historyPage.layout(); } }; findAction .setChecked(historyPage.store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_FINDTOOLBAR)); findAction.setToolTipText(UIText.GitHistoryPage_FindTooltip); } private void createRefreshAction() { refreshAction = new Action(UIText.GitHistoryPage_RefreshMenuLabel, UIIcons.ELCL16_REFRESH) { @Override public void run() { historyPage.refresh(); } }; } private void createFilterActions() { showAllRepoVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLREPO, UIIcons.REPOSITORY, UIText.GitHistoryPage_AllInRepoMenuLabel, UIText.GitHistoryPage_AllInRepoTooltip); showAllProjectVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLPROJECT, UIIcons.FILTERPROJECT, UIText.GitHistoryPage_AllInProjectMenuLabel, UIText.GitHistoryPage_AllInProjectTooltip); showAllFolderVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLFOLDER, UIIcons.FILTERFOLDER, UIText.GitHistoryPage_AllInParentMenuLabel, UIText.GitHistoryPage_AllInParentTooltip); showAllResourceVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLRESOURCE, UIIcons.FILTERRESOURCE, UIText.GitHistoryPage_AllOfResourceMenuLabel, UIText.GitHistoryPage_AllOfResourceTooltip); showAllRepoVersionsAction .setChecked(historyPage.showAllFilter == showAllRepoVersionsAction.filter); showAllProjectVersionsAction .setChecked(historyPage.showAllFilter == showAllProjectVersionsAction.filter); showAllFolderVersionsAction .setChecked(historyPage.showAllFilter == showAllFolderVersionsAction.filter); showAllResourceVersionsAction .setChecked(historyPage.showAllFilter == showAllResourceVersionsAction.filter); } private void createCompareModeAction() { compareModeAction = new BooleanPrefAction( UIPreferences.RESOURCEHISTORY_COMPARE_MODE, UIText.GitHistoryPage_CompareModeMenuLabel) { @Override void apply(boolean value) { // nothing, just switch the preference } }; compareModeAction.setImageDescriptor(UIIcons.ELCL16_COMPARE_VIEW); compareModeAction.setToolTipText(UIText.GitHistoryPage_compareMode); actionsToDispose.add(compareModeAction); } private void createReuseCompareEditorAction() { reuseCompareEditorAction = new CompareUtils.ReuseCompareEditorAction(); actionsToDispose.add(reuseCompareEditorAction); } private void createShowAllBranchesAction() { showAllBranchesAction = new BooleanPrefAction( UIPreferences.RESOURCEHISTORY_SHOW_ALL_BRANCHES, UIText.GitHistoryPage_ShowAllBranchesMenuLabel) { @Override void apply(boolean value) { historyPage.refresh(); } }; showAllBranchesAction.setImageDescriptor(UIIcons.BRANCH); showAllBranchesAction .setToolTipText(UIText.GitHistoryPage_showAllBranches); actionsToDispose.add(showAllBranchesAction); } private void createShowCommentAction() { showCommentAction = new BooleanPrefAction( UIPreferences.RESOURCEHISTORY_SHOW_REV_COMMENT, UIText.ResourceHistory_toggleRevComment) { void apply(final boolean value) { historyPage.layout(); wrapCommentAction.setEnabled(isChecked()); fillCommentAction.setEnabled(isChecked()); } }; actionsToDispose.add(showCommentAction); } private void createShowFilesAction() { showFilesAction = new BooleanPrefAction( UIPreferences.RESOURCEHISTORY_SHOW_REV_DETAIL, UIText.ResourceHistory_toggleRevDetail) { void apply(final boolean value) { historyPage.layout(); } }; actionsToDispose.add(showFilesAction); } private void createWrapCommentAction() { wrapCommentAction = new BooleanPrefAction( UIPreferences.RESOURCEHISTORY_SHOW_COMMENT_WRAP, UIText.ResourceHistory_toggleCommentWrap) { void apply(boolean wrap) { // nothing, just set the Preference } }; wrapCommentAction.apply(wrapCommentAction.isChecked()); actionsToDispose.add(wrapCommentAction); } private void createFillCommentAction() { fillCommentAction = new BooleanPrefAction( UIPreferences.RESOURCEHISTORY_SHOW_COMMENT_FILL, UIText.ResourceHistory_toggleCommentFill) { void apply(boolean fill) { // nothing, just set the Preference } }; fillCommentAction.apply(fillCommentAction.isChecked()); actionsToDispose.add(fillCommentAction); } } private static final String POPUP_ID = "org.eclipse.egit.ui.historyPageContributions"; //$NON-NLS-1$ private static final String DESCRIPTION_PATTERN = "{0} - {1}"; //$NON-NLS-1$ private static final String NAME_PATTERN = "{0}: {1} [{2}]"; //$NON-NLS-1$ private static final String PREF_SHOWALLFILTER = "org.eclipse.egit.ui.githistorypage.showallfilter"; //$NON-NLS-1$ enum ShowFilter { SHOWALLRESOURCE, SHOWALLFOLDER, SHOWALLPROJECT, SHOWALLREPO, } private ShowFilter showAllFilter = ShowFilter.SHOWALLRESOURCE; private GitHistoryPageActions actions; private void initActions() { try { showAllFilter = ShowFilter.valueOf(Activator.getDefault() .getPreferenceStore().getString(PREF_SHOWALLFILTER)); } catch (IllegalArgumentException e) { showAllFilter = ShowFilter.SHOWALLRESOURCE; } actions = new GitHistoryPageActions(this); setupToolBar(); setupViewMenu(); graph.getControl().addMenuDetectListener(new MenuDetectListener() { public void menuDetected(MenuDetectEvent e) { popupMgr.add(actions.showFilesAction); popupMgr.add(actions.showCommentAction); } }); } private void setupToolBar() { IToolBarManager mgr = getSite().getActionBars().getToolBarManager(); mgr.add(actions.findAction); mgr.add(new Separator()); mgr.add(actions.showAllRepoVersionsAction); mgr.add(actions.showAllProjectVersionsAction); mgr.add(actions.showAllFolderVersionsAction); mgr.add(actions.showAllResourceVersionsAction); mgr.add(new Separator()); mgr.add(actions.compareModeAction); mgr.add(actions.showAllBranchesAction); } private void setupViewMenu() { IMenuManager viewMenuMgr = getSite().getActionBars().getMenuManager(); viewMenuMgr.add(actions.refreshAction); viewMenuMgr.add(new Separator()); IMenuManager showSubMenuMgr = new MenuManager( UIText.GitHistoryPage_ShowSubMenuLabel); viewMenuMgr.add(showSubMenuMgr); showSubMenuMgr.add(actions.showAllBranchesAction); showSubMenuMgr.add(actions.findAction); showSubMenuMgr.add(actions.showFilesAction); showSubMenuMgr.add(actions.showCommentAction); IMenuManager filterSubMenuMgr = new MenuManager( UIText.GitHistoryPage_FilterSubMenuLabel); viewMenuMgr.add(filterSubMenuMgr); filterSubMenuMgr.add(actions.showAllRepoVersionsAction); filterSubMenuMgr.add(actions.showAllProjectVersionsAction); filterSubMenuMgr.add(actions.showAllFolderVersionsAction); filterSubMenuMgr.add(actions.showAllResourceVersionsAction); viewMenuMgr.add(new Separator()); viewMenuMgr.add(actions.compareModeAction); viewMenuMgr.add(actions.reuseCompareEditorAction); viewMenuMgr.add(new Separator()); viewMenuMgr.add(actions.wrapCommentAction); viewMenuMgr.add(actions.fillCommentAction); } /** An error text to be shown instead of the control */ private StyledText errorText; private final IPersistentPreferenceStore store = (IPersistentPreferenceStore) Activator .getDefault().getPreferenceStore(); private ListenerHandle myRefsChangedHandle; private HistoryPageInput input; private String name; private boolean trace = GitTraceLocation.HISTORYVIEW.isActive(); /** * Determine if the input can be shown in this viewer. * * @param object * an object that is hopefully of type ResourceList or IResource, * but may be anything (including null). * @return true if the input is a ResourceList or an IResource of type FILE, * FOLDER or PROJECT and we can show it; false otherwise. */ public static boolean canShowHistoryFor(final Object object) { if (object instanceof HistoryPageInput) { return true; } if (object instanceof IResource) { return typeOk((IResource) object); } if (object instanceof RepositoryTreeNode) return true; if (object instanceof IAdaptable) { IResource resource = (IResource) ((IAdaptable) object) .getAdapter(IResource.class); return resource == null ? false : typeOk(resource); } return false; } private static boolean typeOk(final IResource object) { switch (object.getType()) { case IResource.FILE: case IResource.FOLDER: case IResource.PROJECT: return true; } return false; } /** Overall composite hosting all of our controls. */ private Composite topControl; /** Overall composite hosting the controls that displays the history. */ private Composite historyControl; /** Split between {@link #graph} and {@link #revInfoSplit}. */ private SashForm graphDetailSplit; /** Split between {@link #commentViewer} and {@link #fileViewer}. */ private SashForm revInfoSplit; /** The table showing the DAG, first "paragraph", author, author date. */ private CommitGraphTable graph; /** Viewer displaying the currently selected commit of {@link #graph}. */ private CommitMessageViewer commentViewer; /** Viewer displaying file difference implied by {@link #graph}'s commit. */ private CommitFileDiffViewer fileViewer; /** Toolbar to find commits in the history view. */ private FindToolbar findToolbar; /** Our context menu manager for the entire page. */ private final MenuManager popupMgr = new MenuManager(null, POPUP_ID); /** Job that is updating our history view, if we are refreshing. */ private GenerateHistoryJob job; /** Revision walker that allocated our graph's commit nodes. */ private SWTWalk currentWalk; /** Last HEAD */ private AnyObjectId currentHeadId; /** * Highlight flag that can be applied to commits to make them stand out. * <p> * Allocated at the same time as {@link #currentWalk}. If the walk rebuilds, * so must this flag. */ private RevFlag highlightFlag; /** * List of paths we used to limit {@link #currentWalk}; null if no paths. * <p> * Note that a change in this list requires that {@link #currentWalk} and * all of its associated commits. */ private List<String> pathFilters; /** * The default constructor */ public GitHistoryPage() { trace = GitTraceLocation.HISTORYVIEW.isActive(); if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); } void initAndStartRevWalk(boolean forceNewWalk) throws IllegalStateException { try { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); cancelRefreshJob(); Repository db = input.getRepository(); AnyObjectId headId = resolveHead(db); List<String> paths = buildFilterPaths(input.getItems(), input .getFileList(), db); if (forceNewWalk || pathChange(pathFilters, paths) || currentWalk == null || !headId.equals(currentHeadId)) { // TODO Do not dispose SWTWalk just because HEAD changed // In theory we should be able to update the graph and // not dispose of the SWTWalk, even if HEAD was reset to // HEAD^1 and the old HEAD commit should not be visible. // createNewWalk(db, headId); } else { currentWalk.reset(); } setWalkStartPoints(db, headId); final TreeWalk fileWalker = setupFileViewer(db, paths); setupCommentViewer(db, fileWalker); scheduleNewGenerateHistoryJob(); } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } } private AnyObjectId resolveHead(Repository db) { AnyObjectId headId; try { headId = db.resolve(Constants.HEAD); } catch (IOException e) { throw new IllegalStateException(NLS.bind( UIText.GitHistoryPage_errorParsingHead, Activator .getDefault().getRepositoryUtil() .getRepositoryName(db))); } if (headId == null) throw new IllegalStateException(NLS.bind( UIText.GitHistoryPage_errorParsingHead, Activator .getDefault().getRepositoryUtil() .getRepositoryName(db))); return headId; } private void createNewWalk(Repository db, AnyObjectId headId) { currentHeadId = headId; if (currentWalk != null) currentWalk.release(); currentWalk = new SWTWalk(db); currentWalk.sort(RevSort.COMMIT_TIME_DESC, true); currentWalk.sort(RevSort.BOUNDARY, true); highlightFlag = currentWalk.newFlag("highlight"); //$NON-NLS-1$ } private void setWalkStartPoints(Repository db, AnyObjectId headId) { try { if (store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ALL_BRANCHES)) { markStartAllRefs(Constants.R_HEADS); markStartAllRefs(Constants.R_REMOTES); } else currentWalk.markStart(currentWalk.parseCommit(headId)); } catch (IOException e) { throw new IllegalStateException(NLS.bind( UIText.GitHistoryPage_errorReadingHeadCommit, headId, db.getDirectory().getAbsolutePath()), e); } } private void setupCommentViewer(Repository db, final TreeWalk fileWalker) { commentViewer.setTreeWalk(fileWalker); commentViewer.setDb(db); commentViewer.refresh(); } private TreeWalk setupFileViewer(Repository db, List<String> paths) { final TreeWalk fileWalker = createFileWalker(db, paths); fileViewer.setTreeWalk(db, fileWalker); fileViewer.refresh(); fileViewer.addSelectionChangedListener(commentViewer); return fileWalker; } private TreeWalk createFileWalker(Repository db, List<String> paths) { final TreeWalk fileWalker = new TreeWalk(db); fileWalker.setRecursive(true); if (paths.size() > 0) { pathFilters = paths; currentWalk.setTreeFilter(AndTreeFilter.create(PathFilterGroup .createFromStrings(paths), TreeFilter.ANY_DIFF)); fileWalker.setFilter(currentWalk.getTreeFilter().clone()); } else { pathFilters = null; currentWalk.setTreeFilter(TreeFilter.ALL); fileWalker.setFilter(TreeFilter.ANY_DIFF); } return fileWalker; } private void scheduleNewGenerateHistoryJob() { final SWTCommitList list = new SWTCommitList(graph.getControl().getDisplay()); list.source(currentWalk); final GenerateHistoryJob rj = new GenerateHistoryJob(this, list); rj.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { final Control graphctl = graph.getControl(); if (job != rj || graphctl.isDisposed()) return; graphctl.getDisplay().asyncExec(new Runnable() { public void run() { if (job == rj) job = null; } }); } }); job = rj; if (trace) GitTraceLocation.getTrace().trace( GitTraceLocation.HISTORYVIEW.getLocation(), "Scheduling GenerateHistoryJob"); //$NON-NLS-1$ schedule(rj); } /** * @param compareMode * switch compare mode button of the view on / off */ public void setCompareMode(boolean compareMode) { store.setValue(UIPreferences.RESOURCEHISTORY_COMPARE_MODE, compareMode); } @Override public void createControl(final Composite parent) { trace = GitTraceLocation.HISTORYVIEW.isActive(); if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); historyControl = createMainPanel(parent); GridDataFactory.fillDefaults().grab(true, true).applyTo(historyControl); graphDetailSplit = new SashForm(historyControl, SWT.VERTICAL); GridDataFactory.fillDefaults().grab(true, true).applyTo( graphDetailSplit); graph = new CommitGraphTable(graphDetailSplit, getSite(), popupMgr); revInfoSplit = new SashForm(graphDetailSplit, SWT.HORIZONTAL); commentViewer = new CommitMessageViewer(revInfoSplit, getSite()); fileViewer = new CommitFileDiffViewer(revInfoSplit, getSite()); findToolbar = new FindToolbar(historyControl); layoutSashForm(graphDetailSplit, UIPreferences.RESOURCEHISTORY_GRAPH_SPLIT); layoutSashForm(revInfoSplit, UIPreferences.RESOURCEHISTORY_REV_SPLIT); attachCommitSelectionChanged(); initActions(); getSite().registerContextMenu(POPUP_ID, popupMgr, graph.getTableView()); // due to the issues described in bug 322751, it makes no // sense to set a selection provider for the site here layout(); myRefsChangedHandle = Repository.getGlobalListenerList() .addRefsChangedListener(this); if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } /** * @return the selection provider */ public ISelectionProvider getSelectionProvider() { return graph.getTableView(); } private Runnable refschangedRunnable; public void onRefsChanged(final RefsChangedEvent e) { if (input == null || e.getRepository() != input.getRepository()) return; if (getControl().isDisposed()) return; synchronized (this) { if (refschangedRunnable == null) { refschangedRunnable = new Runnable() { public void run() { if (!getControl().isDisposed()) { if (GitTraceLocation.HISTORYVIEW.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.HISTORYVIEW .getLocation(), "Executing async repository changed event"); //$NON-NLS-1$ refschangedRunnable = null; initAndStartRevWalk(true); } } }; getControl().getDisplay().asyncExec(refschangedRunnable); } } } private void layoutSashForm(final SashForm sf, final String key) { sf.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { final int[] w = sf.getWeights(); store.putValue(key, UIPreferences.intArrayToString(w)); if (store.needsSaving()) try { store.save(); } catch (IOException e1) { Activator.handleError(e1.getMessage(), e1, false); } } }); sf.setWeights(UIPreferences.stringToIntArray(store.getString(key), 2)); } private Composite createMainPanel(final Composite parent) { topControl = new Composite(parent, SWT.NONE); StackLayout layout = new StackLayout(); topControl.setLayout(layout); final Composite c = new Composite(topControl, SWT.NULL); layout.topControl = c; // shown instead of the splitter if an error message was set errorText = new StyledText(topControl, SWT.NONE); // use the same font as in message viewer errorText.setFont(UIUtils .getFont(UIPreferences.THEME_CommitMessageFont)); errorText.setText(UIText.CommitFileDiffViewer_SelectOneCommitMessage); final GridLayout parentLayout = new GridLayout(); parentLayout.marginHeight = 0; parentLayout.marginWidth = 0; parentLayout.verticalSpacing = 0; c.setLayout(parentLayout); return c; } private void layout() { final boolean showComment = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_REV_COMMENT); final boolean showFiles = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_REV_DETAIL); final boolean showFindToolbar = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_FINDTOOLBAR); if (showComment && showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(null); } else if (showComment && !showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(commentViewer.getControl()); } else if (!showComment && showFiles) { graphDetailSplit.setMaximizedControl(null); // the parent of the control! revInfoSplit.setMaximizedControl(fileViewer.getControl() .getParent()); } else if (!showComment && !showFiles) { graphDetailSplit.setMaximizedControl(graph.getControl()); } if (showFindToolbar) { ((GridData) findToolbar.getLayoutData()).heightHint = SWT.DEFAULT; } else { ((GridData) findToolbar.getLayoutData()).heightHint = 0; findToolbar.clear(); } historyControl.layout(); } private void attachCommitSelectionChanged() { graph.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(final SelectionChangedEvent event) { final ISelection s = event.getSelection(); if (s.isEmpty() || !(s instanceof IStructuredSelection)) { commentViewer.setInput(null); fileViewer.setInput(null); return; } final IStructuredSelection sel = ((IStructuredSelection) s); if (sel.size() > 1) { commentViewer.setInput(null); fileViewer.setInput(null); return; } final PlotCommit<?> c = (PlotCommit<?>) sel.getFirstElement(); commentViewer.setInput(c); fileViewer.setInput(c); } }); commentViewer .addCommitNavigationListener(new CommitNavigationListener() { public void showCommit(final RevCommit c) { graph.selectCommit(c); } }); findToolbar.addSelectionListener(new Listener() { public void handleEvent(Event event) { graph.selectCommit((RevCommit) event.data); } }); } public void dispose() { trace = GitTraceLocation.HISTORYVIEW.isActive(); if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); if (myRefsChangedHandle != null) { myRefsChangedHandle.remove(); myRefsChangedHandle = null; } // dispose of the actions (the history framework doesn't do this for us) for (IWorkbenchAction action : actions.actionsToDispose) action.dispose(); actions.actionsToDispose.clear(); cancelRefreshJob(); if (popupMgr != null) { for (final IContributionItem i : popupMgr.getItems()) { if (i instanceof IWorkbenchAction) ((IWorkbenchAction) i).dispose(); } for (final IContributionItem i : getSite().getActionBars() .getMenuManager().getItems()) { if (i instanceof IWorkbenchAction) ((IWorkbenchAction) i).dispose(); } } super.dispose(); } public void refresh() { this.input = null; inputSet(); } @Override public void setFocus() { graph.getControl().setFocus(); } @Override public Control getControl() { return topControl; } @Override public boolean setInput(Object object) { try { trace = GitTraceLocation.HISTORYVIEW.isActive(); if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation(), object); if (object == getInput()) return true; this.input = null; return super.setInput(object); } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } } @Override public boolean inputSet() { try { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); if (this.input != null) return true; cancelRefreshJob(); setErrorMessage(null); Object o = super.getInput(); if (o == null) { setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } if (o instanceof IResource) { RepositoryMapping mapping = RepositoryMapping .getMapping((IResource) o); if (mapping != null) { Repository repo = mapping.getRepository(); input = new HistoryPageInput(repo, new IResource[] { (IResource) o }); } } else if (o instanceof RepositoryTreeNode) { RepositoryTreeNode repoNode = (RepositoryTreeNode) o; switch (repoNode.getType()) { case FILE: File file = ((FileNode) repoNode).getObject(); input = new HistoryPageInput(repoNode.getRepository(), new File[] { file }); break; case FOLDER: File folder = ((FolderNode) repoNode).getObject(); input = new HistoryPageInput(repoNode.getRepository(), new File[] { folder }); break; default: input = new HistoryPageInput(repoNode.getRepository()); } } else if (o instanceof HistoryPageInput) input = (HistoryPageInput) o; else if (o instanceof IAdaptable) { IResource resource = (IResource) ((IAdaptable) o) .getAdapter(IResource.class); if (resource != null) { RepositoryMapping mapping = RepositoryMapping .getMapping(resource); Repository repo = mapping.getRepository(); input = new HistoryPageInput(repo, new IResource[] { resource }); } } if (input == null) { this.name = ""; //$NON-NLS-1$ setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } final IResource[] inResources = input.getItems(); final File[] inFiles = input.getFileList(); if (inResources != null && inResources.length == 0) { this.name = ""; //$NON-NLS-1$ setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } this.name = calculateName(input); // disable the filters if we have a Repository as input boolean filtersActive = inResources != null || inFiles != null; actions.showAllRepoVersionsAction.setEnabled(filtersActive); actions.showAllProjectVersionsAction.setEnabled(filtersActive); // the repository itself has no notion of projects actions.showAllFolderVersionsAction.setEnabled(inResources != null); actions.showAllResourceVersionsAction.setEnabled(filtersActive); try { initAndStartRevWalk(true); } catch (IllegalStateException e) { - Activator.handleError(e.getMessage(), e.getCause(), true); + Activator.handleError(e.getMessage(), e, true); return false; } return true; } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } } private ArrayList<String> buildFilterPaths(final IResource[] inResources, final File[] inFiles, final Repository db) throws IllegalStateException { final ArrayList<String> paths; if (inResources != null) { paths = new ArrayList<String>(inResources.length); for (final IResource r : inResources) { final RepositoryMapping map = RepositoryMapping.getMapping(r); if (map == null) continue; if (db != map.getRepository()) { throw new IllegalStateException( UIText.AbstractHistoryCommanndHandler_NoUniqueRepository); } if (showAllFilter == ShowFilter.SHOWALLFOLDER) { final String path; // if the resource's parent is the workspace root, we will // get nonsense from map.getRepoRelativePath(), so we // check here and use the project instead if (r.getParent() instanceof IWorkspaceRoot) path = map.getRepoRelativePath(r.getProject()); else path = map.getRepoRelativePath(r.getParent()); if (path != null && path.length() > 0) paths.add(path); } else if (showAllFilter == ShowFilter.SHOWALLPROJECT) { final String path = map.getRepoRelativePath(r.getProject()); if (path != null && path.length() > 0) paths.add(path); } else if (showAllFilter == ShowFilter.SHOWALLREPO) { // nothing } else /* if (showAllFilter == ShowFilter.SHOWALLRESOURCE) */{ final String path = map.getRepoRelativePath(r); if (path != null && path.length() > 0) paths.add(path); } } } else if (inFiles != null) { IPath workdirPath = new Path(db.getWorkTree().getPath()); IPath gitDirPath = new Path(db.getDirectory().getPath()); int segmentCount = workdirPath.segmentCount(); paths = new ArrayList<String>(inFiles.length); for (File file : inFiles) { IPath filePath; if (showAllFilter == ShowFilter.SHOWALLFOLDER) { filePath = new Path(file.getParentFile().getPath()); } else if (showAllFilter == ShowFilter.SHOWALLPROJECT || showAllFilter == ShowFilter.SHOWALLREPO) { // we don't know of projects here -> treat as SHOWALLREPO continue; } else /* if (showAllFilter == ShowFilter.SHOWALLRESOURCE) */{ filePath = new Path(file.getPath()); } if (gitDirPath.isPrefixOf(filePath)) { throw new IllegalStateException( NLS .bind( UIText.GitHistoryPage_FileOrFolderPartOfGitDirMessage, filePath.toOSString())); } IPath pathToAdd = filePath.removeFirstSegments(segmentCount) .setDevice(null); if (!pathToAdd.isEmpty()) { paths.add(pathToAdd.toString()); } } } else { paths = new ArrayList<String>(0); } return paths; } /** * @param message * the message to display instead of the control */ public void setErrorMessage(final String message) { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation(), message); getHistoryPageSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { StackLayout layout = (StackLayout) topControl.getLayout(); if (message != null) { errorText.setText(message); layout.topControl = errorText; } else { errorText.setText(""); //$NON-NLS-1$ layout.topControl = historyControl; } topControl.layout(); } }); if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } /** * {@link RevWalk#markStart(RevCommit)} all refs with given prefix to mark * start of graph traversal using currentWalker * * @param prefix * prefix of refs to be marked * @throws IOException * @throws MissingObjectException * @throws IncorrectObjectTypeException */ private void markStartAllRefs(String prefix) throws IOException, MissingObjectException, IncorrectObjectTypeException { for (Entry<String, Ref> refEntry : input.getRepository() .getRefDatabase().getRefs(prefix).entrySet()) { Ref ref = refEntry.getValue(); if (ref.isSymbolic()) continue; currentWalk.markStart(currentWalk.parseCommit(ref.getObjectId())); } } private void cancelRefreshJob() { if (job != null && job.getState() != Job.NONE) { job.cancel(); try { job.join(); } catch (InterruptedException e) { cancelRefreshJob(); return; } job = null; } } private boolean pathChange(final List<String> o, final List<String> n) { if (o == null) return !n.isEmpty(); return !o.equals(n); } private void schedule(final Job j) { final IWorkbenchPartSite site = getWorkbenchSite(); if (site != null) { final IWorkbenchSiteProgressService p; p = (IWorkbenchSiteProgressService) site .getAdapter(IWorkbenchSiteProgressService.class); if (p != null) { p.schedule(j, 0, true /* use half-busy cursor */); return; } } j.schedule(); } void showCommitList(final Job j, final SWTCommitList list, final SWTCommit[] asArray) { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation(), new Object[] { list, asArray }); if (job != j || graph.getControl().isDisposed()) return; graph.getControl().getDisplay().asyncExec(new Runnable() { public void run() { if (!graph.getControl().isDisposed() && job == j) { graph.setInput(highlightFlag, list, asArray, input); if (trace) GitTraceLocation.getTrace().trace( GitTraceLocation.HISTORYVIEW.getLocation(), "Setting input to table"); //$NON-NLS-1$ findToolbar.setInput(highlightFlag, graph.getTableView() .getTable(), asArray); setErrorMessage(null); } } }); if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } private IWorkbenchPartSite getWorkbenchSite() { final IWorkbenchPart part = getHistoryPageSite().getPart(); return part != null ? part.getSite() : null; } public boolean isValidInput(final Object object) { return canShowHistoryFor(object); } public Object getAdapter(final Class adapter) { return null; } public String getName() { return this.name; } /** * @return the internal input object, or <code>null</code> */ public HistoryPageInput getInputInternal() { return this.input; } private static String calculateName(HistoryPageInput in) { // we always visualize the current input in the form // <type>: <path> [<respository name>] // in order to give the user an understanding which context // menus they can expect with the current input // we show the filter hint only upon getDescription() // as it wrongly pollutes the navigation history final String repositoryName = Activator.getDefault() .getRepositoryUtil().getRepositoryName(in.getRepository()); if (in.getItems() == null && in.getFileList() == null) { // plain repository, no files specified return NLS.bind(UIText.GitHistoryPage_RepositoryNamePattern, repositoryName); } else if (in.getItems() != null && in.getItems().length == 1) { // single resource IResource resource = in.getItems()[0]; final String type; switch (resource.getType()) { case IResource.FILE: type = UIText.GitHistoryPage_FileType; break; case IResource.PROJECT: type = UIText.GitHistoryPage_ProjectType; break; default: type = UIText.GitHistoryPage_FolderType; break; } String path = resource.getFullPath().makeRelative().toString(); if (resource.getType() == IResource.FOLDER) path = path + '/'; return NLS.bind(NAME_PATTERN, new Object[] { type, path, repositoryName }); } else if (in.getFileList() != null && in.getFileList().length == 1) { // single file from Repository File resource = in.getFileList()[0]; String path; final String type; if (resource.isDirectory()) { type = UIText.GitHistoryPage_FolderType; path = resource.getPath() + IPath.SEPARATOR; } else { type = UIText.GitHistoryPage_FileType; path = resource.getPath(); } return NLS.bind(NAME_PATTERN, new Object[] { type, path, repositoryName }); } else { // user has selected multiple resources and then hits Team->Show in // History (the generic history view can not deal with multiple // selection) int count = 0; StringBuilder b = new StringBuilder(); if (in.getItems() != null) { count = in.getItems().length; for (IResource res : in.getItems()) { b.append(res.getFullPath()); if (res.getType() == IResource.FOLDER) b.append('/'); // limit the total length if (b.length() > 100) { b.append("... "); //$NON-NLS-1$ break; } b.append(", "); //$NON-NLS-1$ } } if (in.getFileList() != null) { count = in.getFileList().length; for (File file : in.getFileList()) { b.append(getRepoRelativePath(in.getRepository(), file)); if (file.isDirectory()) b.append('/'); // limit the total length if (b.length() > 100) { b.append("... "); //$NON-NLS-1$ break; } b.append(", "); //$NON-NLS-1$ } } // trim off the last ", " (or " " if total length exceeded) if (b.length() > 2) b.setLength(b.length() - 2); String multiResourcePrefix = NLS.bind( UIText.GitHistoryPage_MultiResourcesType, Integer .valueOf(count)); return NLS.bind(NAME_PATTERN, new Object[] { multiResourcePrefix, b.toString(), repositoryName }); } } private static String getRepoRelativePath(Repository repo, File file) { IPath workdirPath = new Path(repo.getWorkTree().getPath()); IPath filePath = new Path(file.getPath()).setDevice(null); return filePath.removeFirstSegments(workdirPath.segmentCount()) .toString(); } public String getDescription() { // this doesn't seem to be rendered anywhere, but still... String filterHint = null; switch (showAllFilter) { case SHOWALLREPO: filterHint = UIText.GitHistoryPage_AllChangesInRepoHint; break; case SHOWALLPROJECT: filterHint = UIText.GitHistoryPage_AllChangesInProjectHint; break; case SHOWALLFOLDER: filterHint = UIText.GitHistoryPage_AllChangesInFolderHint; break; case SHOWALLRESOURCE: filterHint = UIText.GitHistoryPage_AllChangesOfResourceHint; break; } return NLS.bind(DESCRIPTION_PATTERN, getName(), filterHint); } }
true
true
public boolean inputSet() { try { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); if (this.input != null) return true; cancelRefreshJob(); setErrorMessage(null); Object o = super.getInput(); if (o == null) { setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } if (o instanceof IResource) { RepositoryMapping mapping = RepositoryMapping .getMapping((IResource) o); if (mapping != null) { Repository repo = mapping.getRepository(); input = new HistoryPageInput(repo, new IResource[] { (IResource) o }); } } else if (o instanceof RepositoryTreeNode) { RepositoryTreeNode repoNode = (RepositoryTreeNode) o; switch (repoNode.getType()) { case FILE: File file = ((FileNode) repoNode).getObject(); input = new HistoryPageInput(repoNode.getRepository(), new File[] { file }); break; case FOLDER: File folder = ((FolderNode) repoNode).getObject(); input = new HistoryPageInput(repoNode.getRepository(), new File[] { folder }); break; default: input = new HistoryPageInput(repoNode.getRepository()); } } else if (o instanceof HistoryPageInput) input = (HistoryPageInput) o; else if (o instanceof IAdaptable) { IResource resource = (IResource) ((IAdaptable) o) .getAdapter(IResource.class); if (resource != null) { RepositoryMapping mapping = RepositoryMapping .getMapping(resource); Repository repo = mapping.getRepository(); input = new HistoryPageInput(repo, new IResource[] { resource }); } } if (input == null) { this.name = ""; //$NON-NLS-1$ setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } final IResource[] inResources = input.getItems(); final File[] inFiles = input.getFileList(); if (inResources != null && inResources.length == 0) { this.name = ""; //$NON-NLS-1$ setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } this.name = calculateName(input); // disable the filters if we have a Repository as input boolean filtersActive = inResources != null || inFiles != null; actions.showAllRepoVersionsAction.setEnabled(filtersActive); actions.showAllProjectVersionsAction.setEnabled(filtersActive); // the repository itself has no notion of projects actions.showAllFolderVersionsAction.setEnabled(inResources != null); actions.showAllResourceVersionsAction.setEnabled(filtersActive); try { initAndStartRevWalk(true); } catch (IllegalStateException e) { Activator.handleError(e.getMessage(), e.getCause(), true); return false; } return true; } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } }
public boolean inputSet() { try { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); if (this.input != null) return true; cancelRefreshJob(); setErrorMessage(null); Object o = super.getInput(); if (o == null) { setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } if (o instanceof IResource) { RepositoryMapping mapping = RepositoryMapping .getMapping((IResource) o); if (mapping != null) { Repository repo = mapping.getRepository(); input = new HistoryPageInput(repo, new IResource[] { (IResource) o }); } } else if (o instanceof RepositoryTreeNode) { RepositoryTreeNode repoNode = (RepositoryTreeNode) o; switch (repoNode.getType()) { case FILE: File file = ((FileNode) repoNode).getObject(); input = new HistoryPageInput(repoNode.getRepository(), new File[] { file }); break; case FOLDER: File folder = ((FolderNode) repoNode).getObject(); input = new HistoryPageInput(repoNode.getRepository(), new File[] { folder }); break; default: input = new HistoryPageInput(repoNode.getRepository()); } } else if (o instanceof HistoryPageInput) input = (HistoryPageInput) o; else if (o instanceof IAdaptable) { IResource resource = (IResource) ((IAdaptable) o) .getAdapter(IResource.class); if (resource != null) { RepositoryMapping mapping = RepositoryMapping .getMapping(resource); Repository repo = mapping.getRepository(); input = new HistoryPageInput(repo, new IResource[] { resource }); } } if (input == null) { this.name = ""; //$NON-NLS-1$ setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } final IResource[] inResources = input.getItems(); final File[] inFiles = input.getFileList(); if (inResources != null && inResources.length == 0) { this.name = ""; //$NON-NLS-1$ setErrorMessage(UIText.GitHistoryPage_NoInputMessage); return false; } this.name = calculateName(input); // disable the filters if we have a Repository as input boolean filtersActive = inResources != null || inFiles != null; actions.showAllRepoVersionsAction.setEnabled(filtersActive); actions.showAllProjectVersionsAction.setEnabled(filtersActive); // the repository itself has no notion of projects actions.showAllFolderVersionsAction.setEnabled(inResources != null); actions.showAllResourceVersionsAction.setEnabled(filtersActive); try { initAndStartRevWalk(true); } catch (IllegalStateException e) { Activator.handleError(e.getMessage(), e, true); return false; } return true; } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } }
diff --git a/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/ShowAreaRender.java b/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/ShowAreaRender.java index f8c411f9..15e78108 100644 --- a/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/ShowAreaRender.java +++ b/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/ShowAreaRender.java @@ -1,68 +1,68 @@ package org.sakaiproject.tool.messageforums.jsf; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.Renderer; /** * @author Chen Wen * @version $Id$ * */ public class ShowAreaRender extends Renderer { public boolean supportsComponentType(UIComponent component) { return (component instanceof ShowAreaComponent); } public void encodeBegin(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); String value = (String) component.getAttributes().get("value"); if((value!=null) && (!value.equals(""))) { int pos; // writer.write("<div>"); value = value.replaceAll("<strong>", "<b>"); value = value.replaceAll("</strong>", "</b>"); writer.write("<table border=\"1\" id=\"message_table\" cellpadding=\"7\" style=\"border-collapse: collapse;" + - " \"table-layout:fixed\" width=\"99%\"><tr width=\"95%\"><td width=\"100%\" STYLE=\"word-wrap: break-word\">"); + " \"table-layout:fixed\" width=\"90%\"><tr width=\"95%\"><td width=\"100%\" STYLE=\"word-wrap: break-word\">"); /* int blocks = value.length() % 200 ; for (int i=0; i<blocks; i++) { writer.write(value.substring(i*200, ((i+1)*200-1))); writer.flush(); } writer.write(value.substring(blocks*200, (value.length()-1))); writer.flush(); */ value = value.replaceAll("<a href=", "<a title=\"Open a new window\" target=\"_new\" href="); writer.write(value); writer.write("</td></tr></table>"); // writer.write("</div>"); } } public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); String value = (String) component.getAttributes().get("value"); if((value!=null) && (!value.equals(""))) { } } }
true
true
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); String value = (String) component.getAttributes().get("value"); if((value!=null) && (!value.equals(""))) { int pos; // writer.write("<div>"); value = value.replaceAll("<strong>", "<b>"); value = value.replaceAll("</strong>", "</b>"); writer.write("<table border=\"1\" id=\"message_table\" cellpadding=\"7\" style=\"border-collapse: collapse;" + " \"table-layout:fixed\" width=\"99%\"><tr width=\"95%\"><td width=\"100%\" STYLE=\"word-wrap: break-word\">"); /* int blocks = value.length() % 200 ; for (int i=0; i<blocks; i++) { writer.write(value.substring(i*200, ((i+1)*200-1))); writer.flush(); } writer.write(value.substring(blocks*200, (value.length()-1))); writer.flush(); */ value = value.replaceAll("<a href=", "<a title=\"Open a new window\" target=\"_new\" href="); writer.write(value); writer.write("</td></tr></table>"); // writer.write("</div>"); } }
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); String value = (String) component.getAttributes().get("value"); if((value!=null) && (!value.equals(""))) { int pos; // writer.write("<div>"); value = value.replaceAll("<strong>", "<b>"); value = value.replaceAll("</strong>", "</b>"); writer.write("<table border=\"1\" id=\"message_table\" cellpadding=\"7\" style=\"border-collapse: collapse;" + " \"table-layout:fixed\" width=\"90%\"><tr width=\"95%\"><td width=\"100%\" STYLE=\"word-wrap: break-word\">"); /* int blocks = value.length() % 200 ; for (int i=0; i<blocks; i++) { writer.write(value.substring(i*200, ((i+1)*200-1))); writer.flush(); } writer.write(value.substring(blocks*200, (value.length()-1))); writer.flush(); */ value = value.replaceAll("<a href=", "<a title=\"Open a new window\" target=\"_new\" href="); writer.write(value); writer.write("</td></tr></table>"); // writer.write("</div>"); } }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java index 7e9599939..fa97b5921 100644 --- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java +++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java @@ -1,373 +1,374 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/org/documents/epl-v10.php * * 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.ide.eclipse.adt.internal.project; import com.android.ide.eclipse.adt.AdtConstants; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.AndroidPrintStream; import com.android.ide.eclipse.adt.internal.build.BuildHelper; import com.android.ide.eclipse.adt.internal.build.DexException; import com.android.ide.eclipse.adt.internal.build.NativeLibInJarException; import com.android.ide.eclipse.adt.internal.build.ProguardExecException; import com.android.ide.eclipse.adt.internal.build.ProguardResultException; import com.android.ide.eclipse.adt.internal.sdk.ProjectState; import com.android.ide.eclipse.adt.internal.sdk.Sdk; import com.android.ide.eclipse.adt.io.IFileWrapper; import com.android.sdklib.SdkConstants; import com.android.sdklib.build.ApkCreationException; import com.android.sdklib.build.DuplicateFileException; import com.android.sdklib.internal.project.ProjectProperties; import com.android.sdklib.xml.AndroidManifest; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; /** * Export helper to export release version of APKs. */ public final class ExportHelper { private final static String TEMP_PREFIX = "android_"; //$NON-NLS-1$ /** * Exports a release version of the application created by the given project. * @param project the project to export * @param outputFile the file to write * @param key the key to used for signing. Can be null. * @param certificate the certificate used for signing. Can be null. * @param monitor */ public static void exportReleaseApk(IProject project, File outputFile, PrivateKey key, X509Certificate certificate, IProgressMonitor monitor) throws CoreException { // the export, takes the output of the precompiler & Java builders so it's // important to call build in case the auto-build option of the workspace is disabled. // Also enable dependency building to make sure everything is up to date. // However do not package the APK since we're going to do it manually here, using a // different output location. ProjectHelper.compileInReleaseMode(project, monitor); // if either key or certificate is null, ensure the other is null. if (key == null) { certificate = null; } else if (certificate == null) { key = null; } try { // check if the manifest declares debuggable as true. While this is a release build, // debuggable in the manifest will override this and generate a debug build IResource manifestResource = project.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML); if (manifestResource.getType() != IResource.FILE) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, String.format("%1$s missing.", SdkConstants.FN_ANDROID_MANIFEST_XML))); } IFileWrapper manifestFile = new IFileWrapper((IFile) manifestResource); boolean debugMode = AndroidManifest.getDebuggable(manifestFile); AndroidPrintStream fakeStream = new AndroidPrintStream(null, null, new OutputStream() { @Override public void write(int b) throws IOException { // do nothing } }); BuildHelper helper = new BuildHelper(project, fakeStream, fakeStream, debugMode, false /*verbose*/); // get the list of library projects ProjectState projectState = Sdk.getProjectState(project); List<IProject> libProjects = projectState.getFullLibraryProjects(); // Step 1. Package the resources. // tmp file for the packaged resource file. To not disturb the incremental builders // output, all intermediary files are created in tmp files. File resourceFile = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_RES); resourceFile.deleteOnExit(); // Make sure the PNG crunch cache is up to date helper.updateCrunchCache(); // package the resources. helper.packageResources( project.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML), libProjects, null, // res filter 0, // versionCode resourceFile.getParent(), resourceFile.getName()); // Step 2. Convert the byte code to Dalvik bytecode // tmp file for the packaged resource file. File dexFile = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_DEX); dexFile.deleteOnExit(); ProjectState state = Sdk.getProjectState(project); String proguardConfig = state.getProperties().getProperty( ProjectProperties.PROPERTY_PROGUARD_CONFIG); boolean runProguard = false; File proguardConfigFile = null; if (proguardConfig != null && proguardConfig.length() > 0) { proguardConfigFile = new File(proguardConfig); if (proguardConfigFile.isAbsolute() == false) { proguardConfigFile = new File(project.getLocation().toFile(), proguardConfig); } runProguard = proguardConfigFile.isFile(); } String[] dxInput; if (runProguard) { // the output of the main project (and any java-only project dependency) String[] projectOutputs = helper.getProjectJavaOutputs(); // create a jar from the output of these projects File inputJar = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_JAR); inputJar.deleteOnExit(); JarOutputStream jos = new JarOutputStream(new FileOutputStream(inputJar)); for (String po : projectOutputs) { File root = new File(po); if (root.exists()) { addFileToJar(jos, root, root); } } jos.close(); // get the other jar files String[] jarFiles = helper.getCompiledCodePaths(false /*includeProjectOutputs*/, null /*resourceMarker*/); // destination file for proguard File obfuscatedJar = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_JAR); obfuscatedJar.deleteOnExit(); // run proguard helper.runProguard(proguardConfigFile, inputJar, jarFiles, obfuscatedJar, new File(project.getLocation().toFile(), SdkConstants.FD_PROGUARD)); // dx input is proguard's output dxInput = new String[] { obfuscatedJar.getAbsolutePath() }; } else { // no proguard, simply get all the compiled code path: project output(s) + // jar file(s) dxInput = helper.getCompiledCodePaths(true /*includeProjectOutputs*/, null /*resourceMarker*/); } IJavaProject javaProject = JavaCore.create(project); List<IProject> javaProjects = ProjectHelper.getReferencedProjects(project); List<IJavaProject> referencedJavaProjects = BuildHelper.getJavaProjects( javaProjects); helper.executeDx(javaProject, dxInput, dexFile.getAbsolutePath()); // Step 3. Final package helper.finalPackage( resourceFile.getAbsolutePath(), dexFile.getAbsolutePath(), outputFile.getAbsolutePath(), javaProject, libProjects, referencedJavaProjects, key, certificate, null); //resourceMarker // success! } catch (CoreException e) { throw e; } catch (ProguardResultException e) { String msg = String.format("Proguard returned with error code %d. See console", e.getErrorCode()); AdtPlugin.printErrorToConsole(project, msg); AdtPlugin.printErrorToConsole(project, (Object[]) e.getOutput()); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, msg, e)); } catch (ProguardExecException e) { String msg = String.format("Failed to run proguard: %s", e.getMessage()); AdtPlugin.printErrorToConsole(project, msg); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, msg, e)); } catch (DuplicateFileException e) { String msg = String.format( "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s", e.getArchivePath(), e.getFile1(), e.getFile2()); AdtPlugin.printErrorToConsole(project, msg); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (NativeLibInJarException e) { String msg = e.getMessage(); AdtPlugin.printErrorToConsole(project, msg); AdtPlugin.printErrorToConsole(project, (Object[]) e.getAdditionalInfo()); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (DexException e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (ApkCreationException e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Failed to export application", e)); } finally { // move back to a debug build. // By using a normal build, we'll simply rebuild the debug version, and let the // builder decide whether to build the full package or not. ProjectHelper.buildWithDeps(project, IncrementalProjectBuilder.FULL_BUILD, monitor); + project.refreshLocal(IResource.DEPTH_INFINITE, monitor); } } /** * Exports an unsigned release APK after prompting the user for a location. * * <strong>Must be called from the UI thread.</strong> * * @param project the project to export */ public static void exportUnsignedReleaseApk(final IProject project) { Shell shell = Display.getCurrent().getActiveShell(); // create a default file name for the apk. String fileName = project.getName() + AdtConstants.DOT_ANDROID_PACKAGE; // Pop up the file save window to get the file location FileDialog fileDialog = new FileDialog(shell, SWT.SAVE); fileDialog.setText("Export Project"); fileDialog.setFileName(fileName); final String saveLocation = fileDialog.open(); if (saveLocation != null) { new Job("Android Release Export") { @Override protected IStatus run(IProgressMonitor monitor) { try { exportReleaseApk(project, new File(saveLocation), null, //key null, //certificate monitor); // this is unsigned export. Let's tell the developers to run zip align AdtPlugin.displayWarning("Android IDE Plug-in", String.format( "An unsigned package of the application was saved at\n%1$s\n\n" + "Before publishing the application you will need to:\n" + "- Sign the application with your release key,\n" + "- run zipalign on the signed package. ZipAlign is located in <SDK>/tools/\n\n" + "Aligning applications allows Android to use application resources\n" + "more efficiently.", saveLocation)); return Status.OK_STATUS; } catch (CoreException e) { AdtPlugin.displayError("Android IDE Plug-in", String.format( "Error exporting application:\n\n%1$s", e.getMessage())); return e.getStatus(); } } }.schedule(); } } /** * Adds a file to a jar file. * The <var>rootDirectory</var> dictates the path of the file inside the jar file. It must be * a parent of <var>file</var>. * @param jar the jar to add the file to * @param file the file to add * @param rootDirectory the rootDirectory. * @throws IOException */ private static void addFileToJar(JarOutputStream jar, File file, File rootDirectory) throws IOException { if (file.isDirectory()) { for (File child: file.listFiles()) { addFileToJar(jar, child, rootDirectory); } } else if (file.isFile()) { // check the extension String name = file.getName(); if (name.toLowerCase().endsWith(AdtConstants.DOT_CLASS) == false) { return; } String rootPath = rootDirectory.getAbsolutePath(); String path = file.getAbsolutePath(); path = path.substring(rootPath.length()).replace("\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$ if (path.charAt(0) == '/') { path = path.substring(1); } JarEntry entry = new JarEntry(path); entry.setTime(file.lastModified()); jar.putNextEntry(entry); // put the content of the file. byte[] buffer = new byte[1024]; int count; BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream(file)); while ((count = bis.read(buffer)) != -1) { jar.write(buffer, 0, count); } } finally { if (bis != null) { try { bis.close(); } catch (IOException ignore) { } } } jar.closeEntry(); } } }
true
true
public static void exportReleaseApk(IProject project, File outputFile, PrivateKey key, X509Certificate certificate, IProgressMonitor monitor) throws CoreException { // the export, takes the output of the precompiler & Java builders so it's // important to call build in case the auto-build option of the workspace is disabled. // Also enable dependency building to make sure everything is up to date. // However do not package the APK since we're going to do it manually here, using a // different output location. ProjectHelper.compileInReleaseMode(project, monitor); // if either key or certificate is null, ensure the other is null. if (key == null) { certificate = null; } else if (certificate == null) { key = null; } try { // check if the manifest declares debuggable as true. While this is a release build, // debuggable in the manifest will override this and generate a debug build IResource manifestResource = project.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML); if (manifestResource.getType() != IResource.FILE) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, String.format("%1$s missing.", SdkConstants.FN_ANDROID_MANIFEST_XML))); } IFileWrapper manifestFile = new IFileWrapper((IFile) manifestResource); boolean debugMode = AndroidManifest.getDebuggable(manifestFile); AndroidPrintStream fakeStream = new AndroidPrintStream(null, null, new OutputStream() { @Override public void write(int b) throws IOException { // do nothing } }); BuildHelper helper = new BuildHelper(project, fakeStream, fakeStream, debugMode, false /*verbose*/); // get the list of library projects ProjectState projectState = Sdk.getProjectState(project); List<IProject> libProjects = projectState.getFullLibraryProjects(); // Step 1. Package the resources. // tmp file for the packaged resource file. To not disturb the incremental builders // output, all intermediary files are created in tmp files. File resourceFile = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_RES); resourceFile.deleteOnExit(); // Make sure the PNG crunch cache is up to date helper.updateCrunchCache(); // package the resources. helper.packageResources( project.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML), libProjects, null, // res filter 0, // versionCode resourceFile.getParent(), resourceFile.getName()); // Step 2. Convert the byte code to Dalvik bytecode // tmp file for the packaged resource file. File dexFile = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_DEX); dexFile.deleteOnExit(); ProjectState state = Sdk.getProjectState(project); String proguardConfig = state.getProperties().getProperty( ProjectProperties.PROPERTY_PROGUARD_CONFIG); boolean runProguard = false; File proguardConfigFile = null; if (proguardConfig != null && proguardConfig.length() > 0) { proguardConfigFile = new File(proguardConfig); if (proguardConfigFile.isAbsolute() == false) { proguardConfigFile = new File(project.getLocation().toFile(), proguardConfig); } runProguard = proguardConfigFile.isFile(); } String[] dxInput; if (runProguard) { // the output of the main project (and any java-only project dependency) String[] projectOutputs = helper.getProjectJavaOutputs(); // create a jar from the output of these projects File inputJar = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_JAR); inputJar.deleteOnExit(); JarOutputStream jos = new JarOutputStream(new FileOutputStream(inputJar)); for (String po : projectOutputs) { File root = new File(po); if (root.exists()) { addFileToJar(jos, root, root); } } jos.close(); // get the other jar files String[] jarFiles = helper.getCompiledCodePaths(false /*includeProjectOutputs*/, null /*resourceMarker*/); // destination file for proguard File obfuscatedJar = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_JAR); obfuscatedJar.deleteOnExit(); // run proguard helper.runProguard(proguardConfigFile, inputJar, jarFiles, obfuscatedJar, new File(project.getLocation().toFile(), SdkConstants.FD_PROGUARD)); // dx input is proguard's output dxInput = new String[] { obfuscatedJar.getAbsolutePath() }; } else { // no proguard, simply get all the compiled code path: project output(s) + // jar file(s) dxInput = helper.getCompiledCodePaths(true /*includeProjectOutputs*/, null /*resourceMarker*/); } IJavaProject javaProject = JavaCore.create(project); List<IProject> javaProjects = ProjectHelper.getReferencedProjects(project); List<IJavaProject> referencedJavaProjects = BuildHelper.getJavaProjects( javaProjects); helper.executeDx(javaProject, dxInput, dexFile.getAbsolutePath()); // Step 3. Final package helper.finalPackage( resourceFile.getAbsolutePath(), dexFile.getAbsolutePath(), outputFile.getAbsolutePath(), javaProject, libProjects, referencedJavaProjects, key, certificate, null); //resourceMarker // success! } catch (CoreException e) { throw e; } catch (ProguardResultException e) { String msg = String.format("Proguard returned with error code %d. See console", e.getErrorCode()); AdtPlugin.printErrorToConsole(project, msg); AdtPlugin.printErrorToConsole(project, (Object[]) e.getOutput()); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, msg, e)); } catch (ProguardExecException e) { String msg = String.format("Failed to run proguard: %s", e.getMessage()); AdtPlugin.printErrorToConsole(project, msg); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, msg, e)); } catch (DuplicateFileException e) { String msg = String.format( "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s", e.getArchivePath(), e.getFile1(), e.getFile2()); AdtPlugin.printErrorToConsole(project, msg); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (NativeLibInJarException e) { String msg = e.getMessage(); AdtPlugin.printErrorToConsole(project, msg); AdtPlugin.printErrorToConsole(project, (Object[]) e.getAdditionalInfo()); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (DexException e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (ApkCreationException e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Failed to export application", e)); } finally { // move back to a debug build. // By using a normal build, we'll simply rebuild the debug version, and let the // builder decide whether to build the full package or not. ProjectHelper.buildWithDeps(project, IncrementalProjectBuilder.FULL_BUILD, monitor); } }
public static void exportReleaseApk(IProject project, File outputFile, PrivateKey key, X509Certificate certificate, IProgressMonitor monitor) throws CoreException { // the export, takes the output of the precompiler & Java builders so it's // important to call build in case the auto-build option of the workspace is disabled. // Also enable dependency building to make sure everything is up to date. // However do not package the APK since we're going to do it manually here, using a // different output location. ProjectHelper.compileInReleaseMode(project, monitor); // if either key or certificate is null, ensure the other is null. if (key == null) { certificate = null; } else if (certificate == null) { key = null; } try { // check if the manifest declares debuggable as true. While this is a release build, // debuggable in the manifest will override this and generate a debug build IResource manifestResource = project.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML); if (manifestResource.getType() != IResource.FILE) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, String.format("%1$s missing.", SdkConstants.FN_ANDROID_MANIFEST_XML))); } IFileWrapper manifestFile = new IFileWrapper((IFile) manifestResource); boolean debugMode = AndroidManifest.getDebuggable(manifestFile); AndroidPrintStream fakeStream = new AndroidPrintStream(null, null, new OutputStream() { @Override public void write(int b) throws IOException { // do nothing } }); BuildHelper helper = new BuildHelper(project, fakeStream, fakeStream, debugMode, false /*verbose*/); // get the list of library projects ProjectState projectState = Sdk.getProjectState(project); List<IProject> libProjects = projectState.getFullLibraryProjects(); // Step 1. Package the resources. // tmp file for the packaged resource file. To not disturb the incremental builders // output, all intermediary files are created in tmp files. File resourceFile = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_RES); resourceFile.deleteOnExit(); // Make sure the PNG crunch cache is up to date helper.updateCrunchCache(); // package the resources. helper.packageResources( project.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML), libProjects, null, // res filter 0, // versionCode resourceFile.getParent(), resourceFile.getName()); // Step 2. Convert the byte code to Dalvik bytecode // tmp file for the packaged resource file. File dexFile = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_DEX); dexFile.deleteOnExit(); ProjectState state = Sdk.getProjectState(project); String proguardConfig = state.getProperties().getProperty( ProjectProperties.PROPERTY_PROGUARD_CONFIG); boolean runProguard = false; File proguardConfigFile = null; if (proguardConfig != null && proguardConfig.length() > 0) { proguardConfigFile = new File(proguardConfig); if (proguardConfigFile.isAbsolute() == false) { proguardConfigFile = new File(project.getLocation().toFile(), proguardConfig); } runProguard = proguardConfigFile.isFile(); } String[] dxInput; if (runProguard) { // the output of the main project (and any java-only project dependency) String[] projectOutputs = helper.getProjectJavaOutputs(); // create a jar from the output of these projects File inputJar = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_JAR); inputJar.deleteOnExit(); JarOutputStream jos = new JarOutputStream(new FileOutputStream(inputJar)); for (String po : projectOutputs) { File root = new File(po); if (root.exists()) { addFileToJar(jos, root, root); } } jos.close(); // get the other jar files String[] jarFiles = helper.getCompiledCodePaths(false /*includeProjectOutputs*/, null /*resourceMarker*/); // destination file for proguard File obfuscatedJar = File.createTempFile(TEMP_PREFIX, AdtConstants.DOT_JAR); obfuscatedJar.deleteOnExit(); // run proguard helper.runProguard(proguardConfigFile, inputJar, jarFiles, obfuscatedJar, new File(project.getLocation().toFile(), SdkConstants.FD_PROGUARD)); // dx input is proguard's output dxInput = new String[] { obfuscatedJar.getAbsolutePath() }; } else { // no proguard, simply get all the compiled code path: project output(s) + // jar file(s) dxInput = helper.getCompiledCodePaths(true /*includeProjectOutputs*/, null /*resourceMarker*/); } IJavaProject javaProject = JavaCore.create(project); List<IProject> javaProjects = ProjectHelper.getReferencedProjects(project); List<IJavaProject> referencedJavaProjects = BuildHelper.getJavaProjects( javaProjects); helper.executeDx(javaProject, dxInput, dexFile.getAbsolutePath()); // Step 3. Final package helper.finalPackage( resourceFile.getAbsolutePath(), dexFile.getAbsolutePath(), outputFile.getAbsolutePath(), javaProject, libProjects, referencedJavaProjects, key, certificate, null); //resourceMarker // success! } catch (CoreException e) { throw e; } catch (ProguardResultException e) { String msg = String.format("Proguard returned with error code %d. See console", e.getErrorCode()); AdtPlugin.printErrorToConsole(project, msg); AdtPlugin.printErrorToConsole(project, (Object[]) e.getOutput()); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, msg, e)); } catch (ProguardExecException e) { String msg = String.format("Failed to run proguard: %s", e.getMessage()); AdtPlugin.printErrorToConsole(project, msg); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, msg, e)); } catch (DuplicateFileException e) { String msg = String.format( "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s", e.getArchivePath(), e.getFile1(), e.getFile2()); AdtPlugin.printErrorToConsole(project, msg); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (NativeLibInJarException e) { String msg = e.getMessage(); AdtPlugin.printErrorToConsole(project, msg); AdtPlugin.printErrorToConsole(project, (Object[]) e.getAdditionalInfo()); throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (DexException e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (ApkCreationException e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e)); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Failed to export application", e)); } finally { // move back to a debug build. // By using a normal build, we'll simply rebuild the debug version, and let the // builder decide whether to build the full package or not. ProjectHelper.buildWithDeps(project, IncrementalProjectBuilder.FULL_BUILD, monitor); project.refreshLocal(IResource.DEPTH_INFINITE, monitor); } }
diff --git a/src/cnt/demo/NetworkingDemo.java b/src/cnt/demo/NetworkingDemo.java index 1133d18..aa23b77 100644 --- a/src/cnt/demo/NetworkingDemo.java +++ b/src/cnt/demo/NetworkingDemo.java @@ -1,130 +1,130 @@ /** * Coop Network Tetris — A cooperative tetris over the Internet. * * Copyright © 2012 Calle Lejdbrandt, Mattias Andrée, Peyman Eshtiagh * * Project for prutt12 (DD2385), KTH. */ package cnt.demo; import cnt.game.*; import cnt.network.*; import cnt.*; import java.awt.*; import java.util.*; import java.io.*; import java.net.*; /** * Networking demo class * * @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a> */ public class NetworkingDemo { /** * Non-constructor */ private NetworkingDemo() { assert false : "You may not create instances of this class [NetworkingDemo]."; } /** * This is the main entry point of the demo * * @param args Startup arguments, unused * * @throws Exception On total failure */ public static void main(final String... args) throws Exception { final int PORT = 9999; final ServerSocket server = new ServerSocket(PORT); final Thread thread0 = new Thread() { /** * {@inheritDoc} */ @Override public void run() { try { final Socket sock = server.accept(); final InputStream in = sock.getInputStream(); final OutputStream out = sock.getOutputStream(); final BlackboardNetworking network0 = new BlackboardNetworking(new GameNetworking(new ObjectNetworking(in, out))); Blackboard.broadcastMessage(new Blackboard.LocalPlayer(new Player("Mattias", Color.RED.getRGB()))); System.out.println("network0: sending message: ChatMessage"); Blackboard.broadcastMessage(new Blackboard.ChatMessage(new Player("Mattias", Color.RED.getRGB()), "sending a message")); System.out.println("network0: sending message: SystemMessage"); - Blackboard.broadcastMessage(new Blackboard.SystemMessage(null, "system message")); + Blackboard.broadcastMessage(new Blackboard.SystemMessage(null, "system message (ignored)")); System.out.println("network0: sending message: UserMessage"); - Blackboard.broadcastMessage(new Blackboard.UserMessage("local user chat message")); + Blackboard.broadcastMessage(new Blackboard.UserMessage("local user chat message (converted)")); System.out.println("network0: sending message: MatrixPatch"); Blackboard.broadcastMessage(new Blackboard.MatrixPatch(new boolean[2][2], new Block[2][2], 0, 0)); } catch (final Throwable err) { err.printStackTrace(System.err); } } }; final Thread thread1 = new Thread() { /** * {@inheritDoc} */ @Override public void run() { try { final Socket sock = new Socket("127.0.0.1", PORT); final InputStream in = sock.getInputStream(); final OutputStream out = sock.getOutputStream(); final BlackboardNetworking network1 = new BlackboardNetworking(new GameNetworking(new ObjectNetworking(in, out))) { /** * {@inheritDoc} */ @Override protected void broadcastMessage(final Blackboard.BlackboardMessage message) throws IOException, ClassNotFoundException { System.out.println("network1: received blackboard message: " + message.getClass().toString()); } }; Blackboard.unregisterObserver(network1); - for (int i = 0; i < 4; i++) + for (int i = 0; i < 3; i++) network1.receiveAndBroadcast(); } catch (final Throwable err) { err.printStackTrace(System.err); } } }; thread0.start(); Thread.sleep(200); thread1.start(); } }
false
true
public static void main(final String... args) throws Exception { final int PORT = 9999; final ServerSocket server = new ServerSocket(PORT); final Thread thread0 = new Thread() { /** * {@inheritDoc} */ @Override public void run() { try { final Socket sock = server.accept(); final InputStream in = sock.getInputStream(); final OutputStream out = sock.getOutputStream(); final BlackboardNetworking network0 = new BlackboardNetworking(new GameNetworking(new ObjectNetworking(in, out))); Blackboard.broadcastMessage(new Blackboard.LocalPlayer(new Player("Mattias", Color.RED.getRGB()))); System.out.println("network0: sending message: ChatMessage"); Blackboard.broadcastMessage(new Blackboard.ChatMessage(new Player("Mattias", Color.RED.getRGB()), "sending a message")); System.out.println("network0: sending message: SystemMessage"); Blackboard.broadcastMessage(new Blackboard.SystemMessage(null, "system message")); System.out.println("network0: sending message: UserMessage"); Blackboard.broadcastMessage(new Blackboard.UserMessage("local user chat message")); System.out.println("network0: sending message: MatrixPatch"); Blackboard.broadcastMessage(new Blackboard.MatrixPatch(new boolean[2][2], new Block[2][2], 0, 0)); } catch (final Throwable err) { err.printStackTrace(System.err); } } }; final Thread thread1 = new Thread() { /** * {@inheritDoc} */ @Override public void run() { try { final Socket sock = new Socket("127.0.0.1", PORT); final InputStream in = sock.getInputStream(); final OutputStream out = sock.getOutputStream(); final BlackboardNetworking network1 = new BlackboardNetworking(new GameNetworking(new ObjectNetworking(in, out))) { /** * {@inheritDoc} */ @Override protected void broadcastMessage(final Blackboard.BlackboardMessage message) throws IOException, ClassNotFoundException { System.out.println("network1: received blackboard message: " + message.getClass().toString()); } }; Blackboard.unregisterObserver(network1); for (int i = 0; i < 4; i++) network1.receiveAndBroadcast(); } catch (final Throwable err) { err.printStackTrace(System.err); } } }; thread0.start(); Thread.sleep(200); thread1.start(); }
public static void main(final String... args) throws Exception { final int PORT = 9999; final ServerSocket server = new ServerSocket(PORT); final Thread thread0 = new Thread() { /** * {@inheritDoc} */ @Override public void run() { try { final Socket sock = server.accept(); final InputStream in = sock.getInputStream(); final OutputStream out = sock.getOutputStream(); final BlackboardNetworking network0 = new BlackboardNetworking(new GameNetworking(new ObjectNetworking(in, out))); Blackboard.broadcastMessage(new Blackboard.LocalPlayer(new Player("Mattias", Color.RED.getRGB()))); System.out.println("network0: sending message: ChatMessage"); Blackboard.broadcastMessage(new Blackboard.ChatMessage(new Player("Mattias", Color.RED.getRGB()), "sending a message")); System.out.println("network0: sending message: SystemMessage"); Blackboard.broadcastMessage(new Blackboard.SystemMessage(null, "system message (ignored)")); System.out.println("network0: sending message: UserMessage"); Blackboard.broadcastMessage(new Blackboard.UserMessage("local user chat message (converted)")); System.out.println("network0: sending message: MatrixPatch"); Blackboard.broadcastMessage(new Blackboard.MatrixPatch(new boolean[2][2], new Block[2][2], 0, 0)); } catch (final Throwable err) { err.printStackTrace(System.err); } } }; final Thread thread1 = new Thread() { /** * {@inheritDoc} */ @Override public void run() { try { final Socket sock = new Socket("127.0.0.1", PORT); final InputStream in = sock.getInputStream(); final OutputStream out = sock.getOutputStream(); final BlackboardNetworking network1 = new BlackboardNetworking(new GameNetworking(new ObjectNetworking(in, out))) { /** * {@inheritDoc} */ @Override protected void broadcastMessage(final Blackboard.BlackboardMessage message) throws IOException, ClassNotFoundException { System.out.println("network1: received blackboard message: " + message.getClass().toString()); } }; Blackboard.unregisterObserver(network1); for (int i = 0; i < 3; i++) network1.receiveAndBroadcast(); } catch (final Throwable err) { err.printStackTrace(System.err); } } }; thread0.start(); Thread.sleep(200); thread1.start(); }
diff --git a/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/SequenceDisplay.java b/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/SequenceDisplay.java index 7813e1651..dfd4af726 100644 --- a/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/SequenceDisplay.java +++ b/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/SequenceDisplay.java @@ -1,537 +1,537 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * created at May 26, 2008 */ package org.biojava.bio.structure.gui; import java.awt.Color; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.biojava.bio.structure.Atom; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.ChainImpl; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.align.StructurePairAligner; import org.biojava.bio.structure.align.pairwise.AlternativeAlignment; import org.biojava.bio.structure.gui.events.AlignmentPositionListener; import org.biojava.bio.structure.io.PDBFileReader; import org.biojava.bio.structure.gui.SequenceDisplay; import org.biojava.bio.structure.gui.util.AlignedPosition; import org.biojava.bio.structure.gui.util.SequenceMouseListener; import org.biojava.bio.structure.gui.util.SequenceScalePanel; /** A sequence display that can show the results of a protein structure alignment. * * @author Andreas Prlic * @since 1.7 */ public class SequenceDisplay extends JPanel implements ChangeListener { /** * */ private static final long serialVersionUID = -1829252532712454236L; Structure structure1; Structure structure2; AlternativeAlignment alig; StructurePairAligner structurePairAligner; SequenceScalePanel panel1; SequenceScalePanel panel2; JSlider residueSizeSlider; JLabel percentageDisplay; int[] idx1; int[] idx2; /** the maximum value that the scale can get * */ public static final int MAX_SCALE = 10; Logger logger = Logger.getLogger("org.biojava"); List<AlignedPosition> apos; float scale; SequenceMouseListener mouseListener1; SequenceMouseListener mouseListener2; JLabel label1; JLabel label2; public static void main(String[] args){ try { PDBFileReader pdbr = new PDBFileReader(); pdbr.setPath("/Users/andreas/WORK/PDB/"); //String pdb1 = "1crl"; //String pdb2 = "1ede"; String pdb1 = "1buz"; String pdb2 = "5pti"; // NO NEED TO DO CHANGE ANYTHING BELOW HERE... StructurePairAligner sc = new StructurePairAligner(); // step1 : read molecules System.out.println("aligning " + pdb1 + " vs. " + pdb2); Structure s1 = pdbr.getStructureById(pdb1); Structure s2 = pdbr.getStructureById(pdb2); // step 2 : do the calculations sc.align(s1,s2); AlternativeAlignment[] aligs = sc.getAlignments(); SequenceDisplay displ = new SequenceDisplay(sc); displ.setStructure1(s1); displ.setStructure2(s2); displ.setAlternativeAlignment(aligs[0]); displ.updateDisplay(); JFrame frame = new JFrame("Sequences for AlternativeAlignment ["+0+"]"); frame.getContentPane().add(displ); frame.pack(); frame.setVisible(true); frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ JFrame f = (JFrame) e.getSource(); f.setVisible(false); f.dispose(); } }); } catch (Exception e){ e.printStackTrace(); } } public SequenceDisplay(StructurePairAligner structurePairAligner){ super(); structure1 = null; structure2 = null; alig = null; this.structurePairAligner = structurePairAligner; panel1 = new SequenceScalePanel(1); panel2 = new SequenceScalePanel(2); mouseListener1 = new SequenceMouseListener(this); panel1.addMouseListener(mouseListener1); panel1.addMouseMotionListener(mouseListener1); mouseListener2 = new SequenceMouseListener(this); panel2.addMouseListener(mouseListener2); panel2.addMouseMotionListener(mouseListener2); //SequenceMouseListener ml = new SequenceMouseListener(this); //this.addMouseListener(ml); //this.addMouseMotionListener(ml); Box vBox = Box.createVerticalBox(); Box hBox1 = Box.createHorizontalBox(); Box hBox2 = Box.createHorizontalBox(); label1 = new JLabel(); hBox1.add(label1); label2 = new JLabel(); hBox2.add(label2); hBox1.add(panel1); hBox2.add(panel2); vBox.add(hBox1); vBox.add(hBox2); int RES_MIN = 1; int RES_MAX = 100; int RES_INIT = 100; residueSizeSlider = new JSlider(JSlider.HORIZONTAL, RES_MIN, RES_MAX, RES_INIT); residueSizeSlider.setInverted(true); //residueSizeSlider.setMajorTickSpacing(5); - //residueSizeSl�ider.setMinorTickSpacing(2); + //residueSizeSlider.setMinorTickSpacing(2); residueSizeSlider.setPaintTicks(false); residueSizeSlider.setPaintLabels(false); residueSizeSlider.addChangeListener(this); //residueSizeSlider.setPreferredSize(new Dimension(100,15)); percentageDisplay = new JLabel("100 %"); Box hBox = Box.createHorizontalBox(); hBox.setBackground(Color.white); hBox.add(Box.createHorizontalGlue()); hBox.add(residueSizeSlider); hBox.add(percentageDisplay); hBox.add(Box.createHorizontalGlue()); //vBox.add(hBox); JScrollPane scroll = new JScrollPane(vBox); //scroll.setPreferredSize(new Dimension(500,160)); Box vBox2 = Box.createVerticalBox(); vBox2.add(scroll); vBox2.add(hBox); //vBox2.setPreferredSize(new Dimension(500,160)); //vBox2.setSize(new Dimension(500,160)); //vBox2.setMinimumSize(new Dimension(500,160)); //vBox2.setMaximumSize(new Dimension(500,160)); this.setPreferredSize(new Dimension(500,100)); this.add(vBox2); this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); apos = new ArrayList<AlignedPosition>(); } public void clearListeners(){ mouseListener1.clearListeners(); mouseListener2.clearListeners(); } public void addAlignmentPositionListener(AlignmentPositionListener li){ mouseListener1.addAlignmentPositionListener(li); mouseListener2.addAlignmentPositionListener(li); } public StructurePairAligner getStructurePairAligner() { return structurePairAligner; } public void setStructurePairAligner(StructurePairAligner structurePairAligner) { this.structurePairAligner = structurePairAligner; } /** get the identical position in the alignment * * @return identical positions for structure1 */ public int[] getIdx1() { return idx1; } /** set the identical positions in the alignment * * @param idx identical positions for structure1 */ private void setIdx1(int[] idx) { this.idx1 = idx; } /** get the identical position in the alignment * * @return identical positions for structure2 */ public int[] getIdx2() { return idx2; } /** set the identical positions in the alignment * * @param idx identical positions for structure2 */ private void setIdx2(int[] idx) { this.idx2 = idx; } private void buildAligMap(){ apos.clear(); int gap = 0; int gpos1 = 0; int gpos2 = 0; for (int pos = 0 ; pos < idx1.length ; pos ++){ int p1 = idx1[pos]; int p2 = idx2[pos]; int end = Math.max(p1,p2); //System.out.println("p1: " + p1 + " p2: " + p2 ); // fill up gaps... for (;gap<end;gap++){ AlignedPosition m = new AlignedPosition(); if ( gpos1 < p1){ m.setPos1(gpos1); gpos1++; } if ( gpos2 < p2){ m.setPos2(gpos2); gpos2++; } m.setEquivalent(AlignedPosition.NOT_ALIGNED); //System.out.println(m + " => " + end); apos.add(m); } // add this aligned position AlignedPosition m = new AlignedPosition(); m.setPos1(p1); m.setPos2(p2); m.setEquivalent(AlignedPosition.EQUIVALENT); //System.out.println(m); apos.add(m); gpos1++; gpos2++; gap++; } //System.out.println(apos); } private void setAtoms(Structure s, SequenceScalePanel panel){ if ( structurePairAligner == null){ System.err.println("StructurePairAligner has not been set"); return; } Atom[] ca1 = structurePairAligner.getAlignmentAtoms(s); Chain c = new ChainImpl(); c.setName("1"); for (Atom atom : ca1) { Group g = atom.getParent(); Chain parentChain = g.getParent(); c.addGroup(g); // hack for Jmol? g.setParent(parentChain); } panel.setChain(c); } //TODO: add a method to allow the display if the structure alignment // has been called with setting the atoms directly public void setStructure1(Structure structure){ this.structure1 = structure; if ( structure != null) { setAtoms(structure1,panel1); label1.setText(structure.getPDBCode()); label1.repaint(); } } public void setStructure2(Structure structure){ this.structure2 = structure; if ( structure != null){ setAtoms(structure2,panel2); label2.setText(structure.getPDBCode()); label2.repaint(); } } public void setAlternativeAlignment(AlternativeAlignment alig){ this.alig = alig; this.setIdx1(alig.getIdx1()); this.setIdx2(alig.getIdx2()); buildAligMap(); panel1.setAligMap(apos); panel2.setAligMap(apos); updateDisplay(); } public List<AlignedPosition> getAligMap(){ return apos; } public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); //if (!source.getValueIsAdjusting()) { int residueSize = (int)source.getValue(); calcScale(residueSize); updatePercentageDisplay(); this.repaint(); this.revalidate(); //this.updateUI(); //int width = getTotalWidth(); //int height = getTotalHeight(); //Dimension d = new Dimension(width,height); //logger.info("setting preferred size" + width + " " + height); //this.setPreferredSize(d); //this.setSize(d); // } } public void updateDisplay(){ int residueSize = (int)residueSizeSlider.getValue(); calcScale(residueSize); updatePercentageDisplay(); this.repaint(); this.revalidate(); } private void updatePercentageDisplay(){ int perc = residueSizeSlider.getValue(); percentageDisplay.setText(perc+ " %"); } private int getMaxSequenceLength(){ int l1 = panel1.getChain().getAtomGroups("amino").size(); int l2 = panel2.getChain().getAtomGroups("amino").size(); if ( l1 > l2) return l1; else return l2; } /** calculate the float that is used for display. * 1 * scale = size of 1 amino acid (in pixel). * maximum @see MAX_SCALE * @param zoomFactor * @return a float that is the display "scale" - an internal value required for paintin. * user should only interact with the zoomfactor ... */ private float getScaleForZoom(int zoomFactor){ if ( zoomFactor > 100) zoomFactor = 100; if ( zoomFactor < 1) zoomFactor = 1; int DEFAULT_X_START = SequenceScalePanel.DEFAULT_X_START; int DEFAULT_X_RIGHT_BORDER = SequenceScalePanel.DEFAULT_X_RIGHT_BORDER; int seqLength = getMaxSequenceLength(); // the maximum width depends on the size of the parent Component int width=getWidth(); float s = width / (float) ( seqLength + DEFAULT_X_START + DEFAULT_X_RIGHT_BORDER ); //logger.info("scale for 100% " + s + " " + seqLength + " " + zoomFactor); s = (100) * s / ( zoomFactor * 1.0f) ; if ( s > MAX_SCALE) s = MAX_SCALE; //logger.info("but changed to " + s); return s; } /** a value of 100 means that the whole sequence should be displayed in the current visible window * a factor of 1 means that one amino acid shoud be drawn as big as possible * * @param zoomFactor - a value between 1 and 100 * * */ public void calcScale(int zoomFactor){ float s = getScaleForZoom(zoomFactor); scale = s; //logger.info("calc scale zoom:"+zoomFactor+ " s: " + s); panel1.setScale(s); panel2.setScale(s); panel1.repaint(); panel2.repaint(); //return scale; } public float getScale(){ return scale; } }
true
true
public SequenceDisplay(StructurePairAligner structurePairAligner){ super(); structure1 = null; structure2 = null; alig = null; this.structurePairAligner = structurePairAligner; panel1 = new SequenceScalePanel(1); panel2 = new SequenceScalePanel(2); mouseListener1 = new SequenceMouseListener(this); panel1.addMouseListener(mouseListener1); panel1.addMouseMotionListener(mouseListener1); mouseListener2 = new SequenceMouseListener(this); panel2.addMouseListener(mouseListener2); panel2.addMouseMotionListener(mouseListener2); //SequenceMouseListener ml = new SequenceMouseListener(this); //this.addMouseListener(ml); //this.addMouseMotionListener(ml); Box vBox = Box.createVerticalBox(); Box hBox1 = Box.createHorizontalBox(); Box hBox2 = Box.createHorizontalBox(); label1 = new JLabel(); hBox1.add(label1); label2 = new JLabel(); hBox2.add(label2); hBox1.add(panel1); hBox2.add(panel2); vBox.add(hBox1); vBox.add(hBox2); int RES_MIN = 1; int RES_MAX = 100; int RES_INIT = 100; residueSizeSlider = new JSlider(JSlider.HORIZONTAL, RES_MIN, RES_MAX, RES_INIT); residueSizeSlider.setInverted(true); //residueSizeSlider.setMajorTickSpacing(5); //residueSizeSl�ider.setMinorTickSpacing(2); residueSizeSlider.setPaintTicks(false); residueSizeSlider.setPaintLabels(false); residueSizeSlider.addChangeListener(this); //residueSizeSlider.setPreferredSize(new Dimension(100,15)); percentageDisplay = new JLabel("100 %"); Box hBox = Box.createHorizontalBox(); hBox.setBackground(Color.white); hBox.add(Box.createHorizontalGlue()); hBox.add(residueSizeSlider); hBox.add(percentageDisplay); hBox.add(Box.createHorizontalGlue()); //vBox.add(hBox); JScrollPane scroll = new JScrollPane(vBox); //scroll.setPreferredSize(new Dimension(500,160)); Box vBox2 = Box.createVerticalBox(); vBox2.add(scroll); vBox2.add(hBox); //vBox2.setPreferredSize(new Dimension(500,160)); //vBox2.setSize(new Dimension(500,160)); //vBox2.setMinimumSize(new Dimension(500,160)); //vBox2.setMaximumSize(new Dimension(500,160)); this.setPreferredSize(new Dimension(500,100)); this.add(vBox2); this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); apos = new ArrayList<AlignedPosition>(); }
public SequenceDisplay(StructurePairAligner structurePairAligner){ super(); structure1 = null; structure2 = null; alig = null; this.structurePairAligner = structurePairAligner; panel1 = new SequenceScalePanel(1); panel2 = new SequenceScalePanel(2); mouseListener1 = new SequenceMouseListener(this); panel1.addMouseListener(mouseListener1); panel1.addMouseMotionListener(mouseListener1); mouseListener2 = new SequenceMouseListener(this); panel2.addMouseListener(mouseListener2); panel2.addMouseMotionListener(mouseListener2); //SequenceMouseListener ml = new SequenceMouseListener(this); //this.addMouseListener(ml); //this.addMouseMotionListener(ml); Box vBox = Box.createVerticalBox(); Box hBox1 = Box.createHorizontalBox(); Box hBox2 = Box.createHorizontalBox(); label1 = new JLabel(); hBox1.add(label1); label2 = new JLabel(); hBox2.add(label2); hBox1.add(panel1); hBox2.add(panel2); vBox.add(hBox1); vBox.add(hBox2); int RES_MIN = 1; int RES_MAX = 100; int RES_INIT = 100; residueSizeSlider = new JSlider(JSlider.HORIZONTAL, RES_MIN, RES_MAX, RES_INIT); residueSizeSlider.setInverted(true); //residueSizeSlider.setMajorTickSpacing(5); //residueSizeSlider.setMinorTickSpacing(2); residueSizeSlider.setPaintTicks(false); residueSizeSlider.setPaintLabels(false); residueSizeSlider.addChangeListener(this); //residueSizeSlider.setPreferredSize(new Dimension(100,15)); percentageDisplay = new JLabel("100 %"); Box hBox = Box.createHorizontalBox(); hBox.setBackground(Color.white); hBox.add(Box.createHorizontalGlue()); hBox.add(residueSizeSlider); hBox.add(percentageDisplay); hBox.add(Box.createHorizontalGlue()); //vBox.add(hBox); JScrollPane scroll = new JScrollPane(vBox); //scroll.setPreferredSize(new Dimension(500,160)); Box vBox2 = Box.createVerticalBox(); vBox2.add(scroll); vBox2.add(hBox); //vBox2.setPreferredSize(new Dimension(500,160)); //vBox2.setSize(new Dimension(500,160)); //vBox2.setMinimumSize(new Dimension(500,160)); //vBox2.setMaximumSize(new Dimension(500,160)); this.setPreferredSize(new Dimension(500,100)); this.add(vBox2); this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); apos = new ArrayList<AlignedPosition>(); }
diff --git a/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java b/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java index bbd37e1f..7f2c5f58 100644 --- a/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java +++ b/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java @@ -1,1480 +1,1482 @@ /** * */ package com.pace.base.project.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.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 org.apache.log4j.Logger; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.pace.base.PafErrSeverity; import com.pace.base.PafException; import com.pace.base.project.ExcelPaceProjectConstants; import com.pace.base.project.ExcelProjectDataErrorException; import com.pace.base.project.ProjectDataError; import com.pace.base.project.ProjectElementId; import com.pace.base.project.excel.PafExcelInput; import com.pace.base.project.excel.PafExcelRow; import com.pace.base.project.excel.PafExcelValueObject; import com.pace.base.utility.CollectionsUtil; import com.pace.base.utility.StringUtils; /** * @author jmilliron * */ public class PafExcelUtil { private static final Logger logger = Logger.getLogger(PafExcelUtil.class); /** * * A user can read from an existing workbook via the input, or pass have this method create a new * workbook reference and read from that. The main objective of this method is to read in a sheet from * an existing workbook and to convert the data from that sheet into a model pace can use. * * If input doesn't have a column limit, a default of 100 columns will be read. * * @param input input meta data used by method to read in sheet * @return a list of paf row's. * @throws PafException */ public static List<PafExcelRow> readExcelSheet(PafExcelInput input) throws PafException { validateReadInput(input); Workbook wb = null; if ( input.getWorkbook() != null ) { wb = input.getWorkbook(); } else { wb = readWorkbook(input.getFullWorkbookName()); } List<PafExcelRow> pafRowList = new ArrayList<PafExcelRow>(); if (wb ==null) logger.info("Workbook(WB) is null"); if ( wb != null ) { logger.info("Workbook(WB) exists"); Sheet sheet = wb.getSheet(input.getSheetId()); if (sheet ==null) logger.info("Sheet is null"); if ( sheet != null ) { logger.info("Sheet is not null"); int sheetLastRowNumber = sheet.getLastRowNum(); //if row limit is less than max row number on sheet, reset last row number to row limit. if ( input.getRowLimit() > 0 && input.getRowLimit() < sheetLastRowNumber ) { sheetLastRowNumber = input.getRowLimit(); //subtract one to aline with 0 based indexes sheetLastRowNumber--; } int startColumnIndex = 0; if ( input.getStartDataReadColumnIndex() != null && input.getStartDataReadColumnIndex() < input.getColumnLimit()) { startColumnIndex = input.getStartDataReadColumnIndex(); } PafExcelRow pafRow = null; OUTTER_LOOP: for (int i = 0; i <= sheetLastRowNumber; i++) { Row row = sheet.getRow(i); //if entire row is blank if ( row == null ) { //by default, include empty row if ( ! input.isExcludeEmptyRows() ) { logger.info("Adding PafExcelRow"); pafRowList.add(new PafExcelRow()); } continue; } int endColumnIndex = input.getColumnLimit(); //Add pace row items to pace row for (int t = startColumnIndex; t < endColumnIndex; t++) { Cell cell = row.getCell(t); //if cell is null, have row create blank cell if ( cell == null ) { logger.debug("Null Blank: " + i + ", " + t); //since cell is null, have row create cell cell = row.createCell(t, Cell.CELL_TYPE_BLANK); } PafExcelValueObject pafExcelValueObject = PafExcelValueObject.createFromCell(wb, cell); //if 1st column item if ( t == startColumnIndex ) { //if user flagged end of sheet data with a string and string matches here, stop reading data if ( pafExcelValueObject.isString() && input.getEndOfSheetIdnt() != null && pafExcelValueObject.getString().equalsIgnoreCase(input.getEndOfSheetIdnt())) { break OUTTER_LOOP; } //if not multi data row or it is but 1st item isn't a blank, create a new row if ( ! input.isMultiDataRow() || (input.isMultiDataRow() && ! pafExcelValueObject.isBlank()) ) { pafRow = new PafExcelRow(); } } pafRow.addRowItem(t, pafExcelValueObject); } //if the list already contains the row, remove. if (pafRowList.contains(pafRow) && pafRowList.indexOf(pafRow) == (pafRowList.size() - 1)) { pafRowList.remove(pafRow); } pafRowList.add(pafRow); //header row if ( isHeaderRow(input, pafRow) ) { //if exclude header, then remove from list of pace rows if ( input.isExcludeHeaderRows() ) { pafRowList.remove(pafRow); sheetLastRowNumber++; //else set the header attribute } else { pafRow.setHeader(true); } //blank row } else if ( isBlankRow(input, pafRow)) { if ( input.isExcludeEmptyRows() ) { pafRowList.remove(pafRow); sheetLastRowNumber++; } else { pafRow.setBlank(true); } //data row } else { //exclude data rows? if yes, remove if ( input.isExcludeDataRows()) { pafRowList.remove(pafRow); } } } } } return pafRowList; } private static void validateReadInput(PafExcelInput input) throws PafException { if ( input == null ) { String error = "Paf Excel Input cannot be null"; logger.error(error); throw new NullPointerException(error); } else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) { String error = "Paf excel input has not been configured property."; logger.error(error); throw new NullPointerException(error); } Workbook wb = null; if ( input.getWorkbook() != null ) { wb = input.getWorkbook(); } else { wb = readWorkbook(input.getFullWorkbookName()); } if ( wb == null ) { String error = "Workbook " + input.getFullWorkbookName() + " could not be read."; logger.error(error); throw new PafException(error, PafErrSeverity.Error); } else { Sheet sheet = wb.getSheet(input.getSheetId()); if ( sheet == null && input.isSheetRequired() ) { String error = "Sheet " + input.getSheetId() + " does not exist."; logger.error(error); throw new PafException(error, PafErrSeverity.Error); } } } public static List<String> getWorkbookSheetNames(Workbook workbook) throws PafException { List<String> sheetNameList = new ArrayList<String>(); if ( workbook != null ) { for (int i = 0; i < workbook.getNumberOfSheets(); i++) { sheetNameList.add(workbook.getSheetName(i)); } } if ( logger.isDebugEnabled() ) { logger.debug("Sheets: " + sheetNameList); } return sheetNameList; } public static List<String> getWorkbookSheetNames(String workbookLocation) throws PafException { Workbook wb = readWorkbook(workbookLocation); return getWorkbookSheetNames(wb); } private static boolean isBlankRow(PafExcelInput input, PafExcelRow pafRow) { if ( pafRow != null ) { for (Integer index : pafRow.getPafExcelValueObjectListMap().keySet()) { for (PafExcelValueObject valueObject : pafRow.getPafExcelValueObjectListMap().get(index) ) { if ( ! valueObject.isBlank() ) { return false; } } } } return true; } protected static boolean isHeaderRow(PafExcelInput input, PafExcelRow pafRow) { boolean isHeader = false; logger.debug("Checking if row is header row."); if ( input != null && pafRow != null ) { int startIndex = 0; if ( input.getStartDataReadColumnIndex() != null && input.getStartDataReadColumnIndex() > 0 ) { startIndex = input.getStartDataReadColumnIndex(); } int endIndex = input.getColumnLimit(); //continue if start index is less than end index if ( startIndex < endIndex ) { List<Integer> rowColumnIndexList = pafRow.getRowItemOrderedIndexes(); //loop through header list and see if the row matches any of the header list OUTTER_LOOP: for (String headerKey : input.getHeaderListMap().keySet()) { List<String> headerList = input.getHeaderListMap().get(headerKey); //see if header row or not if ( headerList != null && headerList.size() > 0 ) { try { headerList = headerList.subList(startIndex, endIndex); } catch (IndexOutOfBoundsException e) { continue; } List<Integer> updateRowColumnIndexList = new ArrayList<Integer>(); try { updateRowColumnIndexList.addAll(rowColumnIndexList.subList(0, endIndex-startIndex)); } catch (IndexOutOfBoundsException e) { continue; } //if header list size does not equal the number of row item indexes, continue to next header; if ( updateRowColumnIndexList.size() != headerList.size()) { continue; } isHeader = true; //loop through all pace row items for (Integer rowItemIndex : updateRowColumnIndexList ) { List<PafExcelValueObject> paceRowItemList = pafRow.getRowItem(rowItemIndex); logger.debug("\tProcessing Row Item List (element 0): " + paceRowItemList.get(0).getValueAsString()); int headerIndex = updateRowColumnIndexList.indexOf(rowItemIndex); //items to compare String headerItem = headerList.get(headerIndex); String paceRowItem = paceRowItemList.get(0).getValueAsString(); //if pace row item is a header ignore field, set as blank if ( headerItem.equals(ExcelPaceProjectConstants.HEADER_IGNORE_IDENT)) { paceRowItem = ExcelPaceProjectConstants.HEADER_IGNORE_IDENT; } //if string returns something and the header list does not match if ( paceRowItemList.size() > 1 || (paceRowItemList.size() == 1 && ! headerItem.equalsIgnoreCase(paceRowItem))) { isHeader = false; continue OUTTER_LOOP; } } //if header, break look and don't check next header if ( isHeader ) { pafRow.setHeaderIdent(headerKey); break OUTTER_LOOP; } } } } } logger.debug("Row is header: " + isHeader); return isHeader; } public static void writeExcelSheet(PafExcelInput input, List<PafExcelRow> paceRowList) throws PafException { if ( input == null ) { throw new IllegalArgumentException("Pace Excel Input cannot be null"); } else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) { throw new IllegalArgumentException("A Full workbook name and a workbook haven't not been provided. One is required."); } Workbook wb = null; if ( input.getWorkbook() != null ) { wb = input.getWorkbook(); } else { wb = readWorkbook(input.getFullWorkbookName()); } if ( wb == null ) { throw new PafException("Couldn't get a reference to the workbook " + input.getFullWorkbookName() , PafErrSeverity.Error); } Sheet sheet = wb.getSheet(input.getSheetId()); if ( sheet == null ) { sheet = wb.createSheet(input.getSheetId()); } else { sheet = clearSheetValues(sheet); } if ( paceRowList != null ) { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); int rowNdx = 0; int maxNumberOfColumns = 0; CellStyle boldCellStyle = null; boolean isFirstHeader = true; for (PafExcelRow paceRow : paceRowList ) { if ( paceRow != null ) { //if row is header and need to exclude, continue to next row if ( paceRow.isHeader() && input.isExcludeHeaderRows()) { continue; } if ( paceRow.numberOfColumns() > maxNumberOfColumns) { maxNumberOfColumns = paceRow.numberOfColumns(); } for (int i = 0; i < paceRow.numberOfCompressedRows(); i++ ) { Row row = sheet.createRow(rowNdx++); if ( isFirstHeader && paceRow.isHeader() ) { //freeze 1st header row sheet.createFreezePane(0, 1); isFirstHeader = false; } for ( Integer index : paceRow.getRowItemOrderedIndexes() ) { List<PafExcelValueObject> rowItemList = paceRow.getPafExcelValueObjectListMap().get(index); //Cell cell = row.createCell(rowItemNdx++);; Cell cell = row.createCell(index); if ( i < rowItemList.size()) { PafExcelValueObject rowItem = rowItemList.get(i); if ( rowItem == null ) { cell.setCellType(Cell.CELL_TYPE_BLANK); } else { //if header, bold item if ( paceRow.isHeader() || rowItem.isBoldItem() ) { if ( boldCellStyle == null ) { boldCellStyle = getBoldCellStyle(wb); //turn word wrap on boldCellStyle.setWrapText(true); } cell.setCellStyle(boldCellStyle); } switch ( rowItem.getType() ) { case Blank: cell.setCellType(Cell.CELL_TYPE_BLANK); break; case Boolean: if ( rowItem.getBoolean() != null ) { Boolean boolValue = rowItem.getBoolean(); if ( input.isExcludeDefaultValuesOnWrite()) { //if default, clear value if ( boolValue.equals(Boolean.FALSE)) { boolValue = null; } } //true or false if ( boolValue != null ) { cell.setCellType(Cell.CELL_TYPE_BOOLEAN); cell.setCellValue(boolValue); } } break; case Double: if ( rowItem.getDouble() != null ) { Double doubleVal = rowItem.getDouble(); if ( doubleVal != null && input.isExcludeDefaultValuesOnWrite()) { if ( doubleVal == 0 ) { doubleVal = null; } } if ( doubleVal != null ) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(doubleVal); } } break; case Integer: if ( rowItem.getInteger() != null ) { Integer intValue = rowItem.getInteger(); if ( intValue != null && input.isExcludeDefaultValuesOnWrite()) { if ( intValue == 0 ) { intValue = null; } } if ( intValue != null ) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(intValue); } } break; case Formula: cell.setCellType(Cell.CELL_TYPE_FORMULA); String formula = rowItem.getFormula(); String formulas[] = formula.split(" & \" \\| \" & "); if( formulas.length >= 1 ) { //there is only 1 formula formula = formulas[0]; String tokens[] = formula.split("!"); - String sheetName = tokens[0]; - if( ! sheetName.matches("[a-zA-Z0123456789]*") ) { - formula = "'" + sheetName + "'!" + tokens[1]; + if( tokens.length > 1 ) { + String sheetName = tokens[0]; + if( ! sheetName.matches("[a-zA-Z0123456789]*") ) { + formula = "'" + sheetName + "'!" + tokens[1]; + } } } if ( formulas.length > 1 ) { // more than 1 formula concatenated String tmp = ""; for( int j=1;j<formulas.length;j++ ) { tmp = formulas[j]; String tokens[] = formulas[j].split("!"); if( tokens.length > 1 ) { String sheetName = tokens[0]; if( ! sheetName.matches("[a-zA-Z0123456789]*") ) { tmp = "'" + sheetName + "'!" + tokens[1]; } formula = formula + " & \" | \" & " + tmp; } } } cell.setCellFormula(formula); evaluator.evaluateFormulaCell(cell); break; case String: cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(rowItem.getString()); break; } } } else { cell.setCellType(Cell.CELL_TYPE_BLANK); } } } } } //add end of sheet ident if ( input.getEndOfSheetIdnt() != null ) { int lastSheetRowNumber = sheet.getLastRowNum() + 1; Row lastRow = sheet.createRow(lastSheetRowNumber); Cell eosCell = lastRow.createCell(0, Cell.CELL_TYPE_STRING); eosCell.setCellValue(input.getEndOfSheetIdnt()); //set bold style eosCell.setCellStyle(getBoldCellStyle(wb)); } //auto size columns? if ( input.isAutoSizeColumns() ) { for (int i = 0; i <= maxNumberOfColumns; i++) { sheet.autoSizeColumn((short) i); } } } logger.info("\tSaving sheet: " + input.getSheetId() ); wb.setActiveSheet(wb.getSheetIndex(sheet.getSheetName())); //if write to filesystem, close workbook if ( input.isAutoWriteToFileSystem() ) { writeWorkbook(wb, input.getFullWorkbookName()); } } private static CellStyle getBoldCellStyle(Workbook workbook) { CellStyle cellStyle = null; if ( workbook != null ) { cellStyle = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(font); } return cellStyle; } private static Sheet clearSheetValues(Sheet sheet) { if ( sheet != null ) { Workbook wb = sheet.getWorkbook(); String sheetName = sheet.getSheetName(); int sheetNdx = wb.getSheetIndex(sheetName); wb.removeSheetAt(sheetNdx); sheet = wb.createSheet(sheetName); wb.setSheetOrder(sheetName, sheetNdx); } return sheet; } public static String createExcelReference(String sheetId, String address) { String excelReference = null; if ( sheetId != null && address != null ) { if ( sheetId.contains(" ") ) { sheetId = "'" + sheetId.trim() + "'"; } excelReference = sheetId + "!" + address; } return excelReference; } /** * * Replaces all blanks with null * * @param list list of paf excel value objects * @return a list of excel value objects will all blank's converted into null items in list */ public static List<PafExcelValueObject> convertBlanksToNullInList(List<PafExcelValueObject> list) { List<PafExcelValueObject> updatedList = new ArrayList<PafExcelValueObject>(); if ( list != null ) { for (PafExcelValueObject listValueObject : list ) { if ( listValueObject.isBlank() ) { updatedList.add(null); } else { updatedList.add(listValueObject); } } } return updatedList; } public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired) throws ExcelProjectDataErrorException { return getString(projectElementId, valueObject, isRequired, null); } public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject, List<String> validValueList) throws ExcelProjectDataErrorException { return getString(projectElementId, valueObject, false, validValueList); } public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired, List<String> validValueList) throws ExcelProjectDataErrorException { String str = null; //if null or blank if ( valueObject == null || valueObject.isBlank() ) { if ( isRequired ) { throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObject)); } } else if ( valueObject.isString() || valueObject.isFormula() || valueObject.isNumeric() ) { if ( validValueList == null ) { str = valueObject.getValueAsString(); } else if (validValueList != null && CollectionsUtil.containsIgnoreCase(validValueList, valueObject.getValueAsString())) { for (String validValue : validValueList ) { if ( valueObject.getValueAsString().equalsIgnoreCase(validValue)) { str = validValue; break; } } } else { throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject, validValueList)); } } else { throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject, validValueList)); } return str; } public static Integer getInteger(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException { return getInteger(projectElementId, valueObject, false); } public static Integer getInteger(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired) throws ExcelProjectDataErrorException { Integer intValue = null; //if not blank if ( valueObject != null && ! valueObject.isBlank() ) { //if numeric, get int value if ( valueObject.isNumeric() ) { intValue = valueObject.getInteger(); //throw invalid exception } else { throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidNumberProjectDataError(projectElementId, valueObject)); } //if blank } else { //if required and blank if ( isRequired ) { throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObject)); } } return intValue; } public static Boolean getBoolean(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException { return getBoolean(projectElementId, valueObject, false); } public static Boolean getBoolean(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean returnDefaultIfNull) throws ExcelProjectDataErrorException { Boolean boolValue = null; if ( ! valueObject.isBlank() ) { if ( valueObject.isBoolean() ) { boolValue = valueObject.getBoolean(); } else { throw new ExcelProjectDataErrorException(ProjectDataError.createBooleanProjectDataError(projectElementId, valueObject)); } } if ( returnDefaultIfNull && boolValue == null) { boolValue = Boolean.FALSE; } return boolValue; } public static String[] getStringAr(ProjectElementId projectElementId, List<PafExcelValueObject> valueObjectList) throws ExcelProjectDataErrorException { return getStringAr(projectElementId, valueObjectList, false); } public static String[] getStringAr(ProjectElementId projectElementId, List<PafExcelValueObject> valueObjectList, boolean isRequired ) throws ExcelProjectDataErrorException { String[] stringAr = null; List<String> stringList = new ArrayList<String>(); if ( valueObjectList != null ) { for (PafExcelValueObject excelValueObject : valueObjectList ) { stringList.add(getString(projectElementId, excelValueObject)); } } //if list has elements, convert into a string array if ( stringList.size() > 0 ) { stringAr = stringList.toArray(new String[0]); } //if required if ( isRequired ) { //if required and null or array converted to list with nulls pruned and size of 0, then throw project data error. if ( stringAr == null || CollectionsUtil.arrayToListPruneNulls(stringAr).size() == 0 ) { //throw new exception using 1st excel value object in list, should be blank throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObjectList.get(0))); } } return stringAr; } public static String[] getStringArFromDelimValueObject(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException { return getStringArFromDelimValueObject(projectElementId, valueObject, false); } public static String[] getStringArFromDelimValueObject(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired) throws ExcelProjectDataErrorException { String[] strAr = null; //if null or blank if ( valueObject == null || valueObject.isBlank() ) { //if required, throw error if null or blank if ( isRequired ) { throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObject)); } } else if ( valueObject.isString() || valueObject.isFormula() || valueObject.isNumeric() ) { List<String> listFromString = StringUtils.stringToList(PafExcelUtil.getString(projectElementId, valueObject), ExcelPaceProjectConstants.EXCEL_STRING_FIELD_DELIM); if ( listFromString.size() > 0 ) { strAr = listFromString.toArray(new String[0]); } } return strAr; } public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException { return getString(projectElementId, valueObject, false, null); } public static String getHexNumber(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException { if ( valueObject != null ) { if ( ! valueObject.isBlank() ) { String hexNumber = null; if ( valueObject.isNumeric()) { hexNumber = valueObject.getInteger().toString(); } else { hexNumber = valueObject.getValueAsString(); } //hex values are length of 6 if ( hexNumber.length() != 6 ) { throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject)); } else { Pattern p = Pattern.compile(ExcelPaceProjectConstants.HEX_FONT_PATTERN); Matcher m = p.matcher(hexNumber); if ( m.matches() ) { return hexNumber.toUpperCase(); } else { throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject)); } } } } return null; } public static Workbook readWorkbook(String workbookLocation) throws PafException { if ( workbookLocation == null ) { throw new IllegalArgumentException("Workbook location can not be null."); } Workbook wb = null; File fullFileWorkbookLocation = new File(workbookLocation); if ( fullFileWorkbookLocation.isFile() ) { InputStream inp = null; try { inp = new FileInputStream(workbookLocation); wb = WorkbookFactory.create(inp); } catch (FileNotFoundException e) { throw new PafException(e.getMessage(), PafErrSeverity.Error); } catch (InvalidFormatException e) { throw new PafException(e.getMessage(), PafErrSeverity.Error); } catch (IOException e) { throw new PafException(e.getMessage(), PafErrSeverity.Error); } } else { wb = new XSSFWorkbook(); } if ( wb == null ) { logger.error("Couldn't get a refernece to workbook " + workbookLocation); throw new PafException("Workbook reference " + workbookLocation + " is null.", PafErrSeverity.Error); } return wb; } public static void writeWorkbook(Workbook wb, String fullWorkbookName) throws PafException { // Write the output to a file FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(fullWorkbookName); wb.write(fileOut); } catch (FileNotFoundException e) { logger.error(e.getMessage()); throw new PafException(e.getMessage(), PafErrSeverity.Fatal); } catch (IOException e) { logger.error(e.getMessage()); throw new PafException(e.getMessage(), PafErrSeverity.Error); } finally { if ( fileOut != null ) { try { fileOut.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * * Creats a cell reference map, key is actual value, value is sheet/cell reference * * @param input * @return * @throws PafException */ public static Map<String, String> createCellReferenceMap ( PafExcelInput input ) throws PafException { validateReadInput(input); Map<String, String> cellReferenceMap = new HashMap<String, String>(); List<PafExcelRow> excelRowList = readExcelSheet(input); int startColumnIndex = 0; if ( input.getStartDataReadColumnIndex() != null ) { startColumnIndex = input.getStartDataReadColumnIndex(); } if ( excelRowList != null ) { for ( PafExcelRow excelRow : excelRowList ) { if ( excelRow.getRowItemOrderedIndexes().contains(startColumnIndex)) { List<PafExcelValueObject> valueObjectList = excelRow.getRowItem(startColumnIndex); if ( valueObjectList != null && valueObjectList.size() > 0 ) { //get 1st element PafExcelValueObject valueObject = valueObjectList.get(0); if ( valueObject.getCellAddress() != null ) { cellReferenceMap.put(valueObject.getString(), createExcelReference(input.getSheetId(), valueObject.getCellAddress(true))); } } } } } return cellReferenceMap; } public static PafExcelRow createHeaderRow(List<String> headerList) { PafExcelRow row = new PafExcelRow(); if ( headerList != null) { row.setHeader(true); int headerNdx = 0; for ( String header : headerList ) { row.addRowItem(headerNdx++, PafExcelValueObject.createFromString(header)); } } return row; } public static void orderSheets(String fullWorkbookName, List<ProjectElementId> sheetOrderList) throws PafException { try { Workbook wb = readWorkbook(fullWorkbookName); if ( wb != null ) { Map<ProjectElementId, Integer> sheetOrderMap = new HashMap<ProjectElementId, Integer>(); for ( ProjectElementId projectElementId : sheetOrderList ) { int sheetIndex = wb.getSheetIndex(projectElementId.toString()); logger.info(projectElementId.toString() + " : sheet index = " + sheetIndex); } } } catch (PafException e) { throw e; } } public static PafExcelValueObject getDelimValueObjectFromStringAr(String[] stringAr) { PafExcelValueObject valueObject = null; if ( stringAr != null && stringAr.length > 0 ) { List<PafExcelValueObject> list = new ArrayList<PafExcelValueObject>(); for ( String string : stringAr ) { list.add(PafExcelValueObject.createFromString(string)); } valueObject = PafExcelUtil.getDelimValueObjectFromList(list); } else { valueObject = PafExcelValueObject.createBlank(); } return valueObject; } /** * * Converts a list of PafExcelValueObjects into a single PafExcelValueObject that is delimited * by |'s between the values. If all items are string, then the PafExcelValueObject will be a * string with the |'s between the string values, but if formula, the entire list is parsed * into formula segements like this: =RuleSet_ContribPct!$A$2 & "|" & "StoreSales" * * @param list list of paf excel value objects * @return */ public static PafExcelValueObject getDelimValueObjectFromList(List<PafExcelValueObject> list) { PafExcelValueObject valueObject = null; if ( list != null && list.size() > 0 ) { boolean allStringValueObjects = true; for (PafExcelValueObject stringValueObject : list ) { if ( ! stringValueObject.isString() ) { allStringValueObjects = false; break; } } StringBuilder sb = new StringBuilder(); int strNdx = 0; for (PafExcelValueObject buildValueObject : list ) { if ( allStringValueObjects ) { sb.append(buildValueObject.getString()); } else { if ( buildValueObject.isFormula()) { sb.append(buildValueObject.getFormula()); } else { sb.append("\"" + buildValueObject.getString() + "\""); } } if ( ++strNdx != list.size() ) { if ( allStringValueObjects ) { sb.append(" " + ExcelPaceProjectConstants.EXCEL_STRING_FIELD_DELIM + " "); } else { sb.append(" & \" " + ExcelPaceProjectConstants.EXCEL_STRING_FIELD_DELIM + " \" & "); } } } if ( allStringValueObjects ) { valueObject = PafExcelValueObject.createFromString(sb.toString()); } else { valueObject = PafExcelValueObject.createFromFormula(sb.toString()); } } else { valueObject = PafExcelValueObject.createBlank(); } return valueObject; } /** * * Deletes a sheet from a workbook * * @param workbook workbook to delete sheet from * @param sheetName name of sheet to delete */ public static void deleteSheet(Workbook workbook, String sheetName) { if ( workbook != null && sheetName != null ) { int sheetIndex = workbook.getSheetIndex(sheetName); if ( sheetIndex >= 0 ) { logger.info("Deleting sheet: " + sheetName); workbook.removeSheetAt(sheetIndex); } } } }
true
true
public static void writeExcelSheet(PafExcelInput input, List<PafExcelRow> paceRowList) throws PafException { if ( input == null ) { throw new IllegalArgumentException("Pace Excel Input cannot be null"); } else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) { throw new IllegalArgumentException("A Full workbook name and a workbook haven't not been provided. One is required."); } Workbook wb = null; if ( input.getWorkbook() != null ) { wb = input.getWorkbook(); } else { wb = readWorkbook(input.getFullWorkbookName()); } if ( wb == null ) { throw new PafException("Couldn't get a reference to the workbook " + input.getFullWorkbookName() , PafErrSeverity.Error); } Sheet sheet = wb.getSheet(input.getSheetId()); if ( sheet == null ) { sheet = wb.createSheet(input.getSheetId()); } else { sheet = clearSheetValues(sheet); } if ( paceRowList != null ) { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); int rowNdx = 0; int maxNumberOfColumns = 0; CellStyle boldCellStyle = null; boolean isFirstHeader = true; for (PafExcelRow paceRow : paceRowList ) { if ( paceRow != null ) { //if row is header and need to exclude, continue to next row if ( paceRow.isHeader() && input.isExcludeHeaderRows()) { continue; } if ( paceRow.numberOfColumns() > maxNumberOfColumns) { maxNumberOfColumns = paceRow.numberOfColumns(); } for (int i = 0; i < paceRow.numberOfCompressedRows(); i++ ) { Row row = sheet.createRow(rowNdx++); if ( isFirstHeader && paceRow.isHeader() ) { //freeze 1st header row sheet.createFreezePane(0, 1); isFirstHeader = false; } for ( Integer index : paceRow.getRowItemOrderedIndexes() ) { List<PafExcelValueObject> rowItemList = paceRow.getPafExcelValueObjectListMap().get(index); //Cell cell = row.createCell(rowItemNdx++);; Cell cell = row.createCell(index); if ( i < rowItemList.size()) { PafExcelValueObject rowItem = rowItemList.get(i); if ( rowItem == null ) { cell.setCellType(Cell.CELL_TYPE_BLANK); } else { //if header, bold item if ( paceRow.isHeader() || rowItem.isBoldItem() ) { if ( boldCellStyle == null ) { boldCellStyle = getBoldCellStyle(wb); //turn word wrap on boldCellStyle.setWrapText(true); } cell.setCellStyle(boldCellStyle); } switch ( rowItem.getType() ) { case Blank: cell.setCellType(Cell.CELL_TYPE_BLANK); break; case Boolean: if ( rowItem.getBoolean() != null ) { Boolean boolValue = rowItem.getBoolean(); if ( input.isExcludeDefaultValuesOnWrite()) { //if default, clear value if ( boolValue.equals(Boolean.FALSE)) { boolValue = null; } } //true or false if ( boolValue != null ) { cell.setCellType(Cell.CELL_TYPE_BOOLEAN); cell.setCellValue(boolValue); } } break; case Double: if ( rowItem.getDouble() != null ) { Double doubleVal = rowItem.getDouble(); if ( doubleVal != null && input.isExcludeDefaultValuesOnWrite()) { if ( doubleVal == 0 ) { doubleVal = null; } } if ( doubleVal != null ) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(doubleVal); } } break; case Integer: if ( rowItem.getInteger() != null ) { Integer intValue = rowItem.getInteger(); if ( intValue != null && input.isExcludeDefaultValuesOnWrite()) { if ( intValue == 0 ) { intValue = null; } } if ( intValue != null ) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(intValue); } } break; case Formula: cell.setCellType(Cell.CELL_TYPE_FORMULA); String formula = rowItem.getFormula(); String formulas[] = formula.split(" & \" \\| \" & "); if( formulas.length >= 1 ) { //there is only 1 formula formula = formulas[0]; String tokens[] = formula.split("!"); String sheetName = tokens[0]; if( ! sheetName.matches("[a-zA-Z0123456789]*") ) { formula = "'" + sheetName + "'!" + tokens[1]; } } if ( formulas.length > 1 ) { // more than 1 formula concatenated String tmp = ""; for( int j=1;j<formulas.length;j++ ) { tmp = formulas[j]; String tokens[] = formulas[j].split("!"); if( tokens.length > 1 ) { String sheetName = tokens[0]; if( ! sheetName.matches("[a-zA-Z0123456789]*") ) { tmp = "'" + sheetName + "'!" + tokens[1]; } formula = formula + " & \" | \" & " + tmp; } } } cell.setCellFormula(formula); evaluator.evaluateFormulaCell(cell); break; case String: cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(rowItem.getString()); break; } } } else { cell.setCellType(Cell.CELL_TYPE_BLANK); } } } } } //add end of sheet ident if ( input.getEndOfSheetIdnt() != null ) { int lastSheetRowNumber = sheet.getLastRowNum() + 1; Row lastRow = sheet.createRow(lastSheetRowNumber); Cell eosCell = lastRow.createCell(0, Cell.CELL_TYPE_STRING); eosCell.setCellValue(input.getEndOfSheetIdnt()); //set bold style eosCell.setCellStyle(getBoldCellStyle(wb)); } //auto size columns? if ( input.isAutoSizeColumns() ) { for (int i = 0; i <= maxNumberOfColumns; i++) { sheet.autoSizeColumn((short) i); } } } logger.info("\tSaving sheet: " + input.getSheetId() ); wb.setActiveSheet(wb.getSheetIndex(sheet.getSheetName())); //if write to filesystem, close workbook if ( input.isAutoWriteToFileSystem() ) { writeWorkbook(wb, input.getFullWorkbookName()); } }
public static void writeExcelSheet(PafExcelInput input, List<PafExcelRow> paceRowList) throws PafException { if ( input == null ) { throw new IllegalArgumentException("Pace Excel Input cannot be null"); } else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) { throw new IllegalArgumentException("A Full workbook name and a workbook haven't not been provided. One is required."); } Workbook wb = null; if ( input.getWorkbook() != null ) { wb = input.getWorkbook(); } else { wb = readWorkbook(input.getFullWorkbookName()); } if ( wb == null ) { throw new PafException("Couldn't get a reference to the workbook " + input.getFullWorkbookName() , PafErrSeverity.Error); } Sheet sheet = wb.getSheet(input.getSheetId()); if ( sheet == null ) { sheet = wb.createSheet(input.getSheetId()); } else { sheet = clearSheetValues(sheet); } if ( paceRowList != null ) { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); int rowNdx = 0; int maxNumberOfColumns = 0; CellStyle boldCellStyle = null; boolean isFirstHeader = true; for (PafExcelRow paceRow : paceRowList ) { if ( paceRow != null ) { //if row is header and need to exclude, continue to next row if ( paceRow.isHeader() && input.isExcludeHeaderRows()) { continue; } if ( paceRow.numberOfColumns() > maxNumberOfColumns) { maxNumberOfColumns = paceRow.numberOfColumns(); } for (int i = 0; i < paceRow.numberOfCompressedRows(); i++ ) { Row row = sheet.createRow(rowNdx++); if ( isFirstHeader && paceRow.isHeader() ) { //freeze 1st header row sheet.createFreezePane(0, 1); isFirstHeader = false; } for ( Integer index : paceRow.getRowItemOrderedIndexes() ) { List<PafExcelValueObject> rowItemList = paceRow.getPafExcelValueObjectListMap().get(index); //Cell cell = row.createCell(rowItemNdx++);; Cell cell = row.createCell(index); if ( i < rowItemList.size()) { PafExcelValueObject rowItem = rowItemList.get(i); if ( rowItem == null ) { cell.setCellType(Cell.CELL_TYPE_BLANK); } else { //if header, bold item if ( paceRow.isHeader() || rowItem.isBoldItem() ) { if ( boldCellStyle == null ) { boldCellStyle = getBoldCellStyle(wb); //turn word wrap on boldCellStyle.setWrapText(true); } cell.setCellStyle(boldCellStyle); } switch ( rowItem.getType() ) { case Blank: cell.setCellType(Cell.CELL_TYPE_BLANK); break; case Boolean: if ( rowItem.getBoolean() != null ) { Boolean boolValue = rowItem.getBoolean(); if ( input.isExcludeDefaultValuesOnWrite()) { //if default, clear value if ( boolValue.equals(Boolean.FALSE)) { boolValue = null; } } //true or false if ( boolValue != null ) { cell.setCellType(Cell.CELL_TYPE_BOOLEAN); cell.setCellValue(boolValue); } } break; case Double: if ( rowItem.getDouble() != null ) { Double doubleVal = rowItem.getDouble(); if ( doubleVal != null && input.isExcludeDefaultValuesOnWrite()) { if ( doubleVal == 0 ) { doubleVal = null; } } if ( doubleVal != null ) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(doubleVal); } } break; case Integer: if ( rowItem.getInteger() != null ) { Integer intValue = rowItem.getInteger(); if ( intValue != null && input.isExcludeDefaultValuesOnWrite()) { if ( intValue == 0 ) { intValue = null; } } if ( intValue != null ) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(intValue); } } break; case Formula: cell.setCellType(Cell.CELL_TYPE_FORMULA); String formula = rowItem.getFormula(); String formulas[] = formula.split(" & \" \\| \" & "); if( formulas.length >= 1 ) { //there is only 1 formula formula = formulas[0]; String tokens[] = formula.split("!"); if( tokens.length > 1 ) { String sheetName = tokens[0]; if( ! sheetName.matches("[a-zA-Z0123456789]*") ) { formula = "'" + sheetName + "'!" + tokens[1]; } } } if ( formulas.length > 1 ) { // more than 1 formula concatenated String tmp = ""; for( int j=1;j<formulas.length;j++ ) { tmp = formulas[j]; String tokens[] = formulas[j].split("!"); if( tokens.length > 1 ) { String sheetName = tokens[0]; if( ! sheetName.matches("[a-zA-Z0123456789]*") ) { tmp = "'" + sheetName + "'!" + tokens[1]; } formula = formula + " & \" | \" & " + tmp; } } } cell.setCellFormula(formula); evaluator.evaluateFormulaCell(cell); break; case String: cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(rowItem.getString()); break; } } } else { cell.setCellType(Cell.CELL_TYPE_BLANK); } } } } } //add end of sheet ident if ( input.getEndOfSheetIdnt() != null ) { int lastSheetRowNumber = sheet.getLastRowNum() + 1; Row lastRow = sheet.createRow(lastSheetRowNumber); Cell eosCell = lastRow.createCell(0, Cell.CELL_TYPE_STRING); eosCell.setCellValue(input.getEndOfSheetIdnt()); //set bold style eosCell.setCellStyle(getBoldCellStyle(wb)); } //auto size columns? if ( input.isAutoSizeColumns() ) { for (int i = 0; i <= maxNumberOfColumns; i++) { sheet.autoSizeColumn((short) i); } } } logger.info("\tSaving sheet: " + input.getSheetId() ); wb.setActiveSheet(wb.getSheetIndex(sheet.getSheetName())); //if write to filesystem, close workbook if ( input.isAutoWriteToFileSystem() ) { writeWorkbook(wb, input.getFullWorkbookName()); } }
diff --git a/src/resources/registration/src/java/org/wyona/yanel/resources/registration/ValidationException.java b/src/resources/registration/src/java/org/wyona/yanel/resources/registration/ValidationException.java index c628ab7b8..30f61903f 100644 --- a/src/resources/registration/src/java/org/wyona/yanel/resources/registration/ValidationException.java +++ b/src/resources/registration/src/java/org/wyona/yanel/resources/registration/ValidationException.java @@ -1,49 +1,56 @@ /* * Copyright 2010 Wyona */ package org.wyona.yanel.resources.registration; /** * Exception containing validation errors */ public class ValidationException extends Exception { java.util.List<ValidationError> ves; /** * */ public ValidationException() { ves = new java.util.ArrayList<ValidationError>(); } /** * Add validation error * @param key Field name * @param value Field value * @param errorCode Type of error */ public void appendValidationError(String key, String value, String errorCode) { ves.add(new ValidationError(key, value, errorCode)); } /** * Get validation errors */ public ValidationError[] getValidationErrors() { return ves.toArray(new ValidationError[0]); } /** * @see java.lang.Throwable#getMessage() */ @Override public String getMessage() { if (ves != null && ves.size() > 0) { - ValidationError ve = (ValidationError) ves.get(0); - return "'" + ve.getKey() + "', '" + ve.getValue() + "', '" + ve.getErrorCode() + "'"; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < ves.size(); i++) { + ValidationError ve = (ValidationError) ves.get(i); + sb.append("(Validation error: '" + ve.getKey() + "', '" + ve.getValue() + "', '" + ve.getErrorCode() + "')"); + if (i < ves.size() - 1) { + sb.append(" "); + } + } + return sb.toString(); } else { return "No validation errors!"; } } }
true
true
public String getMessage() { if (ves != null && ves.size() > 0) { ValidationError ve = (ValidationError) ves.get(0); return "'" + ve.getKey() + "', '" + ve.getValue() + "', '" + ve.getErrorCode() + "'"; } else { return "No validation errors!"; } }
public String getMessage() { if (ves != null && ves.size() > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < ves.size(); i++) { ValidationError ve = (ValidationError) ves.get(i); sb.append("(Validation error: '" + ve.getKey() + "', '" + ve.getValue() + "', '" + ve.getErrorCode() + "')"); if (i < ves.size() - 1) { sb.append(" "); } } return sb.toString(); } else { return "No validation errors!"; } }
diff --git a/src/cf.java b/src/cf.java index d7581de..7f7ad74 100644 --- a/src/cf.java +++ b/src/cf.java @@ -1,108 +1,108 @@ public class cf extends ay { public int e = -1; public String f; public double g; public double h = 0.0D; public cf() { this.f = "Pig"; this.e = 20; } public boolean a() { return this.a.a(this.b + 0.5D, this.c + 0.5D, this.d + 0.5D, 16.0D) != null; } @Override public void b() { this.h = this.g; if (!a()) { return; } double d1 = this.b + this.a.l.nextFloat(); double d2 = this.c + this.a.l.nextFloat(); double d3 = this.d + this.a.l.nextFloat(); this.a.a("smoke", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.a.a("flame", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.g += 1000.0F / (this.e + 200.0F); while (this.g > 360.0D) { this.g -= 360.0D; this.h -= 360.0D; } if (this.e == -1) { d(); } if (this.e > 0) { this.e -= 1; return; } int i = 4; for (int j = 0; j < i; j++) { jz localjz = (jz) ho.a(this.f, this.a); if (localjz == null) { return; } int k = this.a.a(localjz.getClass(), dv.b(this.b, this.c, this.d, this.b + 1, this.c + 1, this.d + 1).b(8.0D, 4.0D, 8.0D)).size(); if (k >= 6) { d(); return; } if (localjz != null) { double d4 = this.b + (this.a.l.nextDouble() - this.a.l.nextDouble()) * 4.0D; double d5 = this.c + this.a.l.nextInt(3) - 1; double d6 = this.d + (this.a.l.nextDouble() - this.a.l.nextDouble()) * 4.0D; localjz.c(d4, d5, d6, this.a.l.nextFloat() * 360.0F, 0.0F); if (localjz.a()) { // hMod: allow entities to spawn - if ((Boolean) (etc.getLoader().callHook(PluginLoader.Hook.MOB_SPAWN, new Object[]{new LivingEntity(localjz)}))) { + if ((Boolean) (etc.getLoader().callHook(PluginLoader.Hook.MOB_SPAWN, new Object[]{new Mob(localjz)}))) { d(); return; } this.a.a(localjz); for (int m = 0; m < 20; m++) { d1 = this.b + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; d2 = this.c + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; d3 = this.d + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; this.a.a("smoke", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.a.a("flame", d1, d2, d3, 0.0D, 0.0D, 0.0D); } localjz.J(); d(); } } } super.b(); } private void d() { this.e = (200 + this.a.l.nextInt(600)); } @Override public void a(v paramv) { super.a(paramv); this.f = paramv.h("EntityId"); this.e = paramv.c("Delay"); } @Override public void b(v paramv) { super.b(paramv); paramv.a("EntityId", this.f); paramv.a("Delay", (short) this.e); } }
true
true
public void b() { this.h = this.g; if (!a()) { return; } double d1 = this.b + this.a.l.nextFloat(); double d2 = this.c + this.a.l.nextFloat(); double d3 = this.d + this.a.l.nextFloat(); this.a.a("smoke", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.a.a("flame", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.g += 1000.0F / (this.e + 200.0F); while (this.g > 360.0D) { this.g -= 360.0D; this.h -= 360.0D; } if (this.e == -1) { d(); } if (this.e > 0) { this.e -= 1; return; } int i = 4; for (int j = 0; j < i; j++) { jz localjz = (jz) ho.a(this.f, this.a); if (localjz == null) { return; } int k = this.a.a(localjz.getClass(), dv.b(this.b, this.c, this.d, this.b + 1, this.c + 1, this.d + 1).b(8.0D, 4.0D, 8.0D)).size(); if (k >= 6) { d(); return; } if (localjz != null) { double d4 = this.b + (this.a.l.nextDouble() - this.a.l.nextDouble()) * 4.0D; double d5 = this.c + this.a.l.nextInt(3) - 1; double d6 = this.d + (this.a.l.nextDouble() - this.a.l.nextDouble()) * 4.0D; localjz.c(d4, d5, d6, this.a.l.nextFloat() * 360.0F, 0.0F); if (localjz.a()) { // hMod: allow entities to spawn if ((Boolean) (etc.getLoader().callHook(PluginLoader.Hook.MOB_SPAWN, new Object[]{new LivingEntity(localjz)}))) { d(); return; } this.a.a(localjz); for (int m = 0; m < 20; m++) { d1 = this.b + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; d2 = this.c + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; d3 = this.d + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; this.a.a("smoke", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.a.a("flame", d1, d2, d3, 0.0D, 0.0D, 0.0D); } localjz.J(); d(); } } } super.b(); }
public void b() { this.h = this.g; if (!a()) { return; } double d1 = this.b + this.a.l.nextFloat(); double d2 = this.c + this.a.l.nextFloat(); double d3 = this.d + this.a.l.nextFloat(); this.a.a("smoke", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.a.a("flame", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.g += 1000.0F / (this.e + 200.0F); while (this.g > 360.0D) { this.g -= 360.0D; this.h -= 360.0D; } if (this.e == -1) { d(); } if (this.e > 0) { this.e -= 1; return; } int i = 4; for (int j = 0; j < i; j++) { jz localjz = (jz) ho.a(this.f, this.a); if (localjz == null) { return; } int k = this.a.a(localjz.getClass(), dv.b(this.b, this.c, this.d, this.b + 1, this.c + 1, this.d + 1).b(8.0D, 4.0D, 8.0D)).size(); if (k >= 6) { d(); return; } if (localjz != null) { double d4 = this.b + (this.a.l.nextDouble() - this.a.l.nextDouble()) * 4.0D; double d5 = this.c + this.a.l.nextInt(3) - 1; double d6 = this.d + (this.a.l.nextDouble() - this.a.l.nextDouble()) * 4.0D; localjz.c(d4, d5, d6, this.a.l.nextFloat() * 360.0F, 0.0F); if (localjz.a()) { // hMod: allow entities to spawn if ((Boolean) (etc.getLoader().callHook(PluginLoader.Hook.MOB_SPAWN, new Object[]{new Mob(localjz)}))) { d(); return; } this.a.a(localjz); for (int m = 0; m < 20; m++) { d1 = this.b + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; d2 = this.c + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; d3 = this.d + 0.5D + (this.a.l.nextFloat() - 0.5D) * 2.0D; this.a.a("smoke", d1, d2, d3, 0.0D, 0.0D, 0.0D); this.a.a("flame", d1, d2, d3, 0.0D, 0.0D, 0.0D); } localjz.J(); d(); } } } super.b(); }
diff --git a/src/ring/commands/mud/I3.java b/src/ring/commands/mud/I3.java index 44ea44c..0fa305e 100644 --- a/src/ring/commands/mud/I3.java +++ b/src/ring/commands/mud/I3.java @@ -1,93 +1,97 @@ package ring.commands.mud; import java.util.List; import com.aelfengard.i3.I3NotConnectedException; import ring.commands.Command; import ring.commands.CommandParameters; import ring.commands.CommandResult; import ring.commands.CommandSender; import ring.commands.CommandParameters.CommandType; import ring.intermud3.Intermud3Client; import ring.intermud3.Intermud3Daemon; import ring.players.PlayerCharacter; public class I3 implements Command { @Override public void execute(CommandSender sender, CommandParameters params) { params.init(CommandType.TEXT); CommandResult res = new CommandResult(); res.setFailText("This MUD is not connected to I3."); //Continue onwards. String op = params.getParameterAsText(0); PlayerCharacter pc = (PlayerCharacter)sender; + System.out.println("daemon: " + Intermud3Daemon.currentDaemon()); + System.out.println("player: " + pc.getPlayer()); Intermud3Client client = Intermud3Daemon.currentDaemon().getClientForPlayer(pc.getPlayer()); if (!client.isConnected()) { res.send(); return; } String result = ""; if (op.equalsIgnoreCase("muds")) { result = "List of MUDs:\n"; List<String> muds = client.getMuds(); for (String mud : muds) { result += mud + "\n"; } res.setSuccessful(true); res.setText(result); + res.send(); } else if (op.equalsIgnoreCase("channels")) { result = "List of Channels:\n"; List<String> channels = client.getChannels(); for (String channel : channels) { result += channel + "\n"; } res.setSuccessful(true); res.setText(result); + res.send(); } else if (op.equalsIgnoreCase("who")) { String mudName = params.getTextParameters(1); try { client.submitWhoRequest(mudName); res.setText("Who request for [B]" + mudName + "[R] submitted."); res.setSuccessful(true); } catch (I3NotConnectedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (op.equalsIgnoreCase("tell")) { String[] target = params.getParameterAsText(1).split("@"); String message = params.getTextParameters(2); System.out.println("tell mud: " + target[1]); System.out.println("tell user: " + target[0]); client.sendTell(target[1], target[0], message); res.setText("You tell [B]" + target[0] + "@" + target[1] + "[R]: " + message); res.setSuccessful(true); } } @Override public String getCommandName() { return "i3"; } @Override public void rollback() { } }
false
true
public void execute(CommandSender sender, CommandParameters params) { params.init(CommandType.TEXT); CommandResult res = new CommandResult(); res.setFailText("This MUD is not connected to I3."); //Continue onwards. String op = params.getParameterAsText(0); PlayerCharacter pc = (PlayerCharacter)sender; Intermud3Client client = Intermud3Daemon.currentDaemon().getClientForPlayer(pc.getPlayer()); if (!client.isConnected()) { res.send(); return; } String result = ""; if (op.equalsIgnoreCase("muds")) { result = "List of MUDs:\n"; List<String> muds = client.getMuds(); for (String mud : muds) { result += mud + "\n"; } res.setSuccessful(true); res.setText(result); } else if (op.equalsIgnoreCase("channels")) { result = "List of Channels:\n"; List<String> channels = client.getChannels(); for (String channel : channels) { result += channel + "\n"; } res.setSuccessful(true); res.setText(result); } else if (op.equalsIgnoreCase("who")) { String mudName = params.getTextParameters(1); try { client.submitWhoRequest(mudName); res.setText("Who request for [B]" + mudName + "[R] submitted."); res.setSuccessful(true); } catch (I3NotConnectedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (op.equalsIgnoreCase("tell")) { String[] target = params.getParameterAsText(1).split("@"); String message = params.getTextParameters(2); System.out.println("tell mud: " + target[1]); System.out.println("tell user: " + target[0]); client.sendTell(target[1], target[0], message); res.setText("You tell [B]" + target[0] + "@" + target[1] + "[R]: " + message); res.setSuccessful(true); } }
public void execute(CommandSender sender, CommandParameters params) { params.init(CommandType.TEXT); CommandResult res = new CommandResult(); res.setFailText("This MUD is not connected to I3."); //Continue onwards. String op = params.getParameterAsText(0); PlayerCharacter pc = (PlayerCharacter)sender; System.out.println("daemon: " + Intermud3Daemon.currentDaemon()); System.out.println("player: " + pc.getPlayer()); Intermud3Client client = Intermud3Daemon.currentDaemon().getClientForPlayer(pc.getPlayer()); if (!client.isConnected()) { res.send(); return; } String result = ""; if (op.equalsIgnoreCase("muds")) { result = "List of MUDs:\n"; List<String> muds = client.getMuds(); for (String mud : muds) { result += mud + "\n"; } res.setSuccessful(true); res.setText(result); res.send(); } else if (op.equalsIgnoreCase("channels")) { result = "List of Channels:\n"; List<String> channels = client.getChannels(); for (String channel : channels) { result += channel + "\n"; } res.setSuccessful(true); res.setText(result); res.send(); } else if (op.equalsIgnoreCase("who")) { String mudName = params.getTextParameters(1); try { client.submitWhoRequest(mudName); res.setText("Who request for [B]" + mudName + "[R] submitted."); res.setSuccessful(true); } catch (I3NotConnectedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (op.equalsIgnoreCase("tell")) { String[] target = params.getParameterAsText(1).split("@"); String message = params.getTextParameters(2); System.out.println("tell mud: " + target[1]); System.out.println("tell user: " + target[0]); client.sendTell(target[1], target[0], message); res.setText("You tell [B]" + target[0] + "@" + target[1] + "[R]: " + message); res.setSuccessful(true); } }
diff --git a/client/TileEntityShelfRenderer.java b/client/TileEntityShelfRenderer.java index 45ef882..19a5c25 100644 --- a/client/TileEntityShelfRenderer.java +++ b/client/TileEntityShelfRenderer.java @@ -1,233 +1,233 @@ package net.minecraft.src; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.lwjgl.opengl.GL11; import net.minecraft.src.forge.*; public class TileEntityShelfRenderer extends TileEntitySpecialRenderer { private RenderBlocks blockrender; private static Method render; public TileEntityShelfRenderer() { blockrender = new RenderBlocks(); } public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float partialTick) { a((TileEntityShelf)tileentity, x, y, z, partialTick); } public void a(TileEntityShelf tileentityshelf, double x, double y, double z, float partialTick) { float f1 = 0.0F; if (mod_Shelf.RotateItems) { f1 = tileentityshelf.worldObj.getWorldTime() % 360L; } GL11.glPushMatrix(); GL11.glTranslatef((float)x + 0.5F, (float)y + 0.8F, (float)z + 0.5F); int i = tileentityshelf.getBlockMetadata() & 3; switch (i) { case 0: GL11.glRotatef(270F, 0.0F, 1.0F, 0.0F); break; case 1: GL11.glRotatef(90F, 0.0F, 1.0F, 0.0F); break; case 2: GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F); break; case 3: GL11.glRotatef(0.0F, 0.0F, 1.0F, 0.0F); break; } GL11.glEnable(32826 /*GL_RESCALE_NORMAL_EXT*/); for (int j = 0; j < tileentityshelf.getSizeInventory(); j++) { if (j == 0) { GL11.glTranslatef(-0.3333333F, 0.0F, -0.3333333F); } else if (j % 3 != 0) { GL11.glTranslatef(0.3333333F, 0.0F, 0.0F); } else { GL11.glTranslatef(-0.6666667F, -0.3333333F, 0.3333333F); } ItemStack itemstack = tileentityshelf.getStackInSlot(j); System.out.println("item "+j+" is "+itemstack); if (itemstack != null && Item.itemsList[itemstack.itemID] != null) { - if (itemstack.itemID < 256 && RenderBlocks.renderItemIn3d(Block.blocksList[itemstack.itemID].getRenderType())) // TODO: stop hardcoding 256 + if (itemstack.itemID < Block.blocksList.length && RenderBlocks.renderItemIn3d(Block.blocksList[itemstack.itemID].getRenderType())) { Block block = Block.blocksList[itemstack.itemID]; if (block instanceof ITextureProvider) { // Forge infinite sprite sheets // see http://minecraftforge.net/wiki/How_to_use_infinite_terrain_and_sprite_indexes bindTextureByName(((ITextureProvider)block).getTextureFile()); } else { bindTextureByName("/terrain.png"); } float f2 = 0.25F; int i1 = block.getRenderType(); if (i1 == 1 || i1 == 19 || i1 == 12 || i1 == 2) { f2 = 0.5F; } GL11.glPushMatrix(); if (mod_Shelf.RotateItems) { GL11.glRotatef(f1, 0.0F, 1.0F, 0.0F); } GL11.glScalef(f2, f2, f2); GL11.glTranslatef(0.0F, 0.35F, 0.0F); float f3 = 1.0F; blockrender.renderBlockAsItem(Block.blocksList[itemstack.itemID], itemstack.getItemDamage(), f3); GL11.glPopMatrix(); } else { GL11.glPushMatrix(); try { GL11.glScalef(0.3333333F, 0.3333333F, 0.3333333F); if (mod_Shelf.RotateItems) { GL11.glRotatef(f1, 0.0F, 1.0F, 0.0F); } if (mod_Shelf.Render3DItems) { GL11.glTranslatef(-0.5F, 0.0F, 0.0F); } Item item = Item.itemsList[itemstack.itemID]; if (itemstack.getItem().func_46058_c()) { if (item instanceof ITextureProvider) { bindTextureByName(((ITextureProvider)item).getTextureFile()); } else { bindTextureByName("/gui/items.png"); } for (int k = 0; k <= 1; k++) { int j1 = itemstack.getItem().func_46057_a(itemstack.getItemDamage(), k); int color = itemstack.getItem().getColorFromDamage(itemstack.getItemDamage(), k); float red = (float)(color >> 16 & 0xff) / 255F; float green = (float)(color >> 8 & 0xff) / 255F; float blue = (float)(color & 0xff) / 255F; GL11.glColor4f(red, green, blue, 1.0F); drawItem(j1); } } else { int l = itemstack.getIconIndex(); if (item instanceof ITextureProvider) { bindTextureByName(((ITextureProvider)item).getTextureFile()); } else { - if (itemstack.itemID < 256) // TODO: stop hardcoding 256 + if (itemstack.itemID < Block.blocksList.length) { bindTextureByName("/terrain.png"); } else { bindTextureByName("/gui/items.png"); } } int color = Item.itemsList[itemstack.itemID].getColorFromDamage(itemstack.getItemDamage(), 0); float red = (float)(color >> 16 & 0xff) / 255F; float green = (float)(color >> 8 & 0xff) / 255F; float blue = (float)(color & 0xff) / 255F; GL11.glColor4f(red, green, blue, 1.0F); drawItem(l); } } catch (Throwable throwable) { throw new RuntimeException(throwable); } GL11.glPopMatrix(); } } } GL11.glDisable(32826 /*GL_RESCALE_NORMAL_EXT*/); GL11.glPopMatrix(); } private void drawItem(int tileIndex) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Tessellator tessellator = Tessellator.instance; float f = (float)((tileIndex % 16) * 16 + 0) / 256F; float f1 = (float)((tileIndex % 16) * 16 + 16) / 256F; float f2 = (float)((tileIndex / 16) * 16 + 0) / 256F; float f3 = (float)((tileIndex / 16) * 16 + 16) / 256F; float f4 = 1.0F; float f5 = 0.5F; float f6 = 0.25F; if (mod_Shelf.Render3DItems) { render.invoke(RenderManager.instance.itemRenderer, new Object[] { tessellator, Float.valueOf(f1), Float.valueOf(f2), Float.valueOf(f), Float.valueOf(f3) }); } else { tessellator.startDrawingQuads(); tessellator.setNormal(0.0F, 1.0F, 0.0F); tessellator.addVertexWithUV(0.0F - f5, 0.0F - f6, 0.0D, f, f3); tessellator.addVertexWithUV(f4 - f5, 0.0F - f6, 0.0D, f1, f3); tessellator.addVertexWithUV(f4 - f5, 1.0F - f6, 0.0D, f1, f2); tessellator.addVertexWithUV(0.0F - f5, 1.0F - f6, 0.0D, f, f2); tessellator.addVertexWithUV(0.0F - f5, 1.0F - f6, 0.0D, f, f2); tessellator.addVertexWithUV(f4 - f5, 1.0F - f6, 0.0D, f1, f2); tessellator.addVertexWithUV(f4 - f5, 0.0F - f6, 0.0D, f1, f3); tessellator.addVertexWithUV(0.0F - f5, 0.0F - f6, 0.0D, f, f3); tessellator.draw(); } } static { render = null; if (mod_Shelf.Render3DItems) { try { render = (net.minecraft.src.ItemRenderer.class).getDeclaredMethod("a", new Class[] { net.minecraft.src.Tessellator.class, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE }); render.setAccessible(true); } catch (Throwable throwable) { throwable.printStackTrace(); } } } }
false
true
public void a(TileEntityShelf tileentityshelf, double x, double y, double z, float partialTick) { float f1 = 0.0F; if (mod_Shelf.RotateItems) { f1 = tileentityshelf.worldObj.getWorldTime() % 360L; } GL11.glPushMatrix(); GL11.glTranslatef((float)x + 0.5F, (float)y + 0.8F, (float)z + 0.5F); int i = tileentityshelf.getBlockMetadata() & 3; switch (i) { case 0: GL11.glRotatef(270F, 0.0F, 1.0F, 0.0F); break; case 1: GL11.glRotatef(90F, 0.0F, 1.0F, 0.0F); break; case 2: GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F); break; case 3: GL11.glRotatef(0.0F, 0.0F, 1.0F, 0.0F); break; } GL11.glEnable(32826 /*GL_RESCALE_NORMAL_EXT*/); for (int j = 0; j < tileentityshelf.getSizeInventory(); j++) { if (j == 0) { GL11.glTranslatef(-0.3333333F, 0.0F, -0.3333333F); } else if (j % 3 != 0) { GL11.glTranslatef(0.3333333F, 0.0F, 0.0F); } else { GL11.glTranslatef(-0.6666667F, -0.3333333F, 0.3333333F); } ItemStack itemstack = tileentityshelf.getStackInSlot(j); System.out.println("item "+j+" is "+itemstack); if (itemstack != null && Item.itemsList[itemstack.itemID] != null) { if (itemstack.itemID < 256 && RenderBlocks.renderItemIn3d(Block.blocksList[itemstack.itemID].getRenderType())) // TODO: stop hardcoding 256 { Block block = Block.blocksList[itemstack.itemID]; if (block instanceof ITextureProvider) { // Forge infinite sprite sheets // see http://minecraftforge.net/wiki/How_to_use_infinite_terrain_and_sprite_indexes bindTextureByName(((ITextureProvider)block).getTextureFile()); } else { bindTextureByName("/terrain.png"); } float f2 = 0.25F; int i1 = block.getRenderType(); if (i1 == 1 || i1 == 19 || i1 == 12 || i1 == 2) { f2 = 0.5F; } GL11.glPushMatrix(); if (mod_Shelf.RotateItems) { GL11.glRotatef(f1, 0.0F, 1.0F, 0.0F); } GL11.glScalef(f2, f2, f2); GL11.glTranslatef(0.0F, 0.35F, 0.0F); float f3 = 1.0F; blockrender.renderBlockAsItem(Block.blocksList[itemstack.itemID], itemstack.getItemDamage(), f3); GL11.glPopMatrix(); } else { GL11.glPushMatrix(); try { GL11.glScalef(0.3333333F, 0.3333333F, 0.3333333F); if (mod_Shelf.RotateItems) { GL11.glRotatef(f1, 0.0F, 1.0F, 0.0F); } if (mod_Shelf.Render3DItems) { GL11.glTranslatef(-0.5F, 0.0F, 0.0F); } Item item = Item.itemsList[itemstack.itemID]; if (itemstack.getItem().func_46058_c()) { if (item instanceof ITextureProvider) { bindTextureByName(((ITextureProvider)item).getTextureFile()); } else { bindTextureByName("/gui/items.png"); } for (int k = 0; k <= 1; k++) { int j1 = itemstack.getItem().func_46057_a(itemstack.getItemDamage(), k); int color = itemstack.getItem().getColorFromDamage(itemstack.getItemDamage(), k); float red = (float)(color >> 16 & 0xff) / 255F; float green = (float)(color >> 8 & 0xff) / 255F; float blue = (float)(color & 0xff) / 255F; GL11.glColor4f(red, green, blue, 1.0F); drawItem(j1); } } else { int l = itemstack.getIconIndex(); if (item instanceof ITextureProvider) { bindTextureByName(((ITextureProvider)item).getTextureFile()); } else { if (itemstack.itemID < 256) // TODO: stop hardcoding 256 { bindTextureByName("/terrain.png"); } else { bindTextureByName("/gui/items.png"); } } int color = Item.itemsList[itemstack.itemID].getColorFromDamage(itemstack.getItemDamage(), 0); float red = (float)(color >> 16 & 0xff) / 255F; float green = (float)(color >> 8 & 0xff) / 255F; float blue = (float)(color & 0xff) / 255F; GL11.glColor4f(red, green, blue, 1.0F); drawItem(l); } } catch (Throwable throwable) { throw new RuntimeException(throwable); } GL11.glPopMatrix(); } } } GL11.glDisable(32826 /*GL_RESCALE_NORMAL_EXT*/); GL11.glPopMatrix(); }
public void a(TileEntityShelf tileentityshelf, double x, double y, double z, float partialTick) { float f1 = 0.0F; if (mod_Shelf.RotateItems) { f1 = tileentityshelf.worldObj.getWorldTime() % 360L; } GL11.glPushMatrix(); GL11.glTranslatef((float)x + 0.5F, (float)y + 0.8F, (float)z + 0.5F); int i = tileentityshelf.getBlockMetadata() & 3; switch (i) { case 0: GL11.glRotatef(270F, 0.0F, 1.0F, 0.0F); break; case 1: GL11.glRotatef(90F, 0.0F, 1.0F, 0.0F); break; case 2: GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F); break; case 3: GL11.glRotatef(0.0F, 0.0F, 1.0F, 0.0F); break; } GL11.glEnable(32826 /*GL_RESCALE_NORMAL_EXT*/); for (int j = 0; j < tileentityshelf.getSizeInventory(); j++) { if (j == 0) { GL11.glTranslatef(-0.3333333F, 0.0F, -0.3333333F); } else if (j % 3 != 0) { GL11.glTranslatef(0.3333333F, 0.0F, 0.0F); } else { GL11.glTranslatef(-0.6666667F, -0.3333333F, 0.3333333F); } ItemStack itemstack = tileentityshelf.getStackInSlot(j); System.out.println("item "+j+" is "+itemstack); if (itemstack != null && Item.itemsList[itemstack.itemID] != null) { if (itemstack.itemID < Block.blocksList.length && RenderBlocks.renderItemIn3d(Block.blocksList[itemstack.itemID].getRenderType())) { Block block = Block.blocksList[itemstack.itemID]; if (block instanceof ITextureProvider) { // Forge infinite sprite sheets // see http://minecraftforge.net/wiki/How_to_use_infinite_terrain_and_sprite_indexes bindTextureByName(((ITextureProvider)block).getTextureFile()); } else { bindTextureByName("/terrain.png"); } float f2 = 0.25F; int i1 = block.getRenderType(); if (i1 == 1 || i1 == 19 || i1 == 12 || i1 == 2) { f2 = 0.5F; } GL11.glPushMatrix(); if (mod_Shelf.RotateItems) { GL11.glRotatef(f1, 0.0F, 1.0F, 0.0F); } GL11.glScalef(f2, f2, f2); GL11.glTranslatef(0.0F, 0.35F, 0.0F); float f3 = 1.0F; blockrender.renderBlockAsItem(Block.blocksList[itemstack.itemID], itemstack.getItemDamage(), f3); GL11.glPopMatrix(); } else { GL11.glPushMatrix(); try { GL11.glScalef(0.3333333F, 0.3333333F, 0.3333333F); if (mod_Shelf.RotateItems) { GL11.glRotatef(f1, 0.0F, 1.0F, 0.0F); } if (mod_Shelf.Render3DItems) { GL11.glTranslatef(-0.5F, 0.0F, 0.0F); } Item item = Item.itemsList[itemstack.itemID]; if (itemstack.getItem().func_46058_c()) { if (item instanceof ITextureProvider) { bindTextureByName(((ITextureProvider)item).getTextureFile()); } else { bindTextureByName("/gui/items.png"); } for (int k = 0; k <= 1; k++) { int j1 = itemstack.getItem().func_46057_a(itemstack.getItemDamage(), k); int color = itemstack.getItem().getColorFromDamage(itemstack.getItemDamage(), k); float red = (float)(color >> 16 & 0xff) / 255F; float green = (float)(color >> 8 & 0xff) / 255F; float blue = (float)(color & 0xff) / 255F; GL11.glColor4f(red, green, blue, 1.0F); drawItem(j1); } } else { int l = itemstack.getIconIndex(); if (item instanceof ITextureProvider) { bindTextureByName(((ITextureProvider)item).getTextureFile()); } else { if (itemstack.itemID < Block.blocksList.length) { bindTextureByName("/terrain.png"); } else { bindTextureByName("/gui/items.png"); } } int color = Item.itemsList[itemstack.itemID].getColorFromDamage(itemstack.getItemDamage(), 0); float red = (float)(color >> 16 & 0xff) / 255F; float green = (float)(color >> 8 & 0xff) / 255F; float blue = (float)(color & 0xff) / 255F; GL11.glColor4f(red, green, blue, 1.0F); drawItem(l); } } catch (Throwable throwable) { throw new RuntimeException(throwable); } GL11.glPopMatrix(); } } } GL11.glDisable(32826 /*GL_RESCALE_NORMAL_EXT*/); GL11.glPopMatrix(); }
diff --git a/src/com/dynamobi/ws/util/DBDao.java b/src/com/dynamobi/ws/util/DBDao.java index e6b846a..e451bf3 100644 --- a/src/com/dynamobi/ws/util/DBDao.java +++ b/src/com/dynamobi/ws/util/DBDao.java @@ -1,83 +1,84 @@ /* Dynamo Web Services is a web service project for administering LucidDB Copyright (C) 2010 Dynamo Business Intelligence Corporation 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 approved by Dynamo Business Intelligence Corporation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.dynamobi.ws.util; import java.sql.SQLException; import javax.sql.DataSource; import java.lang.ClassNotFoundException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.io.InputStream; import java.io.IOException; // Base class import org.springframework.security.userdetails.jdbc.JdbcDaoImpl; // Factory class to construct our pooled datasource import com.mchange.v2.c3p0.DataSources; import com.dynamobi.ws.util.DBAccess; import com.dynamobi.ws.util.DB; public class DBDao extends JdbcDaoImpl { private DataSource ds_pooled = null; public DBDao() throws ClassNotFoundException, SQLException, IOException { super(); Properties pro = new Properties(); InputStream user_props = this.getClass().getResourceAsStream("/luciddb-jdbc.properties"); if (user_props != null) { pro.load(user_props); } else { pro.load(this.getClass().getResourceAsStream("/luciddb-jdbc-default.properties")); } Class.forName(pro.getProperty("jdbc.driver")); String username = pro.getProperty("jdbc.username"); String password = pro.getProperty("jdbc.password"); String url = pro.getProperty("jdbc.url"); DataSource ds_unpooled = DataSources.unpooledDataSource( url, username, password); Map<String,String> overrides = new HashMap<String,String>(); - overrides.put("minPoolSize", "3"); + //causes problems when DB server is not running + //overrides.put("minPoolSize", "3"); overrides.put("maxIdleTimeExcessConnections", "600"); overrides.put("breakAfterAcquireFailure", "true"); overrides.put("acquireRetryAttempts", "15"); ds_pooled = DataSources.pooledDataSource(ds_unpooled, overrides); setDataSource(ds_pooled); DBAccess.connDataSource = ds_pooled; DB.connDataSource = ds_pooled; } public void cleanup() throws SQLException { DataSources.destroy(ds_pooled); } }
true
true
public DBDao() throws ClassNotFoundException, SQLException, IOException { super(); Properties pro = new Properties(); InputStream user_props = this.getClass().getResourceAsStream("/luciddb-jdbc.properties"); if (user_props != null) { pro.load(user_props); } else { pro.load(this.getClass().getResourceAsStream("/luciddb-jdbc-default.properties")); } Class.forName(pro.getProperty("jdbc.driver")); String username = pro.getProperty("jdbc.username"); String password = pro.getProperty("jdbc.password"); String url = pro.getProperty("jdbc.url"); DataSource ds_unpooled = DataSources.unpooledDataSource( url, username, password); Map<String,String> overrides = new HashMap<String,String>(); overrides.put("minPoolSize", "3"); overrides.put("maxIdleTimeExcessConnections", "600"); overrides.put("breakAfterAcquireFailure", "true"); overrides.put("acquireRetryAttempts", "15"); ds_pooled = DataSources.pooledDataSource(ds_unpooled, overrides); setDataSource(ds_pooled); DBAccess.connDataSource = ds_pooled; DB.connDataSource = ds_pooled; }
public DBDao() throws ClassNotFoundException, SQLException, IOException { super(); Properties pro = new Properties(); InputStream user_props = this.getClass().getResourceAsStream("/luciddb-jdbc.properties"); if (user_props != null) { pro.load(user_props); } else { pro.load(this.getClass().getResourceAsStream("/luciddb-jdbc-default.properties")); } Class.forName(pro.getProperty("jdbc.driver")); String username = pro.getProperty("jdbc.username"); String password = pro.getProperty("jdbc.password"); String url = pro.getProperty("jdbc.url"); DataSource ds_unpooled = DataSources.unpooledDataSource( url, username, password); Map<String,String> overrides = new HashMap<String,String>(); //causes problems when DB server is not running //overrides.put("minPoolSize", "3"); overrides.put("maxIdleTimeExcessConnections", "600"); overrides.put("breakAfterAcquireFailure", "true"); overrides.put("acquireRetryAttempts", "15"); ds_pooled = DataSources.pooledDataSource(ds_unpooled, overrides); setDataSource(ds_pooled); DBAccess.connDataSource = ds_pooled; DB.connDataSource = ds_pooled; }
diff --git a/src/cz/cvut/localtrade/SearchedItemsActivity.java b/src/cz/cvut/localtrade/SearchedItemsActivity.java index 1139d16..b329eaf 100644 --- a/src/cz/cvut/localtrade/SearchedItemsActivity.java +++ b/src/cz/cvut/localtrade/SearchedItemsActivity.java @@ -1,166 +1,167 @@ package cz.cvut.localtrade; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.ActionBar; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; import cz.cvut.localtrade.dao.ItemsDAO; import cz.cvut.localtrade.helper.Filter; import cz.cvut.localtrade.helper.MapUtils; import cz.cvut.localtrade.model.Item; public class SearchedItemsActivity extends FragmentActivity { ListView listView; private ItemsDAO itemDao; private List<Item> items; private ArrayList<Integer> filteredIds; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.searched_items_activity_layout); super.onCreate(savedInstanceState); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getString(R.string.found_items)); // itemDao = new ItemsDAO(); // itemDao.open(); // items = itemDao.findAll(this, query)(); items = (ArrayList<Item>) getIntent().getExtras().getSerializable( "items"); listView = (ListView) findViewById(R.id.searched_items_listview); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(SearchedItemsActivity.this, SearchedItemDetailActivity.class); int itemId = filteredIds.get(position); Bundle bundle = new Bundle(); bundle.putInt("itemId", itemId); bundle.putSerializable("items", (ArrayList<Item>) items); intent.putExtras(bundle); startActivity(intent); } }); } @Override protected void onResume() { fillListView(); super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this, ShowMapActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } public void fillListView() { List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>(); filteredIds = new ArrayList<Integer>(); double minItemPrice = Double.MAX_VALUE; double maxItemPrice = Double.MIN_VALUE; double minDistance = Double.MAX_VALUE; double maxDistance = Double.MIN_VALUE; for (Item item : items) { if (item.getPrice() < minItemPrice) { minItemPrice = item.getPrice(); } if (item.getPrice() > maxItemPrice) { maxItemPrice = item.getPrice(); } float distance = MapUtils.distanceBetween(MapUtils.actualLocation, item.getLocation()); if (distance > maxDistance) { maxDistance = distance; } if (distance < minDistance) { minDistance = distance; } - if (Filter.currentFilter != null && Filter.currentFilter.filter(item)) { + if (Filter.currentFilter != null + && Filter.currentFilter.filter(item)) { continue; } HashMap<String, String> hm = new HashMap<String, String>(); hm.put("tit", item.getTitle()); - hm.put("sta", getString(R.string.state) + ": " + item.getState()); + hm.put("sta", item.getState().toString()); hm.put("dis", String.format("%.2f", distance) + " " + getString(R.string.distance_unit)); hm.put("pri", getString(R.string.price) + ": " + item.getPrice() + " " + getString(R.string.currency)); hm.put("image", Integer.toString(R.drawable.no_image)); aList.add(hm); filteredIds.add(item.getId()); } if (Filter.currentFilter == null) { Filter.currentFilter = new Filter(); Filter.currentFilter.priceLowBound = minItemPrice; Filter.currentFilter.priceHighBound = maxItemPrice; Filter.currentFilter.distanceHighBound = maxDistance; Filter.currentFilter.distanceLowBound = minDistance; } String[] from = { "tit", "sta", "dis", "pri", "image" }; int[] to = { R.id.item_title, R.id.item_state, R.id.item_distance, R.id.item_price, R.id.item_image }; SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.searched_items_list_item_layout, from, to); listView.setAdapter(adapter); } public void showPopupFilter(MenuItem item) { FilterDialogFragment f = new FilterDialogFragment(); f.setFilter(Filter.currentFilter); f.show(getFragmentManager(), "FilterDialogFragment"); } public void onFilterOk(Filter filter) { Filter.currentFilter = filter; fillListView(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.searched_items_activity_menu, menu); return true; } }
false
true
public void fillListView() { List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>(); filteredIds = new ArrayList<Integer>(); double minItemPrice = Double.MAX_VALUE; double maxItemPrice = Double.MIN_VALUE; double minDistance = Double.MAX_VALUE; double maxDistance = Double.MIN_VALUE; for (Item item : items) { if (item.getPrice() < minItemPrice) { minItemPrice = item.getPrice(); } if (item.getPrice() > maxItemPrice) { maxItemPrice = item.getPrice(); } float distance = MapUtils.distanceBetween(MapUtils.actualLocation, item.getLocation()); if (distance > maxDistance) { maxDistance = distance; } if (distance < minDistance) { minDistance = distance; } if (Filter.currentFilter != null && Filter.currentFilter.filter(item)) { continue; } HashMap<String, String> hm = new HashMap<String, String>(); hm.put("tit", item.getTitle()); hm.put("sta", getString(R.string.state) + ": " + item.getState()); hm.put("dis", String.format("%.2f", distance) + " " + getString(R.string.distance_unit)); hm.put("pri", getString(R.string.price) + ": " + item.getPrice() + " " + getString(R.string.currency)); hm.put("image", Integer.toString(R.drawable.no_image)); aList.add(hm); filteredIds.add(item.getId()); } if (Filter.currentFilter == null) { Filter.currentFilter = new Filter(); Filter.currentFilter.priceLowBound = minItemPrice; Filter.currentFilter.priceHighBound = maxItemPrice; Filter.currentFilter.distanceHighBound = maxDistance; Filter.currentFilter.distanceLowBound = minDistance; } String[] from = { "tit", "sta", "dis", "pri", "image" }; int[] to = { R.id.item_title, R.id.item_state, R.id.item_distance, R.id.item_price, R.id.item_image }; SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.searched_items_list_item_layout, from, to); listView.setAdapter(adapter); }
public void fillListView() { List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>(); filteredIds = new ArrayList<Integer>(); double minItemPrice = Double.MAX_VALUE; double maxItemPrice = Double.MIN_VALUE; double minDistance = Double.MAX_VALUE; double maxDistance = Double.MIN_VALUE; for (Item item : items) { if (item.getPrice() < minItemPrice) { minItemPrice = item.getPrice(); } if (item.getPrice() > maxItemPrice) { maxItemPrice = item.getPrice(); } float distance = MapUtils.distanceBetween(MapUtils.actualLocation, item.getLocation()); if (distance > maxDistance) { maxDistance = distance; } if (distance < minDistance) { minDistance = distance; } if (Filter.currentFilter != null && Filter.currentFilter.filter(item)) { continue; } HashMap<String, String> hm = new HashMap<String, String>(); hm.put("tit", item.getTitle()); hm.put("sta", item.getState().toString()); hm.put("dis", String.format("%.2f", distance) + " " + getString(R.string.distance_unit)); hm.put("pri", getString(R.string.price) + ": " + item.getPrice() + " " + getString(R.string.currency)); hm.put("image", Integer.toString(R.drawable.no_image)); aList.add(hm); filteredIds.add(item.getId()); } if (Filter.currentFilter == null) { Filter.currentFilter = new Filter(); Filter.currentFilter.priceLowBound = minItemPrice; Filter.currentFilter.priceHighBound = maxItemPrice; Filter.currentFilter.distanceHighBound = maxDistance; Filter.currentFilter.distanceLowBound = minDistance; } String[] from = { "tit", "sta", "dis", "pri", "image" }; int[] to = { R.id.item_title, R.id.item_state, R.id.item_distance, R.id.item_price, R.id.item_image }; SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.searched_items_list_item_layout, from, to); listView.setAdapter(adapter); }
diff --git a/modules/quercus/src/com/caucho/quercus/lib/db/PDOStatement.java b/modules/quercus/src/com/caucho/quercus/lib/db/PDOStatement.java index 6609fedb7..6de930d9b 100644 --- a/modules/quercus/src/com/caucho/quercus/lib/db/PDOStatement.java +++ b/modules/quercus/src/com/caucho/quercus/lib/db/PDOStatement.java @@ -1,1133 +1,1127 @@ /* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Sam */ package com.caucho.quercus.lib.db; import com.caucho.quercus.UnimplementedException; import com.caucho.quercus.annotation.Optional; import com.caucho.quercus.annotation.ReadOnly; import com.caucho.quercus.annotation.Reference; import com.caucho.quercus.env.ArrayValue; import com.caucho.quercus.env.ArrayValueImpl; import com.caucho.quercus.env.BooleanValue; import com.caucho.quercus.env.DefaultValue; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.EnvCleanup; import com.caucho.quercus.env.NullValue; import com.caucho.quercus.env.UnsetValue; import com.caucho.quercus.env.Value; import com.caucho.util.L10N; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * PDO object oriented API facade. */ public class PDOStatement extends JdbcPreparedStatementResource implements Iterable<Value>, EnvCleanup { private static final L10N L = new L10N(PDOStatement.class); private static final Value[] NULL_VALUES = new Value[0]; private final PDO _pdo; private final PDOError _error; // XXX: need to make public @Name("queryString") public final String queryString; private int _fetchMode = PDO.FETCH_BOTH; private Value[] _fetchModeArgs = NULL_VALUES; private HashMap<Value,BoundColumn> _boundColumnMap; private HashMap<String,Integer> _parameterNameMap; private HashMap<Integer,ColumnType> _paramTypes; private HashMap<Integer,Value> _paramValues; // protected so it's not callable by PHP code protected PDOStatement(Env env, PDO pdo, PDOError error, String query, boolean isPrepared, ArrayValue options, boolean isCatchException) throws SQLException { super(pdo.getConnection()); env.addCleanup(this); _pdo = pdo; _error = error; if (options != null && options.getSize() > 0) { env.notice(L.l("PDOStatement options unsupported")); } if (isPrepared) { query = parseQueryString(env, query); prepare(env, query); // php/1s41 - oracle can't handle this //_preparedStatement.setEscapeProcessing(false); } else { setQuery(query); try { setStatement(pdo.getConnection().createStatement(env)); execute(env, false); } catch (SQLException e) { if (isCatchException) { _error.error(env, e); } else { throw e; } } } this.queryString = query; } //side-effect, updates _parameterNameMap private String parseQueryString(Env env, String query) { int len = query.length(); StringBuilder sb = new StringBuilder(len); int parameterCount = 0; for (int i = 0; i < len; i++) { int ch = query.charAt(i); if (ch == '\'' || ch == '"') { sb.append((char) ch); while (true) { i++; int ch2 = query.charAt(i); if (ch2 < 0) { env.error(L.l("missing ending quote in query: {0}", query)); } sb.append((char) ch2); if (ch2 == ch) { break; } } } else if (ch == '?') { parameterCount++; sb.append((char) ch); } else if (ch == ':') { if (i + 1 < len && query.charAt(i + 1) == ':') { int j = i + 1; - while (j < len) { - if (query.charAt(j + 1) == ':') { - j++; - } - else { - break; - } + for (; j < len && query.charAt(j) == ':'; j++) { } sb.append(query, i, j + 1); i = j; continue; } int start = i + 1; while (true) { i++; int ch2 = -1; if (i < len) { ch2 = query.charAt(i); } // XXX: check what characters are allowed if (ch2 < 0 || ! Character.isJavaIdentifierPart(ch2)) { String name = query.substring(start, i); if (_parameterNameMap == null) { _parameterNameMap = new HashMap<String,Integer>(); } Integer index = Integer.valueOf(parameterCount++); _parameterNameMap.put(name, index); sb.append('?'); if (ch2 >= 0) { sb.append((char) ch2); } break; } } } else { sb.append((char) ch); } } return sb.toString(); } public boolean bindColumn(Env env, Value column, @Reference Value var, @Optional("-1") int type) { try { if (_boundColumnMap == null) { _boundColumnMap = new HashMap<Value,BoundColumn>(); } ColumnType columnType = null; if (type == -1) { } else if (type == PDO.PARAM_INT) { columnType = ColumnType.LONG; } else if (type == PDO.PARAM_BOOL) { columnType = ColumnType.BOOLEAN; } else if (type == PDO.PARAM_STR) { columnType = ColumnType.STRING; } else if (type == PDO.PARAM_NULL) { columnType = ColumnType.NULL; } else if (type == PDO.PARAM_LOB) { columnType = ColumnType.LOB; } else if (type == PDO.PARAM_STMT) { throw new UnimplementedException(L.l("PDO::PARAM_STMT")); } else { env.warning(L.l("unknown column type: {0}", type)); return false; } ResultSetMetaData metaData = getMetaData(); BoundColumn boundColumn = new BoundColumn(metaData, column, var, columnType); _boundColumnMap.put(column, boundColumn); return true; } catch (SQLException e) { _error.warning(env, e.getMessage()); return false; } } public boolean bindParam(Env env, @ReadOnly Value parameter, @Reference Value value, @Optional("PDO::PARAM_STR") int dataType, @Optional("-1") int length, @Optional Value driverOptions) { if (length != -1) { throw new UnimplementedException("length"); } if (! driverOptions.isDefault()) { throw new UnimplementedException("driverOptions"); } boolean isInputOutput = (dataType & PDO.PARAM_INPUT_OUTPUT) != 0; if (isInputOutput) { dataType = dataType & (~PDO.PARAM_INPUT_OUTPUT); if (true) throw new UnimplementedException("PARAM_INPUT_OUTPUT"); } Integer index = resolveParameter(parameter); if (index == null) { _error.warning(env, L.l("unknown parameter: '{0}'", parameter)); return false; } ColumnType type; switch (dataType) { case PDO.PARAM_BOOL: type = ColumnType.BOOLEAN; break; case PDO.PARAM_INT: type = ColumnType.LONG; break; case PDO.PARAM_LOB: type = ColumnType.LOB; break; case PDO.PARAM_NULL: type = ColumnType.NULL; break; case PDO.PARAM_STR: type = ColumnType.STRING; break; case PDO.PARAM_STMT: throw new UnimplementedException(L.l("PDO::PARAM_STMT")); default: _error.warning(env, L.l("unknown dataType '{0}'", dataType)); return false; } if (_paramTypes == null) { _paramTypes = new HashMap<Integer,ColumnType>(); _paramValues = new HashMap<Integer,Value>(); } _paramTypes.put(index, type); _paramValues.put(index, value); return true; } public boolean bindValue(Env env, @ReadOnly Value parameter, @ReadOnly Value value, @Optional("PDO::PARAM_STR") int dataType) { if (dataType == -1) { dataType = PDO.PARAM_STR; } value = value.toValue(); return bindParam(env, parameter, value, dataType, -1, DefaultValue.DEFAULT); } /** * Closes the current cursor. */ public boolean closeCursor(Env env) { return freeResult(); } /** * Returns the number of columns. */ public int columnCount(Env env) { return getColumnCount(env); } @Override public boolean close() { return super.close(); } /** * Implements the EnvCleanup interface. */ public void cleanup() { close(); } public String errorCode(Env env) { return _error.getErrorCode(); } public ArrayValue errorInfo() { return _error.getErrorInfo(); } @Override protected void setError(Env env, SQLException e) { e.printStackTrace(); _error.error(env, e); } /** * Execute the statement. * * @param inputParameters an array containing input values to correspond to * the bound parameters for the statement. * * @return true for success, false for failure */ public boolean execute(Env env, @Optional @ReadOnly Value inputParameters) { _error.clear(); ArrayValue parameters; if (inputParameters.isArray()) { parameters = inputParameters.toArrayValue(env); } else if (inputParameters.isDefault()) { parameters = null; } else { env.warning(L.l("'{0}' is an unexpected argument, expected array", inputParameters)); return false; } closeCursor(env); if (parameters != null) { int size = parameters.getSize(); ColumnType[] types = new ColumnType[size]; Value[] values = new Value[size]; for (Map.Entry<Value, Value> entry : parameters.entrySet()) { Value key = entry.getKey(); Value value = entry.getValue(); int index; if (key.isNumberConvertible()) { index = key.toInt(); } else { index = resolveParameter(key); } ColumnType type = ColumnType.getColumnType(value); if (type == null) { _error.warning(env, L.l("unknown type {0} ({1}) for parameter index {2}", value.getType(), value.getClass(), index)); return false; } types[index] = type; values[index] = value; } bindParams(env, types, values); } else if (_paramTypes != null) { int size = _paramTypes.size(); ColumnType[]types = new ColumnType[size]; Value[] values = new Value[size]; for (Map.Entry<Integer,ColumnType> entry : _paramTypes.entrySet()) { Integer index = entry.getKey(); ColumnType type = entry.getValue(); int i = index.intValue(); types[i] = type; values[i] = _paramValues.get(index); } bindParams(env, types, values); } try { return execute(env, false); } catch (SQLException e) { _error.error(env, e); return false; } } @Override protected boolean executeImpl(Env env) throws SQLException { _pdo.setLastExecutedStatement(this); return super.executeImpl(env); } @Override protected JdbcResultResource createResultSet(ResultSet rs) { return new JdbcResultResource(rs, _pdo.getColumnCase()); } /** * Fetch the next row. * * @param fetchMode the mode, 0 to use the value * set by {@link #setFetchMode}. * @return a value, BooleanValue.FALSE if there * are no more rows or an error occurs. */ public Value fetch(Env env, @Optional int fetchMode, @Optional("0") int cursorOrientation, @Optional("0") int cursorOffset) { if (cursorOrientation != 0) throw new UnimplementedException("fetch with cursorOrientation"); if (cursorOffset != 0) throw new UnimplementedException("fetch with cursorOffset"); int columnIndex = 0; return fetchImpl(env, fetchMode, columnIndex); } /** * * @param fetchMode * @param columnIndex 0-based column index when fetchMode is FETCH_BOTH */ public Value fetchAll(Env env, @Optional("0") int fetchMode, @Optional("-1") int columnIndex) { int effectiveFetchMode; if (fetchMode == 0) { effectiveFetchMode = _fetchMode; } else { effectiveFetchMode = fetchMode; } boolean isGroup = (fetchMode & PDO.FETCH_GROUP) != 0; boolean isUnique = (fetchMode & PDO.FETCH_UNIQUE) != 0; if (isGroup) throw new UnimplementedException("PDO.FETCH_GROUP"); if (isUnique) throw new UnimplementedException("PDO.FETCH_UNIQUE"); effectiveFetchMode = effectiveFetchMode & (~(PDO.FETCH_GROUP | PDO.FETCH_UNIQUE)); switch (effectiveFetchMode) { case PDO.FETCH_COLUMN: break; case PDO.FETCH_LAZY: _error.warning(env, L.l("PDO::FETCH_LAZY can't be used with PDOStatement::fetchAll()")); return BooleanValue.FALSE; default: if (columnIndex != -1) { _error.warning(env, L.l("unexpected arguments")); return BooleanValue.FALSE; } } ArrayValueImpl rows = new ArrayValueImpl(); while (true) { Value value = fetchImpl(env, effectiveFetchMode, columnIndex); if (value == BooleanValue.FALSE) { break; } rows.put(value); } return rows; } private Value fetchBoth(Env env, JdbcResultResource rs) { Value value = rs.fetchBoth(env, false); if (value == NullValue.NULL) { return BooleanValue.FALSE; } return value; } private Value fetchBound(Env env, JdbcResultResource rs) { try { if (! rs.next()) { return BooleanValue.FALSE; } return BooleanValue.TRUE; } catch (SQLException e) { _error.warning(env, e.getMessage()); return BooleanValue.FALSE; } } private void bindColumns(Env env, JdbcResultResource rs) throws SQLException { if (_boundColumnMap != null) { for (BoundColumn binding : _boundColumnMap.values()) { binding.bind(env, rs); } } } private Value fetchClass(Env env, JdbcResultResource rs) { String className; Value[] ctorArgs; if (_fetchModeArgs.length == 0 || _fetchModeArgs.length > 2) { return fetchBoth(env, rs); } className = _fetchModeArgs[0].toString(); if (_fetchModeArgs.length == 2) { if (_fetchModeArgs[1].isArray()) { // XXX: inefiicient, but args[1].getValueArray(_env) // doesn't handle references ArrayValue argsArray = (ArrayValue) _fetchModeArgs[1]; ctorArgs = new Value[argsArray.getSize()]; int i = 0; for (Value key : argsArray.keySet()) ctorArgs[i++] = argsArray.getVar(key); } else return fetchBoth(env, rs); } else { ctorArgs = NULL_VALUES; } return fetchObject(env, className, ctorArgs); } /** * @param column 0-based column number */ public Value fetchColumn(Env env, @Optional int column) { if (column < 0 && _fetchModeArgs.length > 0) { column = _fetchModeArgs[0].toInt(); } try { if (column < 0 || column >= getMetaData().getColumnCount()) { return BooleanValue.FALSE; } JdbcResultResource rs = getResultSet(); if (rs == null || ! rs.next()) { return BooleanValue.FALSE; } return rs.getColumnValue(env, column + 1); } catch (SQLException e) { _error.error(env, e); return BooleanValue.FALSE; } } private Value fetchFunc(Env env) { throw new UnimplementedException(); } /** * Fetch the next row. * * @param fetchMode the mode, 0 to use the value set by {@link #setFetchMode}. * @return a value, BooleanValue.FALSE if there are no more * rows or an error occurs. */ private Value fetchImpl(Env env, int fetchMode, int columnIndex) { JdbcResultResource rs = getResultSet(); if (rs == null) { return BooleanValue.FALSE; } if (fetchMode == 0) { fetchMode = _fetchMode; fetchMode = fetchMode & (~(PDO.FETCH_GROUP | PDO.FETCH_UNIQUE)); } else { if ((fetchMode & PDO.FETCH_GROUP) != 0) { _error.warning(env, L.l("FETCH_GROUP is not allowed")); return BooleanValue.FALSE; } else if ((fetchMode & PDO.FETCH_UNIQUE) != 0) { _error.warning(env, L.l("FETCH_UNIQUE is not allowed")); return BooleanValue.FALSE; } } boolean isClasstype = (fetchMode & PDO.FETCH_CLASSTYPE) != 0; boolean isSerialize = (fetchMode & PDO.FETCH_SERIALIZE) != 0; fetchMode = fetchMode & (~(PDO.FETCH_CLASSTYPE | PDO.FETCH_SERIALIZE)); Value value; switch (fetchMode) { case PDO.FETCH_ASSOC: value = fetchAssoc(env, rs); break; case PDO.FETCH_BOTH: value = fetchBoth(env, rs); break; case PDO.FETCH_BOUND: value = fetchBound(env, rs); break; case PDO.FETCH_COLUMN: value = fetchColumn(env, columnIndex); break; case PDO.FETCH_CLASS: value = fetchClass(env, rs); break; case PDO.FETCH_FUNC: value = fetchFunc(env); break; case PDO.FETCH_INTO: value = fetchInto(env, rs); break; case PDO.FETCH_LAZY: value = fetchLazy(env); break; case PDO.FETCH_NAMED: value = fetchNamed(env, rs); break; case PDO.FETCH_NUM: value = fetchNum(env, rs); break; case PDO.FETCH_OBJ: value = fetchObject(env, rs); break; default: _error.warning(env, L.l("invalid fetch mode {0}", fetchMode)); closeCursor(env); value = BooleanValue.FALSE; } try { if (value != BooleanValue.FALSE) { bindColumns(env, rs); } return value; } catch (SQLException e) { _error.error(env, e); return BooleanValue.FALSE; } } private Value fetchNum(Env env, JdbcResultResource rs) { Value value = rs.fetchNum(env); if (value == NullValue.NULL) { return BooleanValue.FALSE; } return value; } private Value fetchAssoc(Env env, JdbcResultResource rs) { Value value = rs.fetchAssoc(env); if (value == NullValue.NULL) { return BooleanValue.FALSE; } return value; } private Value fetchObject(Env env, JdbcResultResource rs) { Value value = rs.fetchObject(env, null, Value.NULL_ARGS); if (value == NullValue.NULL) { return BooleanValue.FALSE; } return value; } private Value fetchInto(Env env, JdbcResultResource rs) { if (_fetchModeArgs.length == 0) { return BooleanValue.FALSE; } if (! _fetchModeArgs[0].isObject()) { return BooleanValue.FALSE; } try { if (! rs.next()) { return BooleanValue.FALSE; } Value var = _fetchModeArgs[0]; int columnCount = getMetaData().getColumnCount(); for (int i = 1; i <= columnCount; i++) { String name = rs.getColumnLabel(i); Value value = getColumnValue(env, i); var.putField(env, name, value); } return var; } catch (SQLException e) { _error.error(env, e); return BooleanValue.FALSE; } } private Value fetchLazy(Env env) { // XXX: need to check why lazy is no different than object return fetchObject(env, null, NULL_VALUES); } private Value fetchNamed(Env env, JdbcResultResource rs) { try { ArrayValue array = new ArrayValueImpl(); int columnCount = getMetaData().getColumnCount(); for (int i = 1; i <= columnCount; i++) { Value name = env.createString(rs.getColumnLabel(i)); Value value = getColumnValue(env, i); Value existingValue = array.get(name); if (! (existingValue instanceof UnsetValue)) { if (! existingValue.isArray()) { ArrayValue arrayValue = new ArrayValueImpl(); arrayValue.put(existingValue); array.put(name, arrayValue); existingValue = arrayValue; } existingValue.put(value); } else array.put(name, value); } return array; } catch (SQLException e) { _error.error(env, e); return BooleanValue.FALSE; } } public Value fetchObject(Env env, @Optional String className, @Optional Value[] args) { JdbcResultResource rs = getResultSet(); if (rs == null) { return BooleanValue.FALSE; } Value value = rs.fetchObject(env, className, args); if (value == NullValue.NULL) { return BooleanValue.FALSE; } return value; } public Value getAttribute(Env env, int attribute) { _error.unsupportedAttribute(env, attribute); return BooleanValue.FALSE; } /** * @param column 0-based column index */ public Value getColumnMeta(Env env, int column) { throw new UnimplementedException(); } /** * @param column 1-based column index */ private Value getColumnValue(Env env, int column) throws SQLException { JdbcResultResource rs = getResultSet(); return rs.getColumnValue(env, column); } /** * Returns an iterator of the values. */ public Iterator<Value> iterator() { Value value = fetchAll(Env.getInstance(), 0, -1); if (value instanceof ArrayValue) return ((ArrayValue) value).values().iterator(); else { Set<Value> emptySet = Collections.emptySet(); return emptySet.iterator(); } } public boolean nextRowset() { throw new UnimplementedException(); } private Integer resolveParameter(Value parameter) { Integer index = null; if (parameter.isLong()) { // slight optimization for normal case index = Integer.valueOf(parameter.toInt() - 1); } else { String name = parameter.toString(); if (name.length() > 1 && name.charAt(0) == ':') { name = name.substring(1); } if (_parameterNameMap != null) { index = _parameterNameMap.get(name); } else { index = Integer.valueOf(parameter.toInt()); } } return index; } public int rowCount(Env env) { JdbcResultResource rs = getResultSet(); if (rs == null) { return 0; } return rs.getNumRows(); } public boolean setAttribute(Env env, int attribute, Value value) { return setAttribute(env, attribute, value, false); } public boolean setAttribute(Env env, int attribute, Value value, boolean isFromConstructor) { if (isFromConstructor) { switch (attribute) { case PDO.CURSOR_FWDONLY: case PDO.CURSOR_SCROLL: return setCursor(env, attribute); } } _error.unsupportedAttribute(env, attribute); return false; } private boolean setCursor(Env env, int attribute) { switch (attribute) { case PDO.CURSOR_FWDONLY: throw new UnimplementedException(); case PDO.CURSOR_SCROLL: throw new UnimplementedException(); default: _error.unsupportedAttribute(env, attribute); return false; } } /** * Sets the fetch mode, the default is {@link PDO.FETCH_BOTH}. */ public boolean setFetchMode(Env env, int fetchMode, Value[] args) { _fetchMode = PDO.FETCH_BOTH; _fetchModeArgs = NULL_VALUES; int fetchStyle = fetchMode; boolean isGroup = (fetchMode & PDO.FETCH_GROUP) != 0; boolean isUnique = (fetchMode & PDO.FETCH_UNIQUE) != 0; if (isGroup) throw new UnimplementedException("PDO.FETCH_GROUP"); if (isUnique) throw new UnimplementedException("PDO.FETCH_UNIQUE"); fetchStyle = fetchStyle & (~(PDO.FETCH_GROUP | PDO.FETCH_UNIQUE)); boolean isClasstype = (fetchMode & PDO.FETCH_CLASSTYPE) != 0; boolean isSerialize = (fetchMode & PDO.FETCH_SERIALIZE) != 0; fetchStyle = fetchStyle & (~(PDO.FETCH_CLASSTYPE | PDO.FETCH_SERIALIZE)); switch (fetchStyle) { case PDO.FETCH_ASSOC: case PDO.FETCH_BOTH: case PDO.FETCH_BOUND: case PDO.FETCH_LAZY: case PDO.FETCH_NAMED: case PDO.FETCH_NUM: case PDO.FETCH_OBJ: if (args.length > 0) { env.warning(L.l("this fetch mode does not accept any arguments")); return false; } break; case PDO.FETCH_CLASS: if (args.length < 1 || args.length > 2) return false; if (env.findClass(args[0].toString()) == null) return false; if (args.length == 2 && !(args[1].isNull() || args[1].isArray())) { env.warning(L.l("constructor args must be an array")); return false; } break; case PDO.FETCH_COLUMN: if (args.length != 1) return false; break; case PDO.FETCH_FUNC: _error.warning(env, L.l("PDO::FETCH_FUNC can only be used with PDOStatement::fetchAll()")); return false; case PDO.FETCH_INTO: if (args.length != 1 || !args[0].isObject()) return false; break; default: _error.warning(env, L.l("invalid fetch mode")); break; } _fetchModeArgs = args; _fetchMode = fetchMode; return true; } @Override protected boolean isFetchFieldIndexBeforeFieldName() { return false; } public String toString() { String query = getQuery(); return "PDOStatement[" + query.substring(0, 16) + "]"; } }
true
true
private String parseQueryString(Env env, String query) { int len = query.length(); StringBuilder sb = new StringBuilder(len); int parameterCount = 0; for (int i = 0; i < len; i++) { int ch = query.charAt(i); if (ch == '\'' || ch == '"') { sb.append((char) ch); while (true) { i++; int ch2 = query.charAt(i); if (ch2 < 0) { env.error(L.l("missing ending quote in query: {0}", query)); } sb.append((char) ch2); if (ch2 == ch) { break; } } } else if (ch == '?') { parameterCount++; sb.append((char) ch); } else if (ch == ':') { if (i + 1 < len && query.charAt(i + 1) == ':') { int j = i + 1; while (j < len) { if (query.charAt(j + 1) == ':') { j++; } else { break; } } sb.append(query, i, j + 1); i = j; continue; } int start = i + 1; while (true) { i++; int ch2 = -1; if (i < len) { ch2 = query.charAt(i); } // XXX: check what characters are allowed if (ch2 < 0 || ! Character.isJavaIdentifierPart(ch2)) { String name = query.substring(start, i); if (_parameterNameMap == null) { _parameterNameMap = new HashMap<String,Integer>(); } Integer index = Integer.valueOf(parameterCount++); _parameterNameMap.put(name, index); sb.append('?'); if (ch2 >= 0) { sb.append((char) ch2); } break; } } } else { sb.append((char) ch); } } return sb.toString(); }
private String parseQueryString(Env env, String query) { int len = query.length(); StringBuilder sb = new StringBuilder(len); int parameterCount = 0; for (int i = 0; i < len; i++) { int ch = query.charAt(i); if (ch == '\'' || ch == '"') { sb.append((char) ch); while (true) { i++; int ch2 = query.charAt(i); if (ch2 < 0) { env.error(L.l("missing ending quote in query: {0}", query)); } sb.append((char) ch2); if (ch2 == ch) { break; } } } else if (ch == '?') { parameterCount++; sb.append((char) ch); } else if (ch == ':') { if (i + 1 < len && query.charAt(i + 1) == ':') { int j = i + 1; for (; j < len && query.charAt(j) == ':'; j++) { } sb.append(query, i, j + 1); i = j; continue; } int start = i + 1; while (true) { i++; int ch2 = -1; if (i < len) { ch2 = query.charAt(i); } // XXX: check what characters are allowed if (ch2 < 0 || ! Character.isJavaIdentifierPart(ch2)) { String name = query.substring(start, i); if (_parameterNameMap == null) { _parameterNameMap = new HashMap<String,Integer>(); } Integer index = Integer.valueOf(parameterCount++); _parameterNameMap.put(name, index); sb.append('?'); if (ch2 >= 0) { sb.append((char) ch2); } break; } } } else { sb.append((char) ch); } } return sb.toString(); }
diff --git a/prototype/face/src/main/java/com/lisasoft/face/Prototype.java b/prototype/face/src/main/java/com/lisasoft/face/Prototype.java index af58695..6efa73c 100644 --- a/prototype/face/src/main/java/com/lisasoft/face/Prototype.java +++ b/prototype/face/src/main/java/com/lisasoft/face/Prototype.java @@ -1,554 +1,554 @@ package com.lisasoft.face; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToolBar; import org.geotools.coverage.GridSampleDimension; import org.geotools.coverage.grid.GridCoverage2D; import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader; import org.geotools.coverage.grid.io.AbstractGridFormat; import org.geotools.coverage.grid.io.GridFormatFinder; import org.geotools.data.DataStore; import org.geotools.data.DefaultRepository; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.FeatureCollections; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.map.FeatureLayer; import org.geotools.map.GridReaderLayer; import org.geotools.map.MapContent; import org.geotools.map.MapContext; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.renderer.lite.StreamingRenderer; import org.geotools.styling.ChannelSelection; import org.geotools.styling.ContrastEnhancement; import org.geotools.styling.RasterSymbolizer; import org.geotools.styling.SLD; import org.geotools.styling.SelectedChannelType; import org.geotools.styling.Style; import org.geotools.styling.StyleFactory; import org.geotools.swing.JMapPane; import org.geotools.swing.action.ZoomInAction; import org.geotools.swing.action.ZoomOutAction; import org.geotools.swing.table.FeatureCollectionTableModel; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.filter.FilterFactory2; import org.opengis.style.ContrastMethod; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; /** * This is a prototype application *just* showing how to integrate a MapComponent with an existing * application. * <p> * As such the details of this application are not all that interesting; they do serve to illustrate * how to: * <ol> * <li>set up a MapContent (this is used as the background for the MapComponent)</li> * <li>set up a MapComponent (this is actually a simple JPanel consisting of a JMapPane</li> * <li>set up a toolbar using some of the actions available for controlling MapComponent</li> * </ul> * In all cases this is straight forward application of the components provided by GeoTools. * <p> * Here is the interesting bit: * <ul> * <li>set up a MapComponentTable (actually a small JPanel consisting of a JTable working against * the MapComponent table model)</li> * <li>Custom table model; just backed by the Faces provided to MapComponentTable</li> * <li>Custom tool to "select" Faces in the MapComponent; this will update both update an internal * *filter* used to display selected faces; and update a list selection model published for use with * MapComponentTable.</li> * <li>Custom DataStore used to present the Faces provided to MapComponent to the GeoTools rendering * system. This is used by *two* layers. One layer to display the sites; and a second to display the * selection (These two lays are added to the MapContent).</li> * </ul>> * * Implementation Notes: * <ul> * <li>SH: is creating the layout of this form using Eclipse 3.7 window builder tools (this is not * really important or interesting; just FYI)</li> * </ul> * * @author Scott Henderson (LISASoft) * @author Jody Garnett (LISASoft) */ public class Prototype extends JFrame { /** serialVersionUID */ private static final long serialVersionUID = -1415741029620524123L; /** * Used to create GeoTools styles; based on OGC Style Layer Descriptor specification. */ private StyleFactory sf = CommonFactoryFinder.getStyleFactory(null); /** * Used to create GeoTools filters; to query data. */ private FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null); /** * Table used to list Face content. */ private JTable table; /** * Small toolbar configured with both JMapPane tools (for panning and zooming) and custom tools * to select Face content. */ private JToolBar toolBar; /** * Repository used to hold on to DataStores. */ private DefaultRepository repo; /** Used to hold on to rasters */ private Map<String, AbstractGridCoverage2DReader> raster; /** * This is the mapcontent used as a backdrop for mapComponent */ private MapContent map; private SimpleFeatureCollection faces; /** * Create a Prototype Frame; please call init() to configure. * <p> * How to use: * * <pre> * Prototype prototype = new Prototype(); * // any configuration here * init(); * show(); * </pre> * * Subclasses can override init() or set key methods inorder to control or experiment with how * this class functions. These methods are set up to show how to perform common tasks. */ private Prototype() { super("AGP Prototype"); repo = new DefaultRepository(); raster = new LinkedHashMap<String, AbstractGridCoverage2DReader>(); } /** * Prompts the user for a GeoTIFF file and a Shapefile and passes them to the displayLayers * method Usual protected init method called from the constructor(); subclasses can override key * methods in order to takepart in configuration. * <ul> * <li>loadData() - load data into a repository * <li>createMap() - create a MapContent * <li>loadSites() - load site information * <li>initUserInterface() - layout user interface components; this will create the MapComponent and * connect it to the required data model etc... * </ul> */ protected void init() throws Exception { loadData(); loadSites(); map = createMap(repo, raster); initUserInterface(); } /** * Used to laod data; any DataStore's laoded should be registered in a repository (so they can * be cleaned up). */ private void loadData() { File directory = new File("."); if (directory.exists() && directory.isDirectory()) { // check for shapefiles // File[] shapefiles = directory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toUpperCase().endsWith(".SHP"); } }); for (File shp : shapefiles) { try { FileDataStore dataStore = FileDataStoreFinder.getDataStore(shp); if (dataStore != null) { for (String typeName : dataStore.getTypeNames()) { repo.register(typeName, dataStore); } } } catch (IOException eek) { System.err.println("Unable to load shapefile " + shp + ":" + eek); eek.printStackTrace(System.err); } } // check for geotiff files File[] tiffFiles = directory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toUpperCase().endsWith(".TIF") || name.toUpperCase().endsWith(".TIFF"); } }); for (File tif : tiffFiles) { try { AbstractGridFormat format = GridFormatFinder.findFormat(tif); AbstractGridCoverage2DReader reader = format.getReader(tif); if (reader == null) { System.err.println("Unable to load " + tif); continue; } String fileName = tif.getName(); String name = fileName.substring(0, fileName.lastIndexOf(".") - 1); raster.put(name, reader); } catch (Throwable eek) { System.err.println("Unable to load " + tif + ":" + eek); eek.printStackTrace(System.err); } } } } /** * Displays a GeoTIFF file overlaid with a Shapefile * * @param rasterFile the GeoTIFF file * @param shpFile the Shapefile */ private MapContent createMap(DefaultRepository repo2, Map<String, AbstractGridCoverage2DReader> raster2) { // Set up a MapContext with the two layers final MapContent map = new MapContent(); // use rasters as "basemap" for (Entry<String, AbstractGridCoverage2DReader> entry : raster.entrySet()) { // Initially display the raster in greyscale using the // data from the first image band String name = entry.getKey(); AbstractGridCoverage2DReader reader = entry.getValue(); Style style = createStyle(reader); GridReaderLayer layer = new GridReaderLayer(reader, style); if (reader.getInfo() != null && reader.getInfo().getTitle() != null) { layer.setTitle(reader.getInfo().getTitle()); } map.addLayer(layer); } // add shapefiles on top for (DataStore dataStore : repo.getDataStores()) { try { for( String typeName : dataStore.getTypeNames() ){ SimpleFeatureSource featureSource = dataStore.getFeatureSource( typeName ); // Create a basic style with yellow lines and no fill Style style = SLD.createPolygonStyle(Color.RED, null, 0.0f); FeatureLayer layer = new FeatureLayer( featureSource, style ); if (featureSource.getInfo() != null && featureSource.getInfo().getTitle() != null) { layer.setTitle(featureSource.getInfo().getTitle()); } map.addLayer( layer ); } } catch (IOException e) { System.err.print("Could not load "+dataStore ); } } // configure map map.setTitle("Prototype"); return map; } /* * We create a FeatureCollection into which we will put each Feature created from a record in * the input csv data file */ protected void loadSites() { File csvFile = new File("data/locations.csv"); if (csvFile.exists()) { try { faces = getFeaturesFromFile(csvFile); } catch (Throwable eek) { System.out.println("Could not load faces:" + eek); } } } @SuppressWarnings("deprecation") private void initUserInterface() { getContentPane().setLayout(new BorderLayout()); JScrollPane scrollPane = new JScrollPane(table); getContentPane().add(scrollPane, BorderLayout.SOUTH); // scott this is the collection from csv, read this display table if (faces != null) { FeatureCollectionTableModel model = new FeatureCollectionTableModel(faces); table = new JTable(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setPreferredScrollableViewportSize(new Dimension(800, 200)); table.setModel(model); } /* * mapFrame.setSize(800, 600); mapFrame.enableStatusBar(true); * //frame.enableTool(JMapFrame.Tool.ZOOM, JMapFrame.Tool.PAN, JMapFrame.Tool.RESET); * mapFrame.enableToolBar(true); * * JMenuBar menuBar = new JMenuBar(); mapFrame.setJMenuBar(menuBar); JMenu menu = new * JMenu("Raster"); menuBar.add(menu); * * menu.add( new SafeAction("Grayscale display") { public void action(ActionEvent e) throws * Throwable { Style style = createGreyscaleStyle(); if (style != null) { * map.getLayer(0).setStyle(style); mapFrame.repaint(); } } }); * * menu.add( new SafeAction("RGB display") { public void action(ActionEvent e) throws * Throwable { Style style = createRGBStyle(); if (style != null) { * map.getLayer(0).setStyle(style); mapFrame.repaint(); } } }); */ JMapPane mapPane = new JMapPane(); // set a renderer to use with the map pane mapPane.setRenderer(new StreamingRenderer()); // set the map context that contains the layers to be displayed mapPane.setMapContext( new MapContext( map )); mapPane.setSize(800, 500); toolBar = new JToolBar(); toolBar.setOrientation(JToolBar.HORIZONTAL); toolBar.setFloatable(false); ButtonGroup cursorToolGrp = new ButtonGroup(); JButton zoomInBtn = new JButton(new ZoomInAction(mapPane)); toolBar.add(zoomInBtn); // cursorToolGrp.add(zoomInBtn); JButton zoomOutBtn = new JButton(new ZoomOutAction(mapPane)); toolBar.add(zoomOutBtn); toolBar.setSize(800, 100); // cursorToolGrp.add(zoomOutBtn); - getContentPane().add(toolBar, BorderLayout.CENTER); - getContentPane().add(mapPane, BorderLayout.SOUTH); + getContentPane().add(toolBar, BorderLayout.NORTH); + getContentPane().add(mapPane, BorderLayout.CENTER); // mapFrame.setVisible(true); } /** * Create a Style to display the specified band of the GeoTIFF image as a greyscale layer. * <p> * This method is a helper for createGreyScale() and is also called directly by the * displayLayers() method when the application first starts. * * @param band the image band to use for the greyscale display * * @return a new Style instance to render the image in greyscale */ private Style createGreyscaleStyle(int band) { ContrastEnhancement ce = sf.contrastEnhancement(ff.literal(1.0), ContrastMethod.NORMALIZE); SelectedChannelType sct = sf.createSelectedChannelType(String.valueOf(band), ce); RasterSymbolizer sym = sf.getDefaultRasterSymbolizer(); ChannelSelection sel = sf.channelSelection(sct); sym.setChannelSelection(sel); return SLD.wrapSymbolizers(sym); } /** * This method examines the names of the sample dimensions in the provided coverage looking for * "red...", "green..." and "blue..." (case insensitive match). If these names are not found it * uses bands 1, 2, and 3 for the red, green and blue channels. It then sets up a raster * symbolizer and returns this wrapped in a Style. * * @param reader * * @return a new Style object containing a raster symbolizer set up for RGB image */ private Style createStyle(AbstractGridCoverage2DReader reader) { GridCoverage2D cov = null; try { cov = reader.read(null); } catch (IOException giveUp) { throw new RuntimeException(giveUp); } // We need at least three bands to create an RGB style int numBands = cov.getNumSampleDimensions(); if (numBands < 3) { // assume the first brand return createGreyscaleStyle(1); } // Get the names of the bands String[] sampleDimensionNames = new String[numBands]; for (int i = 0; i < numBands; i++) { GridSampleDimension dim = cov.getSampleDimension(i); sampleDimensionNames[i] = dim.getDescription().toString(); } final int RED = 0, GREEN = 1, BLUE = 2; int[] channelNum = { -1, -1, -1 }; // We examine the band names looking for "red...", "green...", "blue...". // Note that the channel numbers we record are indexed from 1, not 0. for (int i = 0; i < numBands; i++) { String name = sampleDimensionNames[i].toLowerCase(); if (name != null) { if (name.matches("red.*")) { channelNum[RED] = i + 1; } else if (name.matches("green.*")) { channelNum[GREEN] = i + 1; } else if (name.matches("blue.*")) { channelNum[BLUE] = i + 1; } } } // If we didn't find named bands "red...", "green...", "blue..." // we fall back to using the first three bands in order if (channelNum[RED] < 0 || channelNum[GREEN] < 0 || channelNum[BLUE] < 0) { channelNum[RED] = 1; channelNum[GREEN] = 2; channelNum[BLUE] = 3; } // Now we create a RasterSymbolizer using the selected channels SelectedChannelType[] sct = new SelectedChannelType[cov.getNumSampleDimensions()]; ContrastEnhancement ce = sf.contrastEnhancement(ff.literal(1.0), ContrastMethod.NORMALIZE); for (int i = 0; i < 3; i++) { sct[i] = sf.createSelectedChannelType(String.valueOf(channelNum[i]), ce); } RasterSymbolizer sym = sf.getDefaultRasterSymbolizer(); ChannelSelection sel = sf.channelSelection(sct[RED], sct[GREEN], sct[BLUE]); sym.setChannelSelection(sel); return SLD.wrapSymbolizers(sym); } /** * Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile * dynamically. * <p> * This method is an improvement on the code used in the main method above (where we used * DataUtilities.createFeatureType) because we can set a Coordinate Reference System for the * FeatureType and a a maximum field length for the 'name' field dddd */ private static SimpleFeatureType createFeatureType() { SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setName("Location"); builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system // add attributes in order builder.add("Location", Point.class); builder.length(15).add("Name", String.class); // <- 15 chars width for name field builder.length(15).add("Number", Integer.class); // <- 15 chars width for name field // build the type final SimpleFeatureType LOCATION = builder.buildFeatureType(); return LOCATION; } /** * Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile * dynamically. * <p> * This method is an improvement on the code used in the main method above (where we used * DataUtilities.createFeatureType) because we can set a Coordinate Reference System for the * FeatureType and a a maximum field length for the 'name' field dddd */ private SimpleFeatureCollection getFeaturesFromFile(File csvFile) throws Exception { final SimpleFeatureType TYPE = createFeatureType(); /* * We create a FeatureCollection into which we will put each Feature created from a record * in the input csv data file */ SimpleFeatureCollection collection = FeatureCollections.newCollection(); /* * GeometryFactory will be used to create the geometry attribute of each feature (a Point * object for the location) */ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); BufferedReader csvReader = new BufferedReader(new FileReader(csvFile)); try { /* First line of the data file is the header */ String line = csvReader.readLine(); System.out.println("Header: " + line); for (line = csvReader.readLine(); line != null; line = csvReader.readLine()) { if (line.trim().length() > 0) { // skip blank lines String tokens[] = line.split("\\,"); double latitude = Double.parseDouble(tokens[0]); double longitude = Double.parseDouble(tokens[1]); String name = tokens[2].trim(); int number = Integer.parseInt(tokens[3].trim()); /* Longitude (= x coord) first ! */ Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude)); featureBuilder.add(point); featureBuilder.add(name); featureBuilder.add(number); SimpleFeature feature = featureBuilder.buildFeature(null); collection.add(feature); } } } finally { csvReader.close(); } return collection; } /** * Opens the prototype user interface. * <p> * Please note any shapefiles or raster files in the current directory will be used as a * background. * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Prototype app = new Prototype(); // configuration app.init(); // display app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setSize(900, 900); app.setVisible(true); } }
true
true
private void initUserInterface() { getContentPane().setLayout(new BorderLayout()); JScrollPane scrollPane = new JScrollPane(table); getContentPane().add(scrollPane, BorderLayout.SOUTH); // scott this is the collection from csv, read this display table if (faces != null) { FeatureCollectionTableModel model = new FeatureCollectionTableModel(faces); table = new JTable(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setPreferredScrollableViewportSize(new Dimension(800, 200)); table.setModel(model); } /* * mapFrame.setSize(800, 600); mapFrame.enableStatusBar(true); * //frame.enableTool(JMapFrame.Tool.ZOOM, JMapFrame.Tool.PAN, JMapFrame.Tool.RESET); * mapFrame.enableToolBar(true); * * JMenuBar menuBar = new JMenuBar(); mapFrame.setJMenuBar(menuBar); JMenu menu = new * JMenu("Raster"); menuBar.add(menu); * * menu.add( new SafeAction("Grayscale display") { public void action(ActionEvent e) throws * Throwable { Style style = createGreyscaleStyle(); if (style != null) { * map.getLayer(0).setStyle(style); mapFrame.repaint(); } } }); * * menu.add( new SafeAction("RGB display") { public void action(ActionEvent e) throws * Throwable { Style style = createRGBStyle(); if (style != null) { * map.getLayer(0).setStyle(style); mapFrame.repaint(); } } }); */ JMapPane mapPane = new JMapPane(); // set a renderer to use with the map pane mapPane.setRenderer(new StreamingRenderer()); // set the map context that contains the layers to be displayed mapPane.setMapContext( new MapContext( map )); mapPane.setSize(800, 500); toolBar = new JToolBar(); toolBar.setOrientation(JToolBar.HORIZONTAL); toolBar.setFloatable(false); ButtonGroup cursorToolGrp = new ButtonGroup(); JButton zoomInBtn = new JButton(new ZoomInAction(mapPane)); toolBar.add(zoomInBtn); // cursorToolGrp.add(zoomInBtn); JButton zoomOutBtn = new JButton(new ZoomOutAction(mapPane)); toolBar.add(zoomOutBtn); toolBar.setSize(800, 100); // cursorToolGrp.add(zoomOutBtn); getContentPane().add(toolBar, BorderLayout.CENTER); getContentPane().add(mapPane, BorderLayout.SOUTH); // mapFrame.setVisible(true); }
private void initUserInterface() { getContentPane().setLayout(new BorderLayout()); JScrollPane scrollPane = new JScrollPane(table); getContentPane().add(scrollPane, BorderLayout.SOUTH); // scott this is the collection from csv, read this display table if (faces != null) { FeatureCollectionTableModel model = new FeatureCollectionTableModel(faces); table = new JTable(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setPreferredScrollableViewportSize(new Dimension(800, 200)); table.setModel(model); } /* * mapFrame.setSize(800, 600); mapFrame.enableStatusBar(true); * //frame.enableTool(JMapFrame.Tool.ZOOM, JMapFrame.Tool.PAN, JMapFrame.Tool.RESET); * mapFrame.enableToolBar(true); * * JMenuBar menuBar = new JMenuBar(); mapFrame.setJMenuBar(menuBar); JMenu menu = new * JMenu("Raster"); menuBar.add(menu); * * menu.add( new SafeAction("Grayscale display") { public void action(ActionEvent e) throws * Throwable { Style style = createGreyscaleStyle(); if (style != null) { * map.getLayer(0).setStyle(style); mapFrame.repaint(); } } }); * * menu.add( new SafeAction("RGB display") { public void action(ActionEvent e) throws * Throwable { Style style = createRGBStyle(); if (style != null) { * map.getLayer(0).setStyle(style); mapFrame.repaint(); } } }); */ JMapPane mapPane = new JMapPane(); // set a renderer to use with the map pane mapPane.setRenderer(new StreamingRenderer()); // set the map context that contains the layers to be displayed mapPane.setMapContext( new MapContext( map )); mapPane.setSize(800, 500); toolBar = new JToolBar(); toolBar.setOrientation(JToolBar.HORIZONTAL); toolBar.setFloatable(false); ButtonGroup cursorToolGrp = new ButtonGroup(); JButton zoomInBtn = new JButton(new ZoomInAction(mapPane)); toolBar.add(zoomInBtn); // cursorToolGrp.add(zoomInBtn); JButton zoomOutBtn = new JButton(new ZoomOutAction(mapPane)); toolBar.add(zoomOutBtn); toolBar.setSize(800, 100); // cursorToolGrp.add(zoomOutBtn); getContentPane().add(toolBar, BorderLayout.NORTH); getContentPane().add(mapPane, BorderLayout.CENTER); // mapFrame.setVisible(true); }
diff --git a/src/net/sqdmc/bubbleshield/ShieldListener.java b/src/net/sqdmc/bubbleshield/ShieldListener.java index dbc150f..e4aa777 100644 --- a/src/net/sqdmc/bubbleshield/ShieldListener.java +++ b/src/net/sqdmc/bubbleshield/ShieldListener.java @@ -1,715 +1,715 @@ package net.sqdmc.bubbleshield; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.logging.Logger; import net.sqdmc.bubbleshield.ShieldBase.ShieldType; import net.sqdmc.bubbleshield.ShieldOwnerFaction; import net.sqdmc.bubbleshield.Shield; import net.sqdmc.bubbleshield.ShieldBase; import net.sqdmc.bubbleshield.BubbleShield; import net.sqdmc.bubbleshield.ShieldStorage; import net.sqdmc.bubbleshield.ShieldTimer; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityExplodeEvent; import com.massivecraft.factions.Board; import com.massivecraft.factions.Faction; public class ShieldListener implements Listener { private BubbleShield plugin; private Logger log = Bukkit.getServer().getLogger(); BSConfiguration config; ShieldStorage shieldstorage; ArrayList<ShieldBase> ShieldBases; private HashMap<Integer, Integer> ShieldDurability = new HashMap<Integer, Integer>(); private HashMap<Integer, Timer> shieldTimer = new HashMap<Integer, Timer>(); public ShieldListener(BubbleShield plugin) { this.plugin = plugin; config = plugin.getBSConfig(); if (shieldstorage != null) { } else { log.info("[BubbleShield] : Creating new shieldstorage..."); shieldstorage = new ShieldStorage(); } ShieldBases = shieldstorage.GetShieldBases(); } /* ============================================================================= * EXPLODE! * */ @EventHandler(priority = EventPriority.NORMAL) public void onEntityExplode(EntityExplodeEvent event) { if (event == null || event.isCancelled()) { return; } ShieldBases = shieldstorage.GetShieldBases(); List<Block> blocks = event.blockList(); for (Block block : blocks) { // assumes set of shields is available for (ShieldBase shieldBase : ShieldBases) { boolean bShieldExists = shieldstorage.GetShieldBases().contains(shieldBase); if (!bShieldExists) { shieldBase.destroy(); log.info("[BubbleShield] : Destroyed abandoned ShieldBase at " + shieldBase.getShieldBaseLocString()); return; } if (blockProtected(block,shieldBase) && shieldstorage.affectedBlockCount < config.getAffectedBlockCountMax()) { //log.info("[BubbleShield] : " + "Shield Damage Taken! " + shieldBase.getShieldBaseLocString()); decreaseDurability(shieldBase); shieldstorage.affectedBlockCount++; Timer timer = new Timer(); timer.schedule(new HitTimer(plugin), 500); if (!event.isCancelled()) event.setCancelled(true); return; } else if (blockProtected(block,shieldBase)) { if (!event.isCancelled()) event.setCancelled(true); return; } } } } /** is block protected by a given shieldbase? */ private boolean blockProtected(Block block, ShieldBase shieldBase) { double radius = config.getShieldRadius(); // first linear checks if (!block.getWorld().getName().equals(shieldBase.world.getName())) return false; if (Math.abs(block.getX() - shieldBase.x)>radius || Math.abs(block.getY() - shieldBase.y)>radius || Math.abs(block.getZ() - shieldBase.z)>radius) { return false; } Location shieldLoc = new Location(shieldBase.world, shieldBase.x, shieldBase.y, shieldBase.z); double distSquared = shieldLoc.distanceSquared(block.getLocation()); return radius*radius >= distSquared; } private void decreaseDurability(ShieldBase shieldBase) { // manage durability stuff Location signLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Location spongeLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y), shieldBase.z); Block signBlock = signLoc.getBlock(); Block ShieldBlock = spongeLoc.getBlock(); //signBlock.getRelative(BlockFace.DOWN); //log.info("[BubbleShield] : decreaseDurability() " + signLoc.toString() + " " + signBlock.getType()); if ((signBlock.getType() == Material.SIGN || signBlock.getType() == Material.SIGN_POST || signBlock.getType() == Material.WALL_SIGN )) { // && ShieldBlock.getType() == Material.SPONGE){ Sign s = (Sign) signBlock.getState(); String shi = s.getLine(0); int maxpower = Integer.parseInt(s.getLine(2)); int pow = Integer.parseInt(s.getLine(3)); if (! (shi.equalsIgnoreCase("[shield]") || shi.equalsIgnoreCase("[f shield]"))) { return; } shieldBase.setShieldMaxPower(maxpower); ShieldBases = shieldstorage.GetShieldBases(); //log.info("[BubbleShield] : decreaseDurability() " + spongeLoc.toString()); boolean bShieldExists = shieldstorage.checkShieldExist(shieldBase, ShieldBases); if (!bShieldExists) { shieldBase.destroy(); TNTBreakShield(ShieldBlock); log.info("[BubbleShield] : Destroyed abandoned ShieldBase at " + shieldBase.getShieldBaseLocString()); return; } if (bShieldExists) { Integer representation = spongeLoc.getWorld().hashCode() + spongeLoc.getBlockX() * 2389 + spongeLoc.getBlockY() * 4027 + spongeLoc.getBlockZ() * 2053; pow--; shieldBase.shield.setShieldPower(pow); if (pow <= 0) { TNTBreakShield(ShieldBlock); return; } if (pow > 0){ String newpower = String.valueOf(pow); s.setLine(3, newpower); s.update(); shieldBase.shield.owner.sendMessage("Shield Power at " + newpower + "!"); if (ShieldDurability.containsKey(representation)) { int currentDurability = (int) ShieldDurability.get(representation); currentDurability++; if (checkIfMax(currentDurability)) { // counter has reached max durability //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max Shield Dura"); TNTBreakShield(ShieldBlock); ResetTime(representation, spongeLoc); return; } else { // counter has not reached max durability yet ShieldDurability.put(representation, currentDurability); //log.info("[BubbleShield] : onEntityExplode() " + "Set already, set Shield Dura"); startNewTimer(representation, shieldBase); } } else { ShieldDurability.put(representation, 1); //log.info("[BubbleShield] : onEntityExplode() " + "Set New Shield Dura"); shieldBase.setShieldMaxPower(pow); startNewTimer(representation, shieldBase); if (checkIfMax(1)) { TNTBreakShield(ShieldBlock); ResetTime(representation, spongeLoc); //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max"); return; } } } return; } } } /* ================================================================ * REGEN * * ================================================================ */ public void RegenPowerLoss(ShieldBase shieldBase) { if (shieldBase != null) { Sign sign = null; Location signlocation = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Location sponglocation = new Location(shieldBase.world, shieldBase.x, (shieldBase.y), shieldBase.z); try { sign = (Sign) signlocation.getBlock().getState(); } catch (java.lang.ClassCastException e) { return; } int max = Integer.parseInt(sign.getLine(2)); int currentpower = Integer.parseInt(sign.getLine(3)); if ( currentpower < max ) { String newpower = String.valueOf(currentpower+1); shieldBase.shield.setShieldPower(currentpower+1); sign.setLine(3, newpower); sign.update(); shieldBase.shield.owner.sendMessage("Shield Power at " + newpower + "!"); Integer representation = shieldBase.world.hashCode() + shieldBase.x * 2389 + shieldBase.y * 4027 + shieldBase.z * 2053; if (ShieldDurability.containsKey(representation)) { int currentDurability = (int) ShieldDurability.get(representation); currentDurability++; if (checkIfMax(currentDurability)) { // counter has reached max durability //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max Shield Dura"); ResetTime(representation, sponglocation); return; } else { // counter has not reached max durability yet ShieldDurability.put(representation, currentDurability); //log.info("[BubbleShield] : onEntityExplode() " + "Set already, set Shield Dura"); startNewTimer(representation, shieldBase); } } else { ShieldDurability.put(representation, 1); //log.info("[BubbleShield] : onEntityExplode() " + "Set New Shield Dura"); startNewTimer(representation, shieldBase); if (checkIfMax(1)) { ResetTime(representation, sponglocation); //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max"); return; } } } } } /* ================================================================ * CREATE * * ================================================================ */ @EventHandler public void createShield(SignChangeEvent event) { Player player = event.getPlayer(); ShieldOwner shieldowner = null; ShieldType shieldType; String line0 = event.getLine(0); String line1 = event.getLine(1); if (line0.equalsIgnoreCase("[shield]")) { if (!player.hasPermission("bubbleshield.create.player") || !config.getUseWildShield()) { player.sendMessage("You do not have permission to create this shield."); return; } shieldType = ShieldType.Player; } else if (line0.equalsIgnoreCase("[f shield]") && line1 != null && !line1.equals("")) { if (!player.hasPermission("bubbleshield.create.faction") || !config.getUseFactionShield()) { player.sendMessage("You do not have permission to create this shield."); return; } shieldType = ShieldType.Faction; } else return; // not for us! if (!Util.isNumeric(line1) && shieldType == ShieldType.Faction) { player.sendMessage("Shield Power must be a number on the second line."); event.getBlock().breakNaturally(); return; } int shieldPower = 0; Block signBlock = event.getBlock(); Block shieldBlock = signBlock.getRelative(BlockFace.DOWN); if (shieldType == ShieldType.Player && ( shieldBlock.getType() == Material.IRON_BLOCK || shieldBlock.getType() == Material.GOLD_BLOCK || shieldBlock.getType() == Material.DIAMOND_BLOCK || shieldBlock.getType() == Material.EMERALD_BLOCK || shieldBlock.getType() == Material.SPONGE)) { shieldowner = new ShieldOwnerPlayer(player); shieldPower = Util.getShieldPowerFromBlock(shieldBlock, config); //Block block = (Block)shieldBlock; int shieldCount = Util.getShieldCount(shieldstorage, shieldowner.getOwner()); if (shieldstorage.getBlockShieldBase() != null){ if (shieldCount > config.getMaxWildShieldCount()){ shieldowner.sendMessage("You have the maximum amount of Shields."); shieldBlock.breakNaturally(); return; } } try { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); //shieldowner = new ShieldOwnerFaction(faction); if (!faction.getId().equals("0")) { shieldowner.sendMessage("You cannot create this shield here."); shieldBlock.breakNaturally(); Bukkit.getWorld(shieldBlock.getWorld().getName()).createExplosion(shieldBlock.getLocation(), 1); return; } } catch (Exception e) { log.info("[BubbleShield] : Create shield in Faction Null Error..."); } event.setLine(1, shieldowner.getOwner()); } else if (shieldType == ShieldType.Faction && shieldBlock.getType() == Material.SPONGE) { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); shieldowner = new ShieldOwnerFaction(faction); shieldPower = Integer.parseInt(line1); Block Sponge = (Block)shieldBlock; if (Sponge.getType() != Material.SPONGE) { player.sendMessage("You can only create Factions Shields with a sponge."); event.getBlock().breakNaturally(); return; } if (faction.getId().equals("-2") || faction.getId().equals("-1") || faction.getId().equals("0") ) { player.sendMessage("You can only create Shields in land you own."); event.getBlock().breakNaturally(); return; } if (shieldPower < 1) { player.sendMessage("Shield must have a power of greater than zero."); event.getBlock().breakNaturally(); return; } if (shieldPower > config.getMaxPowerCost() || shieldPower > faction.getPower()) { player.sendMessage("Not enough power to create Shield!"); signBlock.breakNaturally(); Sponge.breakNaturally(); return; } int shieldCount = Util.getShieldCount(shieldstorage, shieldowner.getOwner()); if (shieldstorage.getBlockShieldBase() != null){ if (shieldCount > config.getMaxFactionShieldCount()){ //log.info("[BubbleShield] : " + fshieldowner.getId() + " Has the maximum amount of Shields.!"); player.sendMessage("You have the maximum amount of Shields."); shieldBlock.breakNaturally(); return; } else if (shieldCount == 0) { faction.setPowerLoss(0); } } faction.addPowerLoss(-shieldPower); event.setLine(1, faction.getTag()); } else { player.sendMessage("Invalid Shield!"); signBlock.breakNaturally(); return; } event.setLine(2, Integer.toString(shieldPower)); event.setLine(3, Integer.toString(shieldPower)); Shield shield = Util.getShield(shieldowner, shieldstorage); shield.setShieldPower(shieldPower); shield.setMaxShieldPower(shieldPower); ShieldBase shieldbase = new ShieldBase(shieldBlock, signBlock, shield, shieldBlock.getWorld(),shieldBlock.getX(),shieldBlock.getY(),shieldBlock.getZ()); shieldbase.setType(shieldType); shieldbase.setShieldMaxPower(shieldPower); shieldstorage.addBlockShieldBase(signBlock, shieldbase); shieldstorage.addBlockShieldBase(shieldBlock, shieldbase); log.info("[BubbleShield] : " + "Shield created by "+ player.getName() + " At location: " + shieldbase.getShieldBaseLocString() + " For Faction/Player: " + shield.getShieldOwner().getOwner() + " With power of: " + shieldPower); shieldowner.sendMessage("Shield Created"); try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * DESTROY */ @EventHandler public void shieldBroken(BlockBreakEvent event) { Block block = event.getBlock(); ShieldBase shieldBase = shieldstorage.getBlockShieldBase().get(block); if (shieldBase != null) { Shield shield = shieldBase.shield; Player player = event.getPlayer(); Location signLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Block signBlock = signLoc.getBlock(); Sign sign = (Sign) signBlock.getState(); int maxpower = Integer.parseInt(sign.getLine(2)); int pow = Integer.parseInt(sign.getLine(3)); if (shieldBase.getType() == ShieldType.Player && player != Bukkit.getPlayer(sign.getLine(1))) { player.sendMessage("Can not break shield unless you own it!"); event.setCancelled(true); return; } if (pow != maxpower) { player.sendMessage("Can not break shield unless it is fully charged!"); event.setCancelled(true); return; } shieldBase.destroy(); ShieldOwnerFaction fShieldOwner = new ShieldOwnerFaction(Board.getFactionAt(block)); shieldstorage.removeShields(fShieldOwner); shieldstorage.removeBlockShieldBase(shieldBase.sponge); shieldstorage.removeBlockShieldBase(shieldBase.sign); if (shieldBase.getType() == ShieldType.Faction) { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); faction.addPowerLoss(maxpower); } shield.owner.sendMessage("Shield Destroyed!"); try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void TNTBreakShield(Block shieldblock) { ShieldBase shieldBase = shieldstorage.getBlockShieldBase().get(shieldblock); if (shieldBase != null) { Shield shield = shieldBase.shield; ShieldOwnerFaction fShieldOwner = new ShieldOwnerFaction(Board.getFactionAt(shieldblock)); Sign sign = (Sign) shieldBase.sign.getState(); shieldstorage.removeShields(fShieldOwner); shieldstorage.removeBlockShieldBase(shieldBase.sponge); shieldstorage.removeBlockShieldBase(shieldBase.sign); shieldBase.destroy(); String maxpower = sign.getLine(2); int explosionpower = Math.round(Integer.parseInt(maxpower) / 4); //log.info("Explosion Power: " + explosionpower + " MaxShield: " + shieldBase.shield.getShieldPowerMax()); if (explosionpower >= 11) explosionpower = 11; else if (explosionpower <= 2) explosionpower = 2; log.info("[BubbleShield] : " + "Shield exploded with Explosion Power of: " + explosionpower + " For Faction " + shieldBase.shield.getShieldOwner().getOwner()); shieldblock.getWorld().createExplosion(shieldblock.getLocation(), explosionpower, true); shield.owner.sendMessage("Shield Destroyed!"); shieldblock.breakNaturally(); if (shieldBase.getType() == ShieldType.Faction) { Faction faction = Board.getFactionAt(shieldblock); faction.addPowerLoss(Integer.parseInt(maxpower)); } try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* ========================================================================= * Shield Area Block Break * * */ @EventHandler public void shieldAreaBlockBreak(BlockBreakEvent event) { if (event == null || event.isCancelled()) { return; } if (!config.getUseShieldBuildProtection()) { return; } ShieldBases = shieldstorage.GetShieldBases(); Block block = event.getBlock(); - for (ShieldBase shieldBase : ShieldBases) { + for (ShieldBase shieldBase : ShieldBases) { + if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) + return; if (!event.getPlayer().getName().equals(shieldBase.shield.getShieldOwner().getOwner())) { if (blockProtected(block,shieldBase) ) { //log.info("[BubbleShield] : " + "Shield Block Attempt Break! " + shieldBase.getShieldBaseLocString()); if (!event.isCancelled()) event.setCancelled(true); return; } } - if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) - return; } } @EventHandler public void shieldAreaBlockPlace(BlockPlaceEvent event) { if (event == null || event.isCancelled()) { return; } if (!config.getUseShieldBuildProtection()) { return; } ShieldBases = shieldstorage.GetShieldBases(); Block block = event.getBlock(); for (ShieldBase shieldBase : ShieldBases) { + if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) + return; if (!event.getPlayer().getName().equals(shieldBase.shield.getShieldOwner().getOwner()) ) { if (blockProtected(block,shieldBase) ) { //log.info("[BubbleShield] : " + "Shield Block Attempt Place! " + shieldBase.getShieldBaseLocString()); if (!event.isCancelled()) event.setCancelled(true); return; } } - if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) - return; } } /* ========================================================================= * TIMERS * * */ private void startNewTimer(Integer representation, ShieldBase shieldbase) { if (shieldTimer.get(representation) != null) { shieldTimer.get(representation).cancel(); } Timer timer = new Timer(); timer.schedule(new ShieldTimer(plugin, representation, shieldbase), config.getRegenTime()); shieldTimer.put(representation, timer); } private boolean checkIfMax(int value) { return value == config.getMaxPowerCost(); } private void ResetTime(Integer representation, Location at) { ShieldDurability.remove(representation); if (shieldTimer.get(representation) != null) { shieldTimer.get(representation).cancel(); } shieldTimer.remove(representation); } /** * Returns the HashMap containing all saved durabilities. * * @return the HashMap containing all saved durabilities */ public HashMap<Integer, Integer> getShieldDurability() { return ShieldDurability; } /** * Sets the HashMap containing all saved durabilities. * * @param map * the HashMap containing all saved durabilities */ public void setShieldDurability(HashMap<Integer, Integer> map) { if (map == null) { return; } ShieldDurability = map; } /** * Returns the HashMap containing all saved durability timers. * * @return the HashMap containing all saved durability timers */ public HashMap<Integer, Timer> getObsidianTimer() { return shieldTimer; } /** * Sets the HashMap containing all saved durability timers. * * @param map * the HashMap containing all saved durability timers */ public void setShieldTimer(HashMap<Integer, Timer> map) { if (map == null) { return; } shieldTimer = map; } public HashMap<ShieldOwner, Shield> getShields() { return shieldstorage.getShields(); } public void setShields(HashMap<ShieldOwner, Shield> map) { if (map == null) { return; } shieldstorage.setShields(map); } public HashMap<Block, ShieldBase> getShieldsBase() { return shieldstorage.getBlockShieldBase(); } public void setShieldBase(HashMap<Block, ShieldBase> map) { if (map == null) { return; } shieldstorage.setBlockShieldBase(map); } }
false
true
private void decreaseDurability(ShieldBase shieldBase) { // manage durability stuff Location signLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Location spongeLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y), shieldBase.z); Block signBlock = signLoc.getBlock(); Block ShieldBlock = spongeLoc.getBlock(); //signBlock.getRelative(BlockFace.DOWN); //log.info("[BubbleShield] : decreaseDurability() " + signLoc.toString() + " " + signBlock.getType()); if ((signBlock.getType() == Material.SIGN || signBlock.getType() == Material.SIGN_POST || signBlock.getType() == Material.WALL_SIGN )) { // && ShieldBlock.getType() == Material.SPONGE){ Sign s = (Sign) signBlock.getState(); String shi = s.getLine(0); int maxpower = Integer.parseInt(s.getLine(2)); int pow = Integer.parseInt(s.getLine(3)); if (! (shi.equalsIgnoreCase("[shield]") || shi.equalsIgnoreCase("[f shield]"))) { return; } shieldBase.setShieldMaxPower(maxpower); ShieldBases = shieldstorage.GetShieldBases(); //log.info("[BubbleShield] : decreaseDurability() " + spongeLoc.toString()); boolean bShieldExists = shieldstorage.checkShieldExist(shieldBase, ShieldBases); if (!bShieldExists) { shieldBase.destroy(); TNTBreakShield(ShieldBlock); log.info("[BubbleShield] : Destroyed abandoned ShieldBase at " + shieldBase.getShieldBaseLocString()); return; } if (bShieldExists) { Integer representation = spongeLoc.getWorld().hashCode() + spongeLoc.getBlockX() * 2389 + spongeLoc.getBlockY() * 4027 + spongeLoc.getBlockZ() * 2053; pow--; shieldBase.shield.setShieldPower(pow); if (pow <= 0) { TNTBreakShield(ShieldBlock); return; } if (pow > 0){ String newpower = String.valueOf(pow); s.setLine(3, newpower); s.update(); shieldBase.shield.owner.sendMessage("Shield Power at " + newpower + "!"); if (ShieldDurability.containsKey(representation)) { int currentDurability = (int) ShieldDurability.get(representation); currentDurability++; if (checkIfMax(currentDurability)) { // counter has reached max durability //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max Shield Dura"); TNTBreakShield(ShieldBlock); ResetTime(representation, spongeLoc); return; } else { // counter has not reached max durability yet ShieldDurability.put(representation, currentDurability); //log.info("[BubbleShield] : onEntityExplode() " + "Set already, set Shield Dura"); startNewTimer(representation, shieldBase); } } else { ShieldDurability.put(representation, 1); //log.info("[BubbleShield] : onEntityExplode() " + "Set New Shield Dura"); shieldBase.setShieldMaxPower(pow); startNewTimer(representation, shieldBase); if (checkIfMax(1)) { TNTBreakShield(ShieldBlock); ResetTime(representation, spongeLoc); //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max"); return; } } } return; } } } /* ================================================================ * REGEN * * ================================================================ */ public void RegenPowerLoss(ShieldBase shieldBase) { if (shieldBase != null) { Sign sign = null; Location signlocation = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Location sponglocation = new Location(shieldBase.world, shieldBase.x, (shieldBase.y), shieldBase.z); try { sign = (Sign) signlocation.getBlock().getState(); } catch (java.lang.ClassCastException e) { return; } int max = Integer.parseInt(sign.getLine(2)); int currentpower = Integer.parseInt(sign.getLine(3)); if ( currentpower < max ) { String newpower = String.valueOf(currentpower+1); shieldBase.shield.setShieldPower(currentpower+1); sign.setLine(3, newpower); sign.update(); shieldBase.shield.owner.sendMessage("Shield Power at " + newpower + "!"); Integer representation = shieldBase.world.hashCode() + shieldBase.x * 2389 + shieldBase.y * 4027 + shieldBase.z * 2053; if (ShieldDurability.containsKey(representation)) { int currentDurability = (int) ShieldDurability.get(representation); currentDurability++; if (checkIfMax(currentDurability)) { // counter has reached max durability //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max Shield Dura"); ResetTime(representation, sponglocation); return; } else { // counter has not reached max durability yet ShieldDurability.put(representation, currentDurability); //log.info("[BubbleShield] : onEntityExplode() " + "Set already, set Shield Dura"); startNewTimer(representation, shieldBase); } } else { ShieldDurability.put(representation, 1); //log.info("[BubbleShield] : onEntityExplode() " + "Set New Shield Dura"); startNewTimer(representation, shieldBase); if (checkIfMax(1)) { ResetTime(representation, sponglocation); //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max"); return; } } } } } /* ================================================================ * CREATE * * ================================================================ */ @EventHandler public void createShield(SignChangeEvent event) { Player player = event.getPlayer(); ShieldOwner shieldowner = null; ShieldType shieldType; String line0 = event.getLine(0); String line1 = event.getLine(1); if (line0.equalsIgnoreCase("[shield]")) { if (!player.hasPermission("bubbleshield.create.player") || !config.getUseWildShield()) { player.sendMessage("You do not have permission to create this shield."); return; } shieldType = ShieldType.Player; } else if (line0.equalsIgnoreCase("[f shield]") && line1 != null && !line1.equals("")) { if (!player.hasPermission("bubbleshield.create.faction") || !config.getUseFactionShield()) { player.sendMessage("You do not have permission to create this shield."); return; } shieldType = ShieldType.Faction; } else return; // not for us! if (!Util.isNumeric(line1) && shieldType == ShieldType.Faction) { player.sendMessage("Shield Power must be a number on the second line."); event.getBlock().breakNaturally(); return; } int shieldPower = 0; Block signBlock = event.getBlock(); Block shieldBlock = signBlock.getRelative(BlockFace.DOWN); if (shieldType == ShieldType.Player && ( shieldBlock.getType() == Material.IRON_BLOCK || shieldBlock.getType() == Material.GOLD_BLOCK || shieldBlock.getType() == Material.DIAMOND_BLOCK || shieldBlock.getType() == Material.EMERALD_BLOCK || shieldBlock.getType() == Material.SPONGE)) { shieldowner = new ShieldOwnerPlayer(player); shieldPower = Util.getShieldPowerFromBlock(shieldBlock, config); //Block block = (Block)shieldBlock; int shieldCount = Util.getShieldCount(shieldstorage, shieldowner.getOwner()); if (shieldstorage.getBlockShieldBase() != null){ if (shieldCount > config.getMaxWildShieldCount()){ shieldowner.sendMessage("You have the maximum amount of Shields."); shieldBlock.breakNaturally(); return; } } try { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); //shieldowner = new ShieldOwnerFaction(faction); if (!faction.getId().equals("0")) { shieldowner.sendMessage("You cannot create this shield here."); shieldBlock.breakNaturally(); Bukkit.getWorld(shieldBlock.getWorld().getName()).createExplosion(shieldBlock.getLocation(), 1); return; } } catch (Exception e) { log.info("[BubbleShield] : Create shield in Faction Null Error..."); } event.setLine(1, shieldowner.getOwner()); } else if (shieldType == ShieldType.Faction && shieldBlock.getType() == Material.SPONGE) { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); shieldowner = new ShieldOwnerFaction(faction); shieldPower = Integer.parseInt(line1); Block Sponge = (Block)shieldBlock; if (Sponge.getType() != Material.SPONGE) { player.sendMessage("You can only create Factions Shields with a sponge."); event.getBlock().breakNaturally(); return; } if (faction.getId().equals("-2") || faction.getId().equals("-1") || faction.getId().equals("0") ) { player.sendMessage("You can only create Shields in land you own."); event.getBlock().breakNaturally(); return; } if (shieldPower < 1) { player.sendMessage("Shield must have a power of greater than zero."); event.getBlock().breakNaturally(); return; } if (shieldPower > config.getMaxPowerCost() || shieldPower > faction.getPower()) { player.sendMessage("Not enough power to create Shield!"); signBlock.breakNaturally(); Sponge.breakNaturally(); return; } int shieldCount = Util.getShieldCount(shieldstorage, shieldowner.getOwner()); if (shieldstorage.getBlockShieldBase() != null){ if (shieldCount > config.getMaxFactionShieldCount()){ //log.info("[BubbleShield] : " + fshieldowner.getId() + " Has the maximum amount of Shields.!"); player.sendMessage("You have the maximum amount of Shields."); shieldBlock.breakNaturally(); return; } else if (shieldCount == 0) { faction.setPowerLoss(0); } } faction.addPowerLoss(-shieldPower); event.setLine(1, faction.getTag()); } else { player.sendMessage("Invalid Shield!"); signBlock.breakNaturally(); return; } event.setLine(2, Integer.toString(shieldPower)); event.setLine(3, Integer.toString(shieldPower)); Shield shield = Util.getShield(shieldowner, shieldstorage); shield.setShieldPower(shieldPower); shield.setMaxShieldPower(shieldPower); ShieldBase shieldbase = new ShieldBase(shieldBlock, signBlock, shield, shieldBlock.getWorld(),shieldBlock.getX(),shieldBlock.getY(),shieldBlock.getZ()); shieldbase.setType(shieldType); shieldbase.setShieldMaxPower(shieldPower); shieldstorage.addBlockShieldBase(signBlock, shieldbase); shieldstorage.addBlockShieldBase(shieldBlock, shieldbase); log.info("[BubbleShield] : " + "Shield created by "+ player.getName() + " At location: " + shieldbase.getShieldBaseLocString() + " For Faction/Player: " + shield.getShieldOwner().getOwner() + " With power of: " + shieldPower); shieldowner.sendMessage("Shield Created"); try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * DESTROY */ @EventHandler public void shieldBroken(BlockBreakEvent event) { Block block = event.getBlock(); ShieldBase shieldBase = shieldstorage.getBlockShieldBase().get(block); if (shieldBase != null) { Shield shield = shieldBase.shield; Player player = event.getPlayer(); Location signLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Block signBlock = signLoc.getBlock(); Sign sign = (Sign) signBlock.getState(); int maxpower = Integer.parseInt(sign.getLine(2)); int pow = Integer.parseInt(sign.getLine(3)); if (shieldBase.getType() == ShieldType.Player && player != Bukkit.getPlayer(sign.getLine(1))) { player.sendMessage("Can not break shield unless you own it!"); event.setCancelled(true); return; } if (pow != maxpower) { player.sendMessage("Can not break shield unless it is fully charged!"); event.setCancelled(true); return; } shieldBase.destroy(); ShieldOwnerFaction fShieldOwner = new ShieldOwnerFaction(Board.getFactionAt(block)); shieldstorage.removeShields(fShieldOwner); shieldstorage.removeBlockShieldBase(shieldBase.sponge); shieldstorage.removeBlockShieldBase(shieldBase.sign); if (shieldBase.getType() == ShieldType.Faction) { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); faction.addPowerLoss(maxpower); } shield.owner.sendMessage("Shield Destroyed!"); try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void TNTBreakShield(Block shieldblock) { ShieldBase shieldBase = shieldstorage.getBlockShieldBase().get(shieldblock); if (shieldBase != null) { Shield shield = shieldBase.shield; ShieldOwnerFaction fShieldOwner = new ShieldOwnerFaction(Board.getFactionAt(shieldblock)); Sign sign = (Sign) shieldBase.sign.getState(); shieldstorage.removeShields(fShieldOwner); shieldstorage.removeBlockShieldBase(shieldBase.sponge); shieldstorage.removeBlockShieldBase(shieldBase.sign); shieldBase.destroy(); String maxpower = sign.getLine(2); int explosionpower = Math.round(Integer.parseInt(maxpower) / 4); //log.info("Explosion Power: " + explosionpower + " MaxShield: " + shieldBase.shield.getShieldPowerMax()); if (explosionpower >= 11) explosionpower = 11; else if (explosionpower <= 2) explosionpower = 2; log.info("[BubbleShield] : " + "Shield exploded with Explosion Power of: " + explosionpower + " For Faction " + shieldBase.shield.getShieldOwner().getOwner()); shieldblock.getWorld().createExplosion(shieldblock.getLocation(), explosionpower, true); shield.owner.sendMessage("Shield Destroyed!"); shieldblock.breakNaturally(); if (shieldBase.getType() == ShieldType.Faction) { Faction faction = Board.getFactionAt(shieldblock); faction.addPowerLoss(Integer.parseInt(maxpower)); } try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* ========================================================================= * Shield Area Block Break * * */ @EventHandler public void shieldAreaBlockBreak(BlockBreakEvent event) { if (event == null || event.isCancelled()) { return; } if (!config.getUseShieldBuildProtection()) { return; } ShieldBases = shieldstorage.GetShieldBases(); Block block = event.getBlock(); for (ShieldBase shieldBase : ShieldBases) { if (!event.getPlayer().getName().equals(shieldBase.shield.getShieldOwner().getOwner())) { if (blockProtected(block,shieldBase) ) { //log.info("[BubbleShield] : " + "Shield Block Attempt Break! " + shieldBase.getShieldBaseLocString()); if (!event.isCancelled()) event.setCancelled(true); return; } } if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) return; } } @EventHandler public void shieldAreaBlockPlace(BlockPlaceEvent event) { if (event == null || event.isCancelled()) { return; } if (!config.getUseShieldBuildProtection()) { return; } ShieldBases = shieldstorage.GetShieldBases(); Block block = event.getBlock(); for (ShieldBase shieldBase : ShieldBases) { if (!event.getPlayer().getName().equals(shieldBase.shield.getShieldOwner().getOwner()) ) { if (blockProtected(block,shieldBase) ) { //log.info("[BubbleShield] : " + "Shield Block Attempt Place! " + shieldBase.getShieldBaseLocString()); if (!event.isCancelled()) event.setCancelled(true); return; } } if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) return; } } /* ========================================================================= * TIMERS * * */ private void startNewTimer(Integer representation, ShieldBase shieldbase) { if (shieldTimer.get(representation) != null) { shieldTimer.get(representation).cancel(); } Timer timer = new Timer(); timer.schedule(new ShieldTimer(plugin, representation, shieldbase), config.getRegenTime()); shieldTimer.put(representation, timer); } private boolean checkIfMax(int value) { return value == config.getMaxPowerCost(); } private void ResetTime(Integer representation, Location at) { ShieldDurability.remove(representation); if (shieldTimer.get(representation) != null) { shieldTimer.get(representation).cancel(); } shieldTimer.remove(representation); } /** * Returns the HashMap containing all saved durabilities. * * @return the HashMap containing all saved durabilities */ public HashMap<Integer, Integer> getShieldDurability() { return ShieldDurability; } /** * Sets the HashMap containing all saved durabilities. * * @param map * the HashMap containing all saved durabilities */ public void setShieldDurability(HashMap<Integer, Integer> map) { if (map == null) { return; } ShieldDurability = map; } /** * Returns the HashMap containing all saved durability timers. * * @return the HashMap containing all saved durability timers */ public HashMap<Integer, Timer> getObsidianTimer() { return shieldTimer; } /** * Sets the HashMap containing all saved durability timers. * * @param map * the HashMap containing all saved durability timers */ public void setShieldTimer(HashMap<Integer, Timer> map) { if (map == null) { return; } shieldTimer = map; } public HashMap<ShieldOwner, Shield> getShields() { return shieldstorage.getShields(); } public void setShields(HashMap<ShieldOwner, Shield> map) { if (map == null) { return; } shieldstorage.setShields(map); } public HashMap<Block, ShieldBase> getShieldsBase() { return shieldstorage.getBlockShieldBase(); } public void setShieldBase(HashMap<Block, ShieldBase> map) { if (map == null) { return; } shieldstorage.setBlockShieldBase(map); } }
private void decreaseDurability(ShieldBase shieldBase) { // manage durability stuff Location signLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Location spongeLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y), shieldBase.z); Block signBlock = signLoc.getBlock(); Block ShieldBlock = spongeLoc.getBlock(); //signBlock.getRelative(BlockFace.DOWN); //log.info("[BubbleShield] : decreaseDurability() " + signLoc.toString() + " " + signBlock.getType()); if ((signBlock.getType() == Material.SIGN || signBlock.getType() == Material.SIGN_POST || signBlock.getType() == Material.WALL_SIGN )) { // && ShieldBlock.getType() == Material.SPONGE){ Sign s = (Sign) signBlock.getState(); String shi = s.getLine(0); int maxpower = Integer.parseInt(s.getLine(2)); int pow = Integer.parseInt(s.getLine(3)); if (! (shi.equalsIgnoreCase("[shield]") || shi.equalsIgnoreCase("[f shield]"))) { return; } shieldBase.setShieldMaxPower(maxpower); ShieldBases = shieldstorage.GetShieldBases(); //log.info("[BubbleShield] : decreaseDurability() " + spongeLoc.toString()); boolean bShieldExists = shieldstorage.checkShieldExist(shieldBase, ShieldBases); if (!bShieldExists) { shieldBase.destroy(); TNTBreakShield(ShieldBlock); log.info("[BubbleShield] : Destroyed abandoned ShieldBase at " + shieldBase.getShieldBaseLocString()); return; } if (bShieldExists) { Integer representation = spongeLoc.getWorld().hashCode() + spongeLoc.getBlockX() * 2389 + spongeLoc.getBlockY() * 4027 + spongeLoc.getBlockZ() * 2053; pow--; shieldBase.shield.setShieldPower(pow); if (pow <= 0) { TNTBreakShield(ShieldBlock); return; } if (pow > 0){ String newpower = String.valueOf(pow); s.setLine(3, newpower); s.update(); shieldBase.shield.owner.sendMessage("Shield Power at " + newpower + "!"); if (ShieldDurability.containsKey(representation)) { int currentDurability = (int) ShieldDurability.get(representation); currentDurability++; if (checkIfMax(currentDurability)) { // counter has reached max durability //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max Shield Dura"); TNTBreakShield(ShieldBlock); ResetTime(representation, spongeLoc); return; } else { // counter has not reached max durability yet ShieldDurability.put(representation, currentDurability); //log.info("[BubbleShield] : onEntityExplode() " + "Set already, set Shield Dura"); startNewTimer(representation, shieldBase); } } else { ShieldDurability.put(representation, 1); //log.info("[BubbleShield] : onEntityExplode() " + "Set New Shield Dura"); shieldBase.setShieldMaxPower(pow); startNewTimer(representation, shieldBase); if (checkIfMax(1)) { TNTBreakShield(ShieldBlock); ResetTime(representation, spongeLoc); //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max"); return; } } } return; } } } /* ================================================================ * REGEN * * ================================================================ */ public void RegenPowerLoss(ShieldBase shieldBase) { if (shieldBase != null) { Sign sign = null; Location signlocation = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Location sponglocation = new Location(shieldBase.world, shieldBase.x, (shieldBase.y), shieldBase.z); try { sign = (Sign) signlocation.getBlock().getState(); } catch (java.lang.ClassCastException e) { return; } int max = Integer.parseInt(sign.getLine(2)); int currentpower = Integer.parseInt(sign.getLine(3)); if ( currentpower < max ) { String newpower = String.valueOf(currentpower+1); shieldBase.shield.setShieldPower(currentpower+1); sign.setLine(3, newpower); sign.update(); shieldBase.shield.owner.sendMessage("Shield Power at " + newpower + "!"); Integer representation = shieldBase.world.hashCode() + shieldBase.x * 2389 + shieldBase.y * 4027 + shieldBase.z * 2053; if (ShieldDurability.containsKey(representation)) { int currentDurability = (int) ShieldDurability.get(representation); currentDurability++; if (checkIfMax(currentDurability)) { // counter has reached max durability //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max Shield Dura"); ResetTime(representation, sponglocation); return; } else { // counter has not reached max durability yet ShieldDurability.put(representation, currentDurability); //log.info("[BubbleShield] : onEntityExplode() " + "Set already, set Shield Dura"); startNewTimer(representation, shieldBase); } } else { ShieldDurability.put(representation, 1); //log.info("[BubbleShield] : onEntityExplode() " + "Set New Shield Dura"); startNewTimer(representation, shieldBase); if (checkIfMax(1)) { ResetTime(representation, sponglocation); //log.info("[BubbleShield] : onEntityExplode() " + "Hit Max"); return; } } } } } /* ================================================================ * CREATE * * ================================================================ */ @EventHandler public void createShield(SignChangeEvent event) { Player player = event.getPlayer(); ShieldOwner shieldowner = null; ShieldType shieldType; String line0 = event.getLine(0); String line1 = event.getLine(1); if (line0.equalsIgnoreCase("[shield]")) { if (!player.hasPermission("bubbleshield.create.player") || !config.getUseWildShield()) { player.sendMessage("You do not have permission to create this shield."); return; } shieldType = ShieldType.Player; } else if (line0.equalsIgnoreCase("[f shield]") && line1 != null && !line1.equals("")) { if (!player.hasPermission("bubbleshield.create.faction") || !config.getUseFactionShield()) { player.sendMessage("You do not have permission to create this shield."); return; } shieldType = ShieldType.Faction; } else return; // not for us! if (!Util.isNumeric(line1) && shieldType == ShieldType.Faction) { player.sendMessage("Shield Power must be a number on the second line."); event.getBlock().breakNaturally(); return; } int shieldPower = 0; Block signBlock = event.getBlock(); Block shieldBlock = signBlock.getRelative(BlockFace.DOWN); if (shieldType == ShieldType.Player && ( shieldBlock.getType() == Material.IRON_BLOCK || shieldBlock.getType() == Material.GOLD_BLOCK || shieldBlock.getType() == Material.DIAMOND_BLOCK || shieldBlock.getType() == Material.EMERALD_BLOCK || shieldBlock.getType() == Material.SPONGE)) { shieldowner = new ShieldOwnerPlayer(player); shieldPower = Util.getShieldPowerFromBlock(shieldBlock, config); //Block block = (Block)shieldBlock; int shieldCount = Util.getShieldCount(shieldstorage, shieldowner.getOwner()); if (shieldstorage.getBlockShieldBase() != null){ if (shieldCount > config.getMaxWildShieldCount()){ shieldowner.sendMessage("You have the maximum amount of Shields."); shieldBlock.breakNaturally(); return; } } try { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); //shieldowner = new ShieldOwnerFaction(faction); if (!faction.getId().equals("0")) { shieldowner.sendMessage("You cannot create this shield here."); shieldBlock.breakNaturally(); Bukkit.getWorld(shieldBlock.getWorld().getName()).createExplosion(shieldBlock.getLocation(), 1); return; } } catch (Exception e) { log.info("[BubbleShield] : Create shield in Faction Null Error..."); } event.setLine(1, shieldowner.getOwner()); } else if (shieldType == ShieldType.Faction && shieldBlock.getType() == Material.SPONGE) { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); shieldowner = new ShieldOwnerFaction(faction); shieldPower = Integer.parseInt(line1); Block Sponge = (Block)shieldBlock; if (Sponge.getType() != Material.SPONGE) { player.sendMessage("You can only create Factions Shields with a sponge."); event.getBlock().breakNaturally(); return; } if (faction.getId().equals("-2") || faction.getId().equals("-1") || faction.getId().equals("0") ) { player.sendMessage("You can only create Shields in land you own."); event.getBlock().breakNaturally(); return; } if (shieldPower < 1) { player.sendMessage("Shield must have a power of greater than zero."); event.getBlock().breakNaturally(); return; } if (shieldPower > config.getMaxPowerCost() || shieldPower > faction.getPower()) { player.sendMessage("Not enough power to create Shield!"); signBlock.breakNaturally(); Sponge.breakNaturally(); return; } int shieldCount = Util.getShieldCount(shieldstorage, shieldowner.getOwner()); if (shieldstorage.getBlockShieldBase() != null){ if (shieldCount > config.getMaxFactionShieldCount()){ //log.info("[BubbleShield] : " + fshieldowner.getId() + " Has the maximum amount of Shields.!"); player.sendMessage("You have the maximum amount of Shields."); shieldBlock.breakNaturally(); return; } else if (shieldCount == 0) { faction.setPowerLoss(0); } } faction.addPowerLoss(-shieldPower); event.setLine(1, faction.getTag()); } else { player.sendMessage("Invalid Shield!"); signBlock.breakNaturally(); return; } event.setLine(2, Integer.toString(shieldPower)); event.setLine(3, Integer.toString(shieldPower)); Shield shield = Util.getShield(shieldowner, shieldstorage); shield.setShieldPower(shieldPower); shield.setMaxShieldPower(shieldPower); ShieldBase shieldbase = new ShieldBase(shieldBlock, signBlock, shield, shieldBlock.getWorld(),shieldBlock.getX(),shieldBlock.getY(),shieldBlock.getZ()); shieldbase.setType(shieldType); shieldbase.setShieldMaxPower(shieldPower); shieldstorage.addBlockShieldBase(signBlock, shieldbase); shieldstorage.addBlockShieldBase(shieldBlock, shieldbase); log.info("[BubbleShield] : " + "Shield created by "+ player.getName() + " At location: " + shieldbase.getShieldBaseLocString() + " For Faction/Player: " + shield.getShieldOwner().getOwner() + " With power of: " + shieldPower); shieldowner.sendMessage("Shield Created"); try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * DESTROY */ @EventHandler public void shieldBroken(BlockBreakEvent event) { Block block = event.getBlock(); ShieldBase shieldBase = shieldstorage.getBlockShieldBase().get(block); if (shieldBase != null) { Shield shield = shieldBase.shield; Player player = event.getPlayer(); Location signLoc = new Location(shieldBase.world, shieldBase.x, (shieldBase.y+1), shieldBase.z); Block signBlock = signLoc.getBlock(); Sign sign = (Sign) signBlock.getState(); int maxpower = Integer.parseInt(sign.getLine(2)); int pow = Integer.parseInt(sign.getLine(3)); if (shieldBase.getType() == ShieldType.Player && player != Bukkit.getPlayer(sign.getLine(1))) { player.sendMessage("Can not break shield unless you own it!"); event.setCancelled(true); return; } if (pow != maxpower) { player.sendMessage("Can not break shield unless it is fully charged!"); event.setCancelled(true); return; } shieldBase.destroy(); ShieldOwnerFaction fShieldOwner = new ShieldOwnerFaction(Board.getFactionAt(block)); shieldstorage.removeShields(fShieldOwner); shieldstorage.removeBlockShieldBase(shieldBase.sponge); shieldstorage.removeBlockShieldBase(shieldBase.sign); if (shieldBase.getType() == ShieldType.Faction) { Faction faction = Board.getFactionAt(event.getBlock().getLocation()); faction.addPowerLoss(maxpower); } shield.owner.sendMessage("Shield Destroyed!"); try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void TNTBreakShield(Block shieldblock) { ShieldBase shieldBase = shieldstorage.getBlockShieldBase().get(shieldblock); if (shieldBase != null) { Shield shield = shieldBase.shield; ShieldOwnerFaction fShieldOwner = new ShieldOwnerFaction(Board.getFactionAt(shieldblock)); Sign sign = (Sign) shieldBase.sign.getState(); shieldstorage.removeShields(fShieldOwner); shieldstorage.removeBlockShieldBase(shieldBase.sponge); shieldstorage.removeBlockShieldBase(shieldBase.sign); shieldBase.destroy(); String maxpower = sign.getLine(2); int explosionpower = Math.round(Integer.parseInt(maxpower) / 4); //log.info("Explosion Power: " + explosionpower + " MaxShield: " + shieldBase.shield.getShieldPowerMax()); if (explosionpower >= 11) explosionpower = 11; else if (explosionpower <= 2) explosionpower = 2; log.info("[BubbleShield] : " + "Shield exploded with Explosion Power of: " + explosionpower + " For Faction " + shieldBase.shield.getShieldOwner().getOwner()); shieldblock.getWorld().createExplosion(shieldblock.getLocation(), explosionpower, true); shield.owner.sendMessage("Shield Destroyed!"); shieldblock.breakNaturally(); if (shieldBase.getType() == ShieldType.Faction) { Faction faction = Board.getFactionAt(shieldblock); faction.addPowerLoss(Integer.parseInt(maxpower)); } try { config.SaveShieldsToFile(); config.LoadShieldFromFile(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* ========================================================================= * Shield Area Block Break * * */ @EventHandler public void shieldAreaBlockBreak(BlockBreakEvent event) { if (event == null || event.isCancelled()) { return; } if (!config.getUseShieldBuildProtection()) { return; } ShieldBases = shieldstorage.GetShieldBases(); Block block = event.getBlock(); for (ShieldBase shieldBase : ShieldBases) { if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) return; if (!event.getPlayer().getName().equals(shieldBase.shield.getShieldOwner().getOwner())) { if (blockProtected(block,shieldBase) ) { //log.info("[BubbleShield] : " + "Shield Block Attempt Break! " + shieldBase.getShieldBaseLocString()); if (!event.isCancelled()) event.setCancelled(true); return; } } } } @EventHandler public void shieldAreaBlockPlace(BlockPlaceEvent event) { if (event == null || event.isCancelled()) { return; } if (!config.getUseShieldBuildProtection()) { return; } ShieldBases = shieldstorage.GetShieldBases(); Block block = event.getBlock(); for (ShieldBase shieldBase : ShieldBases) { if (!shieldBase.equals(null) && shieldBase.getType() == ShieldType.Faction) return; if (!event.getPlayer().getName().equals(shieldBase.shield.getShieldOwner().getOwner()) ) { if (blockProtected(block,shieldBase) ) { //log.info("[BubbleShield] : " + "Shield Block Attempt Place! " + shieldBase.getShieldBaseLocString()); if (!event.isCancelled()) event.setCancelled(true); return; } } } } /* ========================================================================= * TIMERS * * */ private void startNewTimer(Integer representation, ShieldBase shieldbase) { if (shieldTimer.get(representation) != null) { shieldTimer.get(representation).cancel(); } Timer timer = new Timer(); timer.schedule(new ShieldTimer(plugin, representation, shieldbase), config.getRegenTime()); shieldTimer.put(representation, timer); } private boolean checkIfMax(int value) { return value == config.getMaxPowerCost(); } private void ResetTime(Integer representation, Location at) { ShieldDurability.remove(representation); if (shieldTimer.get(representation) != null) { shieldTimer.get(representation).cancel(); } shieldTimer.remove(representation); } /** * Returns the HashMap containing all saved durabilities. * * @return the HashMap containing all saved durabilities */ public HashMap<Integer, Integer> getShieldDurability() { return ShieldDurability; } /** * Sets the HashMap containing all saved durabilities. * * @param map * the HashMap containing all saved durabilities */ public void setShieldDurability(HashMap<Integer, Integer> map) { if (map == null) { return; } ShieldDurability = map; } /** * Returns the HashMap containing all saved durability timers. * * @return the HashMap containing all saved durability timers */ public HashMap<Integer, Timer> getObsidianTimer() { return shieldTimer; } /** * Sets the HashMap containing all saved durability timers. * * @param map * the HashMap containing all saved durability timers */ public void setShieldTimer(HashMap<Integer, Timer> map) { if (map == null) { return; } shieldTimer = map; } public HashMap<ShieldOwner, Shield> getShields() { return shieldstorage.getShields(); } public void setShields(HashMap<ShieldOwner, Shield> map) { if (map == null) { return; } shieldstorage.setShields(map); } public HashMap<Block, ShieldBase> getShieldsBase() { return shieldstorage.getBlockShieldBase(); } public void setShieldBase(HashMap<Block, ShieldBase> map) { if (map == null) { return; } shieldstorage.setBlockShieldBase(map); } }
diff --git a/archive-commons/src/test/java/org/archive/url/URLParserTest.java b/archive-commons/src/test/java/org/archive/url/URLParserTest.java index 63a0a45..b06da7a 100644 --- a/archive-commons/src/test/java/org/archive/url/URLParserTest.java +++ b/archive-commons/src/test/java/org/archive/url/URLParserTest.java @@ -1,52 +1,52 @@ package org.archive.url; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import org.apache.commons.httpclient.URIException; import com.google.common.net.InetAddresses; import junit.framework.TestCase; public class URLParserTest extends TestCase { public void testGuava() throws URIException, UnsupportedEncodingException { Long l = Long.parseLong("3279880203"); int i2 = l.intValue(); // int i = Integer.decode("3279880203"); System.err.format("FromNum(%s)\n", InetAddresses.fromInteger(i2).getHostAddress()); } public void testAddDefaultSchemeIfNeeded() { assertEquals(null,URLParser.addDefaultSchemeIfNeeded(null)); assertEquals("http://",URLParser.addDefaultSchemeIfNeeded("")); assertEquals("http://www.fool.com",URLParser.addDefaultSchemeIfNeeded("http://www.fool.com")); assertEquals("http://www.fool.com/",URLParser.addDefaultSchemeIfNeeded("http://www.fool.com/")); assertEquals("http://www.fool.com",URLParser.addDefaultSchemeIfNeeded("www.fool.com")); assertEquals("http://www.fool.com/",URLParser.addDefaultSchemeIfNeeded("www.fool.com/")); } public void testParse() throws URIException, UnsupportedEncodingException { System.out.format("O(%s) E(%s)\n","%66",URLDecoder.decode("%66","UTF-8")); dumpParse("http://www.archive.org/index.html#foo"); dumpParse("http://www.archive.org/"); dumpParse("http://www.archive.org"); dumpParse("http://www.archive.org?"); dumpParse("http://www.archive.org:8080/index.html?query#foo"); dumpParse("http://www.archive.org:8080/index.html?#foo"); dumpParse("http://www.archive.org:8080?#foo"); - dumpParse("http://b�cher.ch:8080?#foo"); + dumpParse("http://bŸcher.ch:8080?#foo"); - dumpParse("dns:b�cher.ch"); + dumpParse("dns:bŸcher.ch"); } private void dumpParse(String s) throws URIException { HandyURL h = URLParser.parse(s); System.out.format("Input:(%s)\nHandyURL\t%s\n",s,h.toDebugString()); } }
false
true
public void testParse() throws URIException, UnsupportedEncodingException { System.out.format("O(%s) E(%s)\n","%66",URLDecoder.decode("%66","UTF-8")); dumpParse("http://www.archive.org/index.html#foo"); dumpParse("http://www.archive.org/"); dumpParse("http://www.archive.org"); dumpParse("http://www.archive.org?"); dumpParse("http://www.archive.org:8080/index.html?query#foo"); dumpParse("http://www.archive.org:8080/index.html?#foo"); dumpParse("http://www.archive.org:8080?#foo"); dumpParse("http://b�cher.ch:8080?#foo"); dumpParse("dns:b�cher.ch"); }
public void testParse() throws URIException, UnsupportedEncodingException { System.out.format("O(%s) E(%s)\n","%66",URLDecoder.decode("%66","UTF-8")); dumpParse("http://www.archive.org/index.html#foo"); dumpParse("http://www.archive.org/"); dumpParse("http://www.archive.org"); dumpParse("http://www.archive.org?"); dumpParse("http://www.archive.org:8080/index.html?query#foo"); dumpParse("http://www.archive.org:8080/index.html?#foo"); dumpParse("http://www.archive.org:8080?#foo"); dumpParse("http://bŸcher.ch:8080?#foo"); dumpParse("dns:bŸcher.ch"); }
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ClassResolver.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ClassResolver.java index 161191c84..4e2ff8f67 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ClassResolver.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ClassResolver.java @@ -1,144 +1,156 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2004 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import java.util.Set; import java.util.Iterator; /** * Utility class to resolve a class name to an actual class. Note that loaded * classes are not initialized. * <p>Limitations: this does not handle inner classes very well.</p> * * @author Oliver Burn * @version 1.0 */ public class ClassResolver { /** name of the package to check if the class belongs to **/ private final String mPkg; /** set of imports to check against **/ private final Set mImports; /** use to load classes **/ private final ClassLoader mLoader; /** * Creates a new <code>ClassResolver</code> instance. * * @param aLoader the ClassLoader to load classes with. * @param aPkg the name of the package the class may belong to * @param aImports set of imports to check if the class belongs to */ public ClassResolver(ClassLoader aLoader, String aPkg, Set aImports) { mLoader = aLoader; mPkg = aPkg; mImports = aImports; } /** * Attempts to resolve the Class for a specified name. The algorithm is * to check: * - fully qualified name * - explicit imports * - enclosing package * - star imports * @param aName name of the class to resolve * @return the resolved class * @throws ClassNotFoundException if unable to resolve the class */ public Class resolve(String aName) throws ClassNotFoundException { // See if the class is full qualified if (isLoadable(aName)) { return safeLoad(aName); } // try matching explicit imports Iterator it = mImports.iterator(); while (it.hasNext()) { final String imp = (String) it.next(); - if (imp.endsWith(aName) && isLoadable(imp)) { - return safeLoad(imp); + if (imp.endsWith(aName)) { + if (isLoadable(imp)) { + return safeLoad(imp); + } + // perhaps this is a import for inner class + // let's try load it. + int dot = imp.lastIndexOf("."); + if (dot != -1) { + final String innerName = imp.substring(0, dot) + "$" + + imp.substring(dot + 1); + if (isLoadable(innerName)) { + return safeLoad(innerName); + } + } } } // See if in the package if (mPkg != null) { final String fqn = mPkg + "." + aName; if (isLoadable(fqn)) { return safeLoad(fqn); } } // try "java.lang." final String langClass = "java.lang." + aName; if (isLoadable(langClass)) { return safeLoad(langClass); } // try star imports it = mImports.iterator(); while (it.hasNext()) { final String imp = (String) it.next(); if (imp.endsWith(".*")) { final String fqn = imp.substring(0, imp.lastIndexOf('.') + 1) + aName; if (isLoadable(fqn)) { return safeLoad(fqn); } } } // Giving up, the type is unknown, so load the class to generate an // exception return safeLoad(aName); } /** * @return whether a specified class is loadable with safeLoad(). * @param aName name of the class to check */ public boolean isLoadable(String aName) { try { safeLoad(aName); return true; } catch (ClassNotFoundException e) { return false; } } /** * Will load a specified class is such a way that it will NOT be * initialised. * @param aName name of the class to load * @return the <code>Class</code> for the specified class * @throws ClassNotFoundException if an error occurs */ public Class safeLoad(String aName) throws ClassNotFoundException { // The next line will load the class using the specified class // loader. The magic is having the "false" parameter. This means the // class will not be initialised. Very, very important. return Class.forName(aName, false, mLoader); } }
true
true
public Class resolve(String aName) throws ClassNotFoundException { // See if the class is full qualified if (isLoadable(aName)) { return safeLoad(aName); } // try matching explicit imports Iterator it = mImports.iterator(); while (it.hasNext()) { final String imp = (String) it.next(); if (imp.endsWith(aName) && isLoadable(imp)) { return safeLoad(imp); } } // See if in the package if (mPkg != null) { final String fqn = mPkg + "." + aName; if (isLoadable(fqn)) { return safeLoad(fqn); } } // try "java.lang." final String langClass = "java.lang." + aName; if (isLoadable(langClass)) { return safeLoad(langClass); } // try star imports it = mImports.iterator(); while (it.hasNext()) { final String imp = (String) it.next(); if (imp.endsWith(".*")) { final String fqn = imp.substring(0, imp.lastIndexOf('.') + 1) + aName; if (isLoadable(fqn)) { return safeLoad(fqn); } } } // Giving up, the type is unknown, so load the class to generate an // exception return safeLoad(aName); }
public Class resolve(String aName) throws ClassNotFoundException { // See if the class is full qualified if (isLoadable(aName)) { return safeLoad(aName); } // try matching explicit imports Iterator it = mImports.iterator(); while (it.hasNext()) { final String imp = (String) it.next(); if (imp.endsWith(aName)) { if (isLoadable(imp)) { return safeLoad(imp); } // perhaps this is a import for inner class // let's try load it. int dot = imp.lastIndexOf("."); if (dot != -1) { final String innerName = imp.substring(0, dot) + "$" + imp.substring(dot + 1); if (isLoadable(innerName)) { return safeLoad(innerName); } } } } // See if in the package if (mPkg != null) { final String fqn = mPkg + "." + aName; if (isLoadable(fqn)) { return safeLoad(fqn); } } // try "java.lang." final String langClass = "java.lang." + aName; if (isLoadable(langClass)) { return safeLoad(langClass); } // try star imports it = mImports.iterator(); while (it.hasNext()) { final String imp = (String) it.next(); if (imp.endsWith(".*")) { final String fqn = imp.substring(0, imp.lastIndexOf('.') + 1) + aName; if (isLoadable(fqn)) { return safeLoad(fqn); } } } // Giving up, the type is unknown, so load the class to generate an // exception return safeLoad(aName); }
diff --git a/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java b/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java index 9e0d66b..55249d9 100644 --- a/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java +++ b/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java @@ -1,165 +1,165 @@ package rhogenwizard.debugger; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public class DebugProtocol { private DebugServer debugServer; private IDebugCallback debugCallback; private DebugState state; private String filePosition = ""; private int linePosition = 0; private String classPosition = ""; private String methodPosition = ""; public DebugProtocol (DebugServer server, IDebugCallback callback) { this.debugServer = server; this.debugCallback = callback; this.state = DebugState.NOTCONNECTED; } public DebugState getState() { return this.state; } public String getCurrentFile() { return this.filePosition; } public int getCurrentLine() { return this.linePosition; } public String getCurrentClass() { return this.classPosition; } public String getCurrentMethod() { return this.methodPosition; } protected void processCommand(String cmd) { boolean bp; if(cmd.endsWith("\n")) cmd = cmd.substring(0, cmd.length()-1); if (cmd.compareTo("CONNECT")==0) { this.state = DebugState.CONNECTED; debugServer.send("CONNECTED"); debugCallback.connected(); } else if (cmd.compareTo("RESUMED")==0) { this.state = DebugState.RUNNING; debugCallback.resumed(); } else if (cmd.compareTo("QUIT")==0) { this.state = DebugState.EXITED; debugCallback.exited(); } else if ((bp=cmd.startsWith("BP:")) || cmd.startsWith("STEP:")) { this.state = bp ? DebugState.BREAKPOINT : DebugState.STEP; String[] brp = cmd.split(":"); this.filePosition = brp[1].replace('|', ':').replace('\\', '/'); this.linePosition = Integer.parseInt(brp[2]); - this.classPosition = brp[3].replace('#', ':'); - this.methodPosition = brp[4]; + this.classPosition = brp.length > 3 ? brp[3].replace('#', ':') : ""; + this.methodPosition = brp.length > 4 ? brp[4] : ""; if (bp) debugCallback.breakpoint(this.filePosition, this.linePosition, this.classPosition, this.methodPosition); else debugCallback.step(this.filePosition, this.linePosition, this.classPosition, this.methodPosition); } else if (cmd.startsWith("EVL:")) { boolean valid = cmd.charAt(4)=='0'; String var = cmd.substring(6); String val = ""; int val_idx = var.indexOf(':'); if (val_idx>=0) { val = var.substring(val_idx+1); // .replace("\\n", "\n"); try { var = URLDecoder.decode(var.substring(0,val_idx), "UTF-8"); } catch (UnsupportedEncodingException e) { var = var.substring(0,val_idx); } } debugCallback.evaluation(valid, var, val); } else if (cmd.startsWith("V:")) { DebugVariableType vt = DebugVariableType.variableTypeById(cmd.charAt(2)); String var = cmd.substring(4); String val = ""; int val_idx = var.indexOf(':'); if (val_idx>=0) { val = var.substring(val_idx+1); // .replace("\\n", "\n"); var = var.substring(0,val_idx); } debugCallback.watch(vt, var, val); } else if (cmd.startsWith("VSTART:")) { debugCallback.watchBOL(DebugVariableType.variableTypeById(cmd.charAt(7))); } else if (cmd.startsWith("VEND:")) { debugCallback.watchEOL(DebugVariableType.variableTypeById(cmd.charAt(5))); } else { debugCallback.unknown(cmd); } } public void stepOver() { this.state = DebugState.RUNNING; debugServer.send("STEPOVER"); } public void stepInto() { this.state = DebugState.RUNNING; debugServer.send("STEPINTO"); } public void stepReturn() { this.state = DebugState.RUNNING; debugServer.send("STEPRET"); } public void resume() { this.state = DebugState.RUNNING; debugServer.send("CONT"); } public void addBreakpoint(String file, int line) { debugServer.send("BP:"+file+":"+line); } public void removeBreakpoint(String file, int line) { debugServer.send("RM:"+file+":"+line); } public void removeAllBreakpoints() { debugServer.send("RMALL"); } public void skipBreakpoints(boolean skip) { debugServer.send(skip?"DISABLE":"ENABLE"); } public void evaluate(String expression) { try { expression = URLEncoder.encode(expression, "UTF-8"); } catch (UnsupportedEncodingException e) {} debugServer.send("EVL:"+expression); } public void getVariables(DebugVariableType[] types) { for (DebugVariableType t: types) { switch (t) { case GLOBAL: debugServer.send("GVARS"); break; case CLASS: debugServer.send("CVARS"); break; case INSTANCE: debugServer.send("IVARS"); break; default: debugServer.send("LVARS"); } } } public void suspend() { debugServer.send("SUSP"); } public void terminate() { debugServer.send("KILL"); } }
true
true
protected void processCommand(String cmd) { boolean bp; if(cmd.endsWith("\n")) cmd = cmd.substring(0, cmd.length()-1); if (cmd.compareTo("CONNECT")==0) { this.state = DebugState.CONNECTED; debugServer.send("CONNECTED"); debugCallback.connected(); } else if (cmd.compareTo("RESUMED")==0) { this.state = DebugState.RUNNING; debugCallback.resumed(); } else if (cmd.compareTo("QUIT")==0) { this.state = DebugState.EXITED; debugCallback.exited(); } else if ((bp=cmd.startsWith("BP:")) || cmd.startsWith("STEP:")) { this.state = bp ? DebugState.BREAKPOINT : DebugState.STEP; String[] brp = cmd.split(":"); this.filePosition = brp[1].replace('|', ':').replace('\\', '/'); this.linePosition = Integer.parseInt(brp[2]); this.classPosition = brp[3].replace('#', ':'); this.methodPosition = brp[4]; if (bp) debugCallback.breakpoint(this.filePosition, this.linePosition, this.classPosition, this.methodPosition); else debugCallback.step(this.filePosition, this.linePosition, this.classPosition, this.methodPosition); } else if (cmd.startsWith("EVL:")) { boolean valid = cmd.charAt(4)=='0'; String var = cmd.substring(6); String val = ""; int val_idx = var.indexOf(':'); if (val_idx>=0) { val = var.substring(val_idx+1); // .replace("\\n", "\n"); try { var = URLDecoder.decode(var.substring(0,val_idx), "UTF-8"); } catch (UnsupportedEncodingException e) { var = var.substring(0,val_idx); } } debugCallback.evaluation(valid, var, val); } else if (cmd.startsWith("V:")) { DebugVariableType vt = DebugVariableType.variableTypeById(cmd.charAt(2)); String var = cmd.substring(4); String val = ""; int val_idx = var.indexOf(':'); if (val_idx>=0) { val = var.substring(val_idx+1); // .replace("\\n", "\n"); var = var.substring(0,val_idx); } debugCallback.watch(vt, var, val); } else if (cmd.startsWith("VSTART:")) { debugCallback.watchBOL(DebugVariableType.variableTypeById(cmd.charAt(7))); } else if (cmd.startsWith("VEND:")) { debugCallback.watchEOL(DebugVariableType.variableTypeById(cmd.charAt(5))); } else { debugCallback.unknown(cmd); } }
protected void processCommand(String cmd) { boolean bp; if(cmd.endsWith("\n")) cmd = cmd.substring(0, cmd.length()-1); if (cmd.compareTo("CONNECT")==0) { this.state = DebugState.CONNECTED; debugServer.send("CONNECTED"); debugCallback.connected(); } else if (cmd.compareTo("RESUMED")==0) { this.state = DebugState.RUNNING; debugCallback.resumed(); } else if (cmd.compareTo("QUIT")==0) { this.state = DebugState.EXITED; debugCallback.exited(); } else if ((bp=cmd.startsWith("BP:")) || cmd.startsWith("STEP:")) { this.state = bp ? DebugState.BREAKPOINT : DebugState.STEP; String[] brp = cmd.split(":"); this.filePosition = brp[1].replace('|', ':').replace('\\', '/'); this.linePosition = Integer.parseInt(brp[2]); this.classPosition = brp.length > 3 ? brp[3].replace('#', ':') : ""; this.methodPosition = brp.length > 4 ? brp[4] : ""; if (bp) debugCallback.breakpoint(this.filePosition, this.linePosition, this.classPosition, this.methodPosition); else debugCallback.step(this.filePosition, this.linePosition, this.classPosition, this.methodPosition); } else if (cmd.startsWith("EVL:")) { boolean valid = cmd.charAt(4)=='0'; String var = cmd.substring(6); String val = ""; int val_idx = var.indexOf(':'); if (val_idx>=0) { val = var.substring(val_idx+1); // .replace("\\n", "\n"); try { var = URLDecoder.decode(var.substring(0,val_idx), "UTF-8"); } catch (UnsupportedEncodingException e) { var = var.substring(0,val_idx); } } debugCallback.evaluation(valid, var, val); } else if (cmd.startsWith("V:")) { DebugVariableType vt = DebugVariableType.variableTypeById(cmd.charAt(2)); String var = cmd.substring(4); String val = ""; int val_idx = var.indexOf(':'); if (val_idx>=0) { val = var.substring(val_idx+1); // .replace("\\n", "\n"); var = var.substring(0,val_idx); } debugCallback.watch(vt, var, val); } else if (cmd.startsWith("VSTART:")) { debugCallback.watchBOL(DebugVariableType.variableTypeById(cmd.charAt(7))); } else if (cmd.startsWith("VEND:")) { debugCallback.watchEOL(DebugVariableType.variableTypeById(cmd.charAt(5))); } else { debugCallback.unknown(cmd); } }
diff --git a/twitter4j-core/src/main/java/twitter4j/internal/http/HttpClientImpl.java b/twitter4j-core/src/main/java/twitter4j/internal/http/HttpClientImpl.java index ab3ef497..b6d52903 100644 --- a/twitter4j-core/src/main/java/twitter4j/internal/http/HttpClientImpl.java +++ b/twitter4j-core/src/main/java/twitter4j/internal/http/HttpClientImpl.java @@ -1,460 +1,460 @@ /* Copyright (c) 2007-2010, Yusuke Yamamoto 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 Yusuke Yamamoto 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 Yusuke Yamamoto ``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 Yusuke Yamamoto 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 twitter4j.internal.http; import twitter4j.TwitterException; import twitter4j.conf.ConfigurationContext; import twitter4j.internal.logging.Logger; import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.URL; import java.net.URLEncoder; import java.security.AccessControlException; import java.util.HashMap; import java.util.List; import java.util.Map; import static twitter4j.internal.http.RequestMethod.POST; /** * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.1.2 */ public class HttpClientImpl implements HttpClient, HttpResponseCode, java.io.Serializable { private static final Logger logger = Logger.getLogger(HttpClientImpl.class); private String proxyHost = null; private int proxyPort = -1; private String proxyAuthUser = null; private String proxyAuthPassword = null; private int connectionTimeout = 20000; private int readTimeout = 120000; private int retryCount = 0; private int retryIntervalSeconds = 5 * 1000; private static boolean isJDK14orEarlier = false; private static final long serialVersionUID = -8819171414069621503L; static { try { String versionStr = System.getProperty("java.specification.version"); if (null != versionStr) { isJDK14orEarlier = 1.5d > Double.parseDouble(versionStr); } if (ConfigurationContext.getInstance().isDalvik()) { // quick and dirty workaround for TFJ-296 // it must be an Android/Dalvik/Harmony side issue!!!! System.setProperty("http.keepAlive", "false"); } } catch (AccessControlException ace) { isJDK14orEarlier = true; } } public HttpClientImpl() { } public HttpClientImpl(HttpClientConfiguration conf) { setProxyHost(conf.getHttpProxyHost()); setProxyPort(conf.getHttpProxyPort()); setProxyAuthUser(conf.getHttpProxyUser()); setProxyAuthPassword(conf.getHttpProxyPassword()); setConnectionTimeout(conf.getHttpConnectionTimeout()); setReadTimeout(conf.getHttpReadTimeout()); setRetryCount(conf.getHttpRetryCount()); setRetryIntervalSeconds(conf.getHttpRetryIntervalSeconds()); } public void shutdown() { } private static final Map<HttpClientConfiguration, HttpClient> instanceMap = new HashMap<HttpClientConfiguration, HttpClient>(1); public static HttpClient getInstance(HttpClientConfiguration conf) { HttpClient client = instanceMap.get(conf); if (null == client) { client = new HttpClientImpl(conf); instanceMap.put(conf, client); } return client; } public String getProxyHost() { return proxyHost; } /** * Sets proxy host. * * @param proxyHost */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public int getProxyPort() { return proxyPort; } /** * Sets proxy port. * * @param proxyPort */ public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } public String getProxyAuthUser() { return proxyAuthUser; } /** * Sets proxy authentication user. * System property -Dtwitter4j.http.proxyUser overrides this attribute. * * @param proxyAuthUser */ public void setProxyAuthUser(String proxyAuthUser) { this.proxyAuthUser = proxyAuthUser; } public String getProxyAuthPassword() { return proxyAuthPassword; } /** * Sets proxy authentication password. * System property -Dtwitter4j.http.proxyPassword overrides this attribute. * * @param proxyAuthPassword */ public void setProxyAuthPassword(String proxyAuthPassword) { this.proxyAuthPassword = proxyAuthPassword; } public int getConnectionTimeout() { return connectionTimeout; } /** * Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. * * @param connectionTimeout - an int that specifies the connect timeout value in milliseconds */ public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getReadTimeout() { return readTimeout; } /** * Sets the read timeout to a specified timeout, in milliseconds. * * @param readTimeout - an int that specifies the timeout value to be used in milliseconds */ public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public void setRetryCount(int retryCount) { if (retryCount >= 0) { this.retryCount = retryCount; } else { throw new IllegalArgumentException("RetryCount cannot be negative."); } } public void setRetryIntervalSeconds(int retryIntervalSeconds) { if (retryIntervalSeconds >= 0) { this.retryIntervalSeconds = retryIntervalSeconds; } else { throw new IllegalArgumentException( "RetryInterval cannot be negative."); } } public HttpResponse get(String url) throws TwitterException { return request(new HttpRequest(RequestMethod.GET, url, null, null, null)); } public HttpResponse post(String url, HttpParameter[] params) throws TwitterException { return request(new HttpRequest(RequestMethod.POST, url, params, null, null)); } public HttpResponse request(HttpRequest req) throws TwitterException { int retriedCount; int retry = retryCount + 1; HttpResponse res = null; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; OutputStream os = null; try { con = getConnection(req.getURL()); con.setDoInput(true); setHeaders(req, con); con.setRequestMethod(req.getMethod().name()); if (req.getMethod() == POST) { if (HttpParameter.containsFile(req.getParameters())) { String boundary = "----Twitter4J-upload" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; con.setDoOutput(true); os = con.getOutputStream(); DataOutputStream out = new DataOutputStream(os); for (HttpParameter param : req.getParameters()) { if (param.isFile()) { write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"; filename=\"" + param.getFile().getName() + "\"\r\n"); write(out, "Content-Type: " + param.getContentType() + "\r\n\r\n"); BufferedInputStream in = new BufferedInputStream( param.hasFileBody() ? param.getFileBody() :new FileInputStream(param.getFile()) ); int buff = 0; while ((buff = in.read()) != -1) { out.write(buff); } write(out, "\r\n"); in.close(); } else { write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"\r\n"); write(out, "Content-Type: text/plain; charset=UTF-8\r\n\r\n"); logger.debug(param.getValue()); // out.write(encode(param.getValue()).getBytes("UTF-8")); out.write(param.getValue().getBytes("UTF-8")); write(out, "\r\n"); } } write(out, boundary + "--\r\n"); write(out, "\r\n"); } else { con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String postParam = HttpParameter.encodeParameters(req.getParameters()); logger.debug("Post Params: ", postParam); byte[] bytes = postParam.getBytes("UTF-8"); con.setRequestProperty("Content-Length", Integer.toString(bytes.length)); con.setDoOutput(true); os = con.getOutputStream(); os.write(bytes); } os.flush(); os.close(); } res = new HttpResponseImpl(con); responseCode = con.getResponseCode(); if (logger.isDebugEnabled()) { logger.debug("Response: "); Map<String, List<String>> responseHeaders = con.getHeaderFields(); for (String key : responseHeaders.keySet()) { List<String> values = responseHeaders.get(key); for (String value : values) { if (null != key) { logger.debug(key + ": " + value); } else { logger.debug(value); } } } } - if (responseCode < OK && MULTIPLE_CHOICES <= responseCode) { + if (responseCode < OK || MULTIPLE_CHOICES <= responseCode) { if (responseCode == ENHANCE_YOUR_CLAIM || responseCode == SERVICE_UNAVAILABLE || responseCode == BAD_REQUEST || responseCode < INTERNAL_SERVER_ERROR || retriedCount == retryCount) { throw new TwitterException(res.asString(), res); } // will retry if the status code is INTERNAL_SERVER_ERROR } else { break; } } finally { try { os.close(); } catch (Exception ignore) { } } } catch (IOException ioe) { // connection timeout or read timeout if (retriedCount == retryCount) { throw new TwitterException(ioe.getMessage(), ioe, responseCode); } } try { if (logger.isDebugEnabled() && null != res) { res.asString(); } logger.debug("Sleeping " + retryIntervalSeconds + " seconds until the next retry."); Thread.sleep(retryIntervalSeconds * 1000); } catch (InterruptedException ignore) { //nothing to do } } return res; } private void write(DataOutputStream out, String outStr) throws IOException { out.writeBytes(outStr); logger.debug(outStr); } public static String encode(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (java.io.UnsupportedEncodingException neverHappen) { throw new AssertionError("will never happen"); } } /** * sets HTTP headers * @param req The request * @param connection HttpURLConnection */ private void setHeaders(HttpRequest req, HttpURLConnection connection) { logger.debug("Request: "); logger.debug(req.getMethod().name() + " ", req.getURL()); String authorizationHeader; if (null != req.getAuthorization() && null != (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req))) { logger.debug("Authorization: ", authorizationHeader); connection.addRequestProperty("Authorization", authorizationHeader); } if (null != req.getRequestHeaders()) { for (String key : req.getRequestHeaders().keySet()) { connection.addRequestProperty(key, req.getRequestHeaders().get(key)); logger.debug(key + ": " + req.getRequestHeaders().get(key)); } } } private HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection con = null; if (proxyHost != null && !proxyHost.equals("")) { if (proxyAuthUser != null && !proxyAuthUser.equals("")) { logger.debug("Proxy AuthUser: " + proxyAuthUser); logger.debug("Proxy AuthPassword: " + proxyAuthPassword); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { //respond only to proxy auth requests if (getRequestorType().equals(RequestorType.PROXY)) { return new PasswordAuthentication(proxyAuthUser, proxyAuthPassword .toCharArray()); } else { return null; } } }); } final Proxy proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress .createUnresolved(proxyHost, proxyPort)); if (logger.isDebugEnabled()) { logger.debug("Opening proxied connection(" + proxyHost + ":" + proxyPort + ")"); } con = (HttpURLConnection) new URL(url).openConnection(proxy); } else { con = (HttpURLConnection) new URL(url).openConnection(); } if (connectionTimeout > 0 && !isJDK14orEarlier) { con.setConnectTimeout(connectionTimeout); } if (readTimeout > 0 && !isJDK14orEarlier) { con.setReadTimeout(readTimeout); } return con; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof HttpClientImpl)) return false; HttpClientImpl that = (HttpClientImpl) o; if (connectionTimeout != that.connectionTimeout) return false; if (proxyPort != that.proxyPort) return false; if (readTimeout != that.readTimeout) return false; if (retryCount != that.retryCount) return false; if (retryIntervalSeconds != that.retryIntervalSeconds) return false; if (proxyAuthPassword != null ? !proxyAuthPassword.equals(that.proxyAuthPassword) : that.proxyAuthPassword != null) return false; if (proxyAuthUser != null ? !proxyAuthUser.equals(that.proxyAuthUser) : that.proxyAuthUser != null) return false; if (proxyHost != null ? !proxyHost.equals(that.proxyHost) : that.proxyHost != null) return false; return true; } @Override public int hashCode() { int result = proxyHost != null ? proxyHost.hashCode() : 0; result = 31 * result + proxyPort; result = 31 * result + (proxyAuthUser != null ? proxyAuthUser.hashCode() : 0); result = 31 * result + (proxyAuthPassword != null ? proxyAuthPassword.hashCode() : 0); result = 31 * result + connectionTimeout; result = 31 * result + readTimeout; result = 31 * result + retryCount; result = 31 * result + retryIntervalSeconds; return result; } @Override public String toString() { return "HttpClientImpl{" + "proxyHost='" + proxyHost + '\'' + ", proxyPort=" + proxyPort + ", proxyAuthUser='" + proxyAuthUser + '\'' + ", proxyAuthPassword='" + proxyAuthPassword + '\'' + ", connectionTimeout=" + connectionTimeout + ", readTimeout=" + readTimeout + ", retryCount=" + retryCount + ", retryIntervalSeconds=" + retryIntervalSeconds + '}'; } }
true
true
public HttpResponse request(HttpRequest req) throws TwitterException { int retriedCount; int retry = retryCount + 1; HttpResponse res = null; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; OutputStream os = null; try { con = getConnection(req.getURL()); con.setDoInput(true); setHeaders(req, con); con.setRequestMethod(req.getMethod().name()); if (req.getMethod() == POST) { if (HttpParameter.containsFile(req.getParameters())) { String boundary = "----Twitter4J-upload" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; con.setDoOutput(true); os = con.getOutputStream(); DataOutputStream out = new DataOutputStream(os); for (HttpParameter param : req.getParameters()) { if (param.isFile()) { write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"; filename=\"" + param.getFile().getName() + "\"\r\n"); write(out, "Content-Type: " + param.getContentType() + "\r\n\r\n"); BufferedInputStream in = new BufferedInputStream( param.hasFileBody() ? param.getFileBody() :new FileInputStream(param.getFile()) ); int buff = 0; while ((buff = in.read()) != -1) { out.write(buff); } write(out, "\r\n"); in.close(); } else { write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"\r\n"); write(out, "Content-Type: text/plain; charset=UTF-8\r\n\r\n"); logger.debug(param.getValue()); // out.write(encode(param.getValue()).getBytes("UTF-8")); out.write(param.getValue().getBytes("UTF-8")); write(out, "\r\n"); } } write(out, boundary + "--\r\n"); write(out, "\r\n"); } else { con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String postParam = HttpParameter.encodeParameters(req.getParameters()); logger.debug("Post Params: ", postParam); byte[] bytes = postParam.getBytes("UTF-8"); con.setRequestProperty("Content-Length", Integer.toString(bytes.length)); con.setDoOutput(true); os = con.getOutputStream(); os.write(bytes); } os.flush(); os.close(); } res = new HttpResponseImpl(con); responseCode = con.getResponseCode(); if (logger.isDebugEnabled()) { logger.debug("Response: "); Map<String, List<String>> responseHeaders = con.getHeaderFields(); for (String key : responseHeaders.keySet()) { List<String> values = responseHeaders.get(key); for (String value : values) { if (null != key) { logger.debug(key + ": " + value); } else { logger.debug(value); } } } } if (responseCode < OK && MULTIPLE_CHOICES <= responseCode) { if (responseCode == ENHANCE_YOUR_CLAIM || responseCode == SERVICE_UNAVAILABLE || responseCode == BAD_REQUEST || responseCode < INTERNAL_SERVER_ERROR || retriedCount == retryCount) { throw new TwitterException(res.asString(), res); } // will retry if the status code is INTERNAL_SERVER_ERROR } else { break; } } finally { try { os.close(); } catch (Exception ignore) { } } } catch (IOException ioe) { // connection timeout or read timeout if (retriedCount == retryCount) { throw new TwitterException(ioe.getMessage(), ioe, responseCode); } } try { if (logger.isDebugEnabled() && null != res) { res.asString(); } logger.debug("Sleeping " + retryIntervalSeconds + " seconds until the next retry."); Thread.sleep(retryIntervalSeconds * 1000); } catch (InterruptedException ignore) { //nothing to do } } return res; }
public HttpResponse request(HttpRequest req) throws TwitterException { int retriedCount; int retry = retryCount + 1; HttpResponse res = null; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; OutputStream os = null; try { con = getConnection(req.getURL()); con.setDoInput(true); setHeaders(req, con); con.setRequestMethod(req.getMethod().name()); if (req.getMethod() == POST) { if (HttpParameter.containsFile(req.getParameters())) { String boundary = "----Twitter4J-upload" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; con.setDoOutput(true); os = con.getOutputStream(); DataOutputStream out = new DataOutputStream(os); for (HttpParameter param : req.getParameters()) { if (param.isFile()) { write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"; filename=\"" + param.getFile().getName() + "\"\r\n"); write(out, "Content-Type: " + param.getContentType() + "\r\n\r\n"); BufferedInputStream in = new BufferedInputStream( param.hasFileBody() ? param.getFileBody() :new FileInputStream(param.getFile()) ); int buff = 0; while ((buff = in.read()) != -1) { out.write(buff); } write(out, "\r\n"); in.close(); } else { write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"\r\n"); write(out, "Content-Type: text/plain; charset=UTF-8\r\n\r\n"); logger.debug(param.getValue()); // out.write(encode(param.getValue()).getBytes("UTF-8")); out.write(param.getValue().getBytes("UTF-8")); write(out, "\r\n"); } } write(out, boundary + "--\r\n"); write(out, "\r\n"); } else { con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String postParam = HttpParameter.encodeParameters(req.getParameters()); logger.debug("Post Params: ", postParam); byte[] bytes = postParam.getBytes("UTF-8"); con.setRequestProperty("Content-Length", Integer.toString(bytes.length)); con.setDoOutput(true); os = con.getOutputStream(); os.write(bytes); } os.flush(); os.close(); } res = new HttpResponseImpl(con); responseCode = con.getResponseCode(); if (logger.isDebugEnabled()) { logger.debug("Response: "); Map<String, List<String>> responseHeaders = con.getHeaderFields(); for (String key : responseHeaders.keySet()) { List<String> values = responseHeaders.get(key); for (String value : values) { if (null != key) { logger.debug(key + ": " + value); } else { logger.debug(value); } } } } if (responseCode < OK || MULTIPLE_CHOICES <= responseCode) { if (responseCode == ENHANCE_YOUR_CLAIM || responseCode == SERVICE_UNAVAILABLE || responseCode == BAD_REQUEST || responseCode < INTERNAL_SERVER_ERROR || retriedCount == retryCount) { throw new TwitterException(res.asString(), res); } // will retry if the status code is INTERNAL_SERVER_ERROR } else { break; } } finally { try { os.close(); } catch (Exception ignore) { } } } catch (IOException ioe) { // connection timeout or read timeout if (retriedCount == retryCount) { throw new TwitterException(ioe.getMessage(), ioe, responseCode); } } try { if (logger.isDebugEnabled() && null != res) { res.asString(); } logger.debug("Sleeping " + retryIntervalSeconds + " seconds until the next retry."); Thread.sleep(retryIntervalSeconds * 1000); } catch (InterruptedException ignore) { //nothing to do } } return res; }
diff --git a/src/java/nextgen/core/readers/PairedEndReader.java b/src/java/nextgen/core/readers/PairedEndReader.java index 21b062f..94075e4 100644 --- a/src/java/nextgen/core/readers/PairedEndReader.java +++ b/src/java/nextgen/core/readers/PairedEndReader.java @@ -1,417 +1,420 @@ package nextgen.core.readers; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Logger; import org.broad.igv.Globals; import broad.core.util.CLUtil; import broad.core.util.CLUtil.ArgumentMap; import net.sf.picard.util.Log; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import net.sf.samtools.SAMRecordIterator; import net.sf.samtools.SAMSequenceRecord; import net.sf.samtools.util.CloseableIterator; import nextgen.core.alignment.Alignment; import nextgen.core.alignment.ChromosomeInconsistencyException; import nextgen.core.alignment.FragmentAlignment; import nextgen.core.alignment.AbstractPairedEndAlignment.TranscriptionRead; import nextgen.core.alignment.PairedEndAlignmentFactory; import nextgen.core.alignment.PairedReadAlignment; import nextgen.core.alignment.SingleEndAlignment; import nextgen.core.annotation.Annotation; import nextgen.core.writers.PairedEndWriter; //Reads the new PairedEnd BAM files into a queryable object public class PairedEndReader { private static final Log log = Log.getInstance(PairedEndReader.class); public static enum AlignmentType { PAIRED_END, SINGLE_END }; private boolean warned = false; private CloseableIterator<Alignment> mCurrentIterator = null; private SAMFileReader reader; private SAMFileHeader header; private AlignmentType alignmentType; private TranscriptionRead strand; private boolean fragment=true; public PairedEndReader(File bam){ //We are going to read the .pebam files with special attribute flags and create a new "Alignment" object this(bam,TranscriptionRead.UNSTRANDED); } public PairedEndReader(File bam,TranscriptionRead read){ //We are going to read the .pebam files with special attribute flags and create a new "Alignment" object this(bam,read,true); } public PairedEndReader(File bam,TranscriptionRead read,boolean fra){ //We are going to read the .pebam files with special attribute flags and create a new "Alignment" object this.reader=new SAMFileReader(bam); this.header=reader.getFileHeader(); alignmentType = getAlignmentType(this.header); strand = read; setFragmentFlag(fra); } private static AlignmentType getAlignmentType(SAMFileHeader header) { //check if it is paired end with our modified record Object isPairedEndFormat=header.getAttribute(PairedEndWriter.mateLineFlag); return (isPairedEndFormat != null) ? AlignmentType.PAIRED_END : AlignmentType.SINGLE_END; } public AlignmentType getAlignmentType() { return getAlignmentType(this.header); } public void setFragmentFlag(boolean fra){ fragment = fra; } public void close() throws IOException { mCurrentIterator.close(); reader.close(); } public SAMFileHeader getHeader() { if (header == null) { loadHeader(); } return header; } private void loadHeader() { header = reader.getFileHeader(); } public Set<String> getSequenceNames() { SAMFileHeader header = getHeader(); if (header == null) { return null; } Set<String> seqNames = new HashSet<String>(); List<SAMSequenceRecord> records = header.getSequenceDictionary().getSequences(); if (records.size() > 0) { for (SAMSequenceRecord rec : header.getSequenceDictionary().getSequences()) { String chr = rec.getSequenceName(); seqNames.add(chr); } } return seqNames; } public boolean hasIndex() { return reader.hasIndex(); } public CloseableIterator<Alignment> iterator() { if (mCurrentIterator != null) { throw new IllegalStateException("Iteration in progress"); } mCurrentIterator = new PairedEndIterator(); return mCurrentIterator; } public CloseableIterator<Alignment> query(Annotation a, boolean contained) { SAMRecordIterator query = null; query = reader.query(a.getReferenceName(), a.getSAMStart(), a.getSAMEnd(), contained); mCurrentIterator = new PairedEndIterator(query); return mCurrentIterator; } private class PairedEndIterator implements CloseableIterator<Alignment> { private Alignment mNextRecord = null; private boolean isClosed = false; private CloseableIterator<SAMRecord> itr; public PairedEndIterator() { this(reader.iterator()); } public PairedEndIterator(CloseableIterator<SAMRecord> itr) { this.itr = itr; advance(); } public void close() { if (!isClosed) { if (mCurrentIterator == null) { throw new IllegalStateException("Attempt to close non-current iterator"); } itr.close(); mCurrentIterator = null; isClosed = true; } } public void remove() { throw new UnsupportedOperationException("Not supported: remove"); } public boolean hasNext() { if (isClosed) throw new IllegalStateException("Iterator has been closed"); return (mNextRecord != null); } public Alignment next() { if (isClosed) throw new IllegalStateException("Iterator has been closed"); final Alignment result = mNextRecord; advance(); return result; } private void advance() { if (!itr.hasNext()) mNextRecord = null; // VERY IMPORTANT. Otherwise infinite loop while (itr.hasNext()) { SAMRecord r = itr.next(); mNextRecord = samRecordToAlignment(r,strand,fragment); if (mNextRecord != null) {break;} else {log.debug("samRecordToAlignment returned null for this record" + r.getSAMString() );} } } /** * @return The record that will be return by the next call to next() */ protected Alignment peek() { return mNextRecord; } } /** * Parse the record * Either it is our modified record with the mate information or a standard single end read * @param record SamRecord * @return Alignment * @throws ChromosomeInconsistencyException */ private Alignment samRecordToAlignment(SAMRecord record,TranscriptionRead transcriptionRead,boolean fragment) { Alignment rtrn; try { if (alignmentType == AlignmentType.PAIRED_END) { if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { //revised to read single end data @zhuxp String name=record.getReadName(); int mateStart=record.getMateAlignmentStart(); String mateCigar=record.getAttribute(PairedEndWriter.mateCigarFlag).toString(); String mateSequence=record.getAttribute(PairedEndWriter.mateSequenceFlag).toString(); boolean mateNegativeStrand=record.getMateNegativeStrandFlag(); String mateChr=record.getMateReferenceName(); int readStart=new Integer(record.getAttribute(PairedEndWriter.readStartFlag).toString()); String readCigar=record.getAttribute(PairedEndWriter.readCigarFlag).toString(); String readSequence=record.getReadString(); boolean readNegativeStrand=record.getReadNegativeStrandFlag(); String readChr=record.getReferenceName(); // Make the first mate record.setAlignmentStart(readStart); record.setReferenceName(readChr); record.setReadNegativeStrandFlag(readNegativeStrand); record.setCigarString(readCigar); record.setReadString(readSequence); record.setReadName(name); // Make the second mate SAMRecord record2=new SAMRecord(record.getHeader()); record2.setAlignmentStart(mateStart); record2.setReferenceName(mateChr); record2.setReadNegativeStrandFlag(mateNegativeStrand); record2.setCigarString(mateCigar); record2.setReadString(mateSequence); record2.setReadName(name); SingleEndAlignment firstMate=new SingleEndAlignment(record); SingleEndAlignment secondMate=new SingleEndAlignment(record2); rtrn=new PairedEndAlignmentFactory().getAlignment(fragment, firstMate, secondMate, transcriptionRead); rtrn.setProperPairFlag(record.getProperPairFlag()); } else { rtrn = new SingleEndAlignment(record,record.getFirstOfPairFlag()); } } else { //check if paired end without our modified record --> throw warning if (record.getReadPairedFlag() && !record.getMateUnmappedFlag() && !warned) { log.warn("DEBUG: Paired end reads were found but file is not in our paired end format. Processing as single-end reads ..."); warned = true; } //If first read is in direction of trasncription if(transcriptionRead.equals(TranscriptionRead.FIRST_OF_PAIR)){ //This is the first read if(record.getFirstOfPairFlag()){ //Orientation of fragment is same as that of read } //This is the other mate //Reverse its orientation else{ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } } //Second read is the transcription read else if(transcriptionRead.equals(TranscriptionRead.SECOND_OF_PAIR)){ //This is the first read //Reverse orientation if(record.getFirstOfPairFlag()){ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } //This is the other mate else{ //NOTHING } }//UNSTRANDED else{ //NOTHING } rtrn = new SingleEndAlignment(record, record.getReadPairedFlag() && record.getFirstOfPairFlag()); //rtrn=new SingleEndAlignment(record); } - } finally { - log.error("Failed on SAMRecord: " + record.toString()); + } catch (RuntimeException e) { + throw e; } + //finally { + //log.error("Failed on SAMRecord: " + record.toString()); + //} return rtrn; } /** * Get the lengths of the reference sequences * @param chr the chromsoome to query size * @return Map associating each reference name with sequence length */ public int getRefSequenceLengths(String chr) { Set<String> seqNames = getSequenceNames(); for(String seq : seqNames) { SAMSequenceRecord rec = header.getSequence(seq); if(seq.equalsIgnoreCase(chr)){ return Integer.valueOf(rec.getSequenceLength()); } } return -99; } /** * Get the lengths of the reference sequences * @return Map associating each reference name with sequence length */ public Map<String, Integer> getRefSequenceLengths() { Map<String, Integer> rtrn=new TreeMap<String, Integer>(); Set<String> seqNames = getSequenceNames(); for(String seq : seqNames) { SAMSequenceRecord rec = header.getSequence(seq); rtrn.put(seq, Integer.valueOf(rec.getSequenceLength())); } return rtrn; } /** * Returns {@code true} if the given SAM file is in paired end format (has the mateLine) attribute. * Will also check the file with the default extension. * @param fileToCheck * @return */ public static boolean isPairedEndFormat(String fileToCheck) { return (getPairedEndFile(fileToCheck) != null); } /** * Returns the file itself or the file plus the default {@code PAIRED_END_EXTENSION} if either * is in paired end format. If neither is in paired end format, returns null. * @param fileToCheck * @return */ public static String getPairedEndFile(String fileToCheck) { //Check the header to see if it is "Paired End Format" SAMFileReader reader = new SAMFileReader(new File(fileToCheck)); if (getAlignmentType(reader.getFileHeader()) == AlignmentType.PAIRED_END) { return fileToCheck; } //else, lets make the logical extension and see if it is there String tmpBam = fileToCheck + PairedEndWriter.PAIRED_END_EXTENSION; boolean fileExists = new File(tmpBam).exists(); if (fileExists) { //Lets test to make sure it has the correct line reader = new SAMFileReader(new File(tmpBam)); if (getAlignmentType(reader.getFileHeader()) == AlignmentType.PAIRED_END) { return tmpBam; } } return null; } /** * Finds a paired end file or creates one if it doesn't exist * @param fileToCheck * @return */ public static String getOrCreatePairedEndFile(String fileToCheck,TranscriptionRead txnRead) { String result = PairedEndReader.getPairedEndFile(fileToCheck); if (result == null) { result = PairedEndWriter.getDefaultFile(fileToCheck); PairedEndWriter writer = new PairedEndWriter(new File(fileToCheck), result); writer.convertInputToPairedEnd(txnRead); } return result; } public static void main(String[] args){ Globals.setHeadless(true); /* * @param for ArgumentMap - size, usage, default task * argMap maps the command line arguments to the respective parameters */ ArgumentMap argMap = CLUtil.getParameters(args,usage,"makeFile"); TranscriptionRead strand = TranscriptionRead.UNSTRANDED; if(argMap.get("strand").equalsIgnoreCase("first")){ //System.out.println("First read"); strand = TranscriptionRead.FIRST_OF_PAIR; } else if(argMap.get("strand").equalsIgnoreCase("second")){ //System.out.println("Second read"); strand = TranscriptionRead.SECOND_OF_PAIR; } else log.info("no strand"); //String bamFile = argMap.getMandatory("alignment"); String bamFile = getOrCreatePairedEndFile(argMap.getMandatory("alignment"),strand); String file = PairedEndReader.getPairedEndFile(bamFile); if (file == null) { file = PairedEndWriter.getDefaultFile(bamFile); PairedEndWriter writer = new PairedEndWriter(new File(bamFile), file); writer.convertInputToPairedEnd(strand); } } static final String usage = "Usage: CreatePairedEndBamFile -task makeFile "+ "\n**************************************************************"+ "\n\t\tArguments"+ "\n**************************************************************"+ "\n\t\t-strand <VALUES: first, second, unstranded. Specifies the mate that is in the direction of transcription DEFAULT: Unstranded> "+ "\n\n\t\t-alignment <Alignment file to be used for reconstruction. Required.> "; }
false
true
private Alignment samRecordToAlignment(SAMRecord record,TranscriptionRead transcriptionRead,boolean fragment) { Alignment rtrn; try { if (alignmentType == AlignmentType.PAIRED_END) { if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { //revised to read single end data @zhuxp String name=record.getReadName(); int mateStart=record.getMateAlignmentStart(); String mateCigar=record.getAttribute(PairedEndWriter.mateCigarFlag).toString(); String mateSequence=record.getAttribute(PairedEndWriter.mateSequenceFlag).toString(); boolean mateNegativeStrand=record.getMateNegativeStrandFlag(); String mateChr=record.getMateReferenceName(); int readStart=new Integer(record.getAttribute(PairedEndWriter.readStartFlag).toString()); String readCigar=record.getAttribute(PairedEndWriter.readCigarFlag).toString(); String readSequence=record.getReadString(); boolean readNegativeStrand=record.getReadNegativeStrandFlag(); String readChr=record.getReferenceName(); // Make the first mate record.setAlignmentStart(readStart); record.setReferenceName(readChr); record.setReadNegativeStrandFlag(readNegativeStrand); record.setCigarString(readCigar); record.setReadString(readSequence); record.setReadName(name); // Make the second mate SAMRecord record2=new SAMRecord(record.getHeader()); record2.setAlignmentStart(mateStart); record2.setReferenceName(mateChr); record2.setReadNegativeStrandFlag(mateNegativeStrand); record2.setCigarString(mateCigar); record2.setReadString(mateSequence); record2.setReadName(name); SingleEndAlignment firstMate=new SingleEndAlignment(record); SingleEndAlignment secondMate=new SingleEndAlignment(record2); rtrn=new PairedEndAlignmentFactory().getAlignment(fragment, firstMate, secondMate, transcriptionRead); rtrn.setProperPairFlag(record.getProperPairFlag()); } else { rtrn = new SingleEndAlignment(record,record.getFirstOfPairFlag()); } } else { //check if paired end without our modified record --> throw warning if (record.getReadPairedFlag() && !record.getMateUnmappedFlag() && !warned) { log.warn("DEBUG: Paired end reads were found but file is not in our paired end format. Processing as single-end reads ..."); warned = true; } //If first read is in direction of trasncription if(transcriptionRead.equals(TranscriptionRead.FIRST_OF_PAIR)){ //This is the first read if(record.getFirstOfPairFlag()){ //Orientation of fragment is same as that of read } //This is the other mate //Reverse its orientation else{ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } } //Second read is the transcription read else if(transcriptionRead.equals(TranscriptionRead.SECOND_OF_PAIR)){ //This is the first read //Reverse orientation if(record.getFirstOfPairFlag()){ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } //This is the other mate else{ //NOTHING } }//UNSTRANDED else{ //NOTHING } rtrn = new SingleEndAlignment(record, record.getReadPairedFlag() && record.getFirstOfPairFlag()); //rtrn=new SingleEndAlignment(record); } } finally { log.error("Failed on SAMRecord: " + record.toString()); } return rtrn; }
private Alignment samRecordToAlignment(SAMRecord record,TranscriptionRead transcriptionRead,boolean fragment) { Alignment rtrn; try { if (alignmentType == AlignmentType.PAIRED_END) { if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { //revised to read single end data @zhuxp String name=record.getReadName(); int mateStart=record.getMateAlignmentStart(); String mateCigar=record.getAttribute(PairedEndWriter.mateCigarFlag).toString(); String mateSequence=record.getAttribute(PairedEndWriter.mateSequenceFlag).toString(); boolean mateNegativeStrand=record.getMateNegativeStrandFlag(); String mateChr=record.getMateReferenceName(); int readStart=new Integer(record.getAttribute(PairedEndWriter.readStartFlag).toString()); String readCigar=record.getAttribute(PairedEndWriter.readCigarFlag).toString(); String readSequence=record.getReadString(); boolean readNegativeStrand=record.getReadNegativeStrandFlag(); String readChr=record.getReferenceName(); // Make the first mate record.setAlignmentStart(readStart); record.setReferenceName(readChr); record.setReadNegativeStrandFlag(readNegativeStrand); record.setCigarString(readCigar); record.setReadString(readSequence); record.setReadName(name); // Make the second mate SAMRecord record2=new SAMRecord(record.getHeader()); record2.setAlignmentStart(mateStart); record2.setReferenceName(mateChr); record2.setReadNegativeStrandFlag(mateNegativeStrand); record2.setCigarString(mateCigar); record2.setReadString(mateSequence); record2.setReadName(name); SingleEndAlignment firstMate=new SingleEndAlignment(record); SingleEndAlignment secondMate=new SingleEndAlignment(record2); rtrn=new PairedEndAlignmentFactory().getAlignment(fragment, firstMate, secondMate, transcriptionRead); rtrn.setProperPairFlag(record.getProperPairFlag()); } else { rtrn = new SingleEndAlignment(record,record.getFirstOfPairFlag()); } } else { //check if paired end without our modified record --> throw warning if (record.getReadPairedFlag() && !record.getMateUnmappedFlag() && !warned) { log.warn("DEBUG: Paired end reads were found but file is not in our paired end format. Processing as single-end reads ..."); warned = true; } //If first read is in direction of trasncription if(transcriptionRead.equals(TranscriptionRead.FIRST_OF_PAIR)){ //This is the first read if(record.getFirstOfPairFlag()){ //Orientation of fragment is same as that of read } //This is the other mate //Reverse its orientation else{ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } } //Second read is the transcription read else if(transcriptionRead.equals(TranscriptionRead.SECOND_OF_PAIR)){ //This is the first read //Reverse orientation if(record.getFirstOfPairFlag()){ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } //This is the other mate else{ //NOTHING } }//UNSTRANDED else{ //NOTHING } rtrn = new SingleEndAlignment(record, record.getReadPairedFlag() && record.getFirstOfPairFlag()); //rtrn=new SingleEndAlignment(record); } } catch (RuntimeException e) { throw e; } //finally { //log.error("Failed on SAMRecord: " + record.toString()); //} return rtrn; }
diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnDescriptor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnDescriptor.java index 23c6c2e3a..04ddcf414 100755 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnDescriptor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnDescriptor.java @@ -1,332 +1,332 @@ /******************************************************************************* * Copyright (c) 2005, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ui.texteditor.rulers; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.InvalidRegistryObjectException; import org.eclipse.core.runtime.content.IContentType; import org.eclipse.jface.text.Assert; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.internal.texteditor.TextEditorPlugin; import org.eclipse.ui.internal.texteditor.rulers.ExtensionPointHelper; import org.eclipse.ui.internal.texteditor.rulers.RulerColumnMessages; import org.eclipse.ui.internal.texteditor.rulers.RulerColumnPlacement; import org.eclipse.ui.internal.texteditor.rulers.RulerColumnTarget; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.IDocumentProviderExtension4; import org.eclipse.ui.texteditor.ITextEditor; /** * The description of an extension to the * <code>org.eclipse.ui.texteditor.rulerColumn</code> extension point. Instances are * immutable. Instances can be obtained from a {@link RulerColumnRegistry}. * <p> * This API is provisional and may change any time before the 3.3 API freeze. * </p> * * @since 3.3 */ public final class RulerColumnDescriptor { /** The extension schema name of the class attribute. */ private static final String CLASS= "class"; //$NON-NLS-1$ /** The extension schema name of the id attribute. */ private static final String ID= "id"; //$NON-NLS-1$ /** The extension schema name of the optional name attribute. */ private static final String NAME= "name"; //$NON-NLS-1$ /** The extension schema name of the optional enabled attribute. */ private static final String ENABLED= "enabled"; //$NON-NLS-1$ /** The extension schema name of the optional icon attribute. */ private static final String ICON= "icon"; //$NON-NLS-1$ /** The extension schema name of the optional global attribute. */ private static final String GLOBAL= "global"; //$NON-NLS-1$ /** The extension schema name of the optional menu inclusion attribute. */ private static final String INCLUDE_IN_MENU= "includeInMenu"; //$NON-NLS-1$ /** The extension schema name of the targetEditor element. */ private static final String TARGET_EDITOR= "targetEditor"; //$NON-NLS-1$ /** The extension schema name of the targetContentType element. */ private static final String TARGET_CONTENT_TYPE= "targetContentType"; //$NON-NLS-1$ /** The extension schema name of the placement element. */ private static final String PLACEMENT= "placement"; //$NON-NLS-1$ /** The identifier of the extension. */ private final String fId; /** The name of the extension, equal to the id if no name is given. */ private final String fName; /** The icon descriptor. */ private final ImageDescriptor fIcon; /** The configuration element of this extension. */ private final IConfigurationElement fElement; /** The target specification of the ruler column contribution. */ private final RulerColumnTarget fTarget; /** The placement specification of the ruler column contribution. */ private final RulerColumnPlacement fRulerColumnPlacement; /** The default enablement setting of the ruler column contribution. */ private final boolean fDefaultEnablement; /** The global setting of the ruler column contribution. */ private final boolean fIsGlobal; /** The menu inclusion setting of the ruler column contribution. */ private final boolean fIncludeInMenu; /** * Creates a new descriptor. * * @param element the configuration element to read * @param registry the computer registry creating this descriptor * @throws InvalidRegistryObjectException if the configuration element does not conform to the * extension point spec */ RulerColumnDescriptor(IConfigurationElement element, RulerColumnRegistry registry) throws InvalidRegistryObjectException { Assert.isLegal(registry != null); Assert.isLegal(element != null); fElement= element; ILog log= TextEditorPlugin.getDefault().getLog(); ExtensionPointHelper helper= new ExtensionPointHelper(element, log); fId= helper.getNonNullAttribute(ID); fName= helper.getDefaultAttribute(NAME, fId); helper.getNonNullAttribute(CLASS); // just check validity fIcon= ImageDescriptor.createFromURL(helper.getDefaultResourceURL(ICON, null)); fDefaultEnablement= helper.getDefaultAttribute(ENABLED, true); fIsGlobal= helper.getDefaultAttribute(GLOBAL, true); fIncludeInMenu= helper.getDefaultAttribute(INCLUDE_IN_MENU, true); IConfigurationElement[] targetEditors= element.getChildren(TARGET_EDITOR); IConfigurationElement[] targetContentTypes= element.getChildren(TARGET_CONTENT_TYPE); if (targetContentTypes.length + targetEditors.length == 0) fTarget= RulerColumnTarget.createAllTarget(); else { RulerColumnTarget combined= null; for (int i= 0; i < targetEditors.length; i++) { IConfigurationElement targetEditor= targetEditors[i]; RulerColumnTarget target= RulerColumnTarget.createEditorIdTarget(new ExtensionPointHelper(targetEditor, log).getNonNullAttribute(ID)); combined= combined == null ? target : RulerColumnTarget.createOrTarget(combined, target); } for (int i= 0; i < targetContentTypes.length; i++) { - IConfigurationElement targetContentType= targetEditors[i]; + IConfigurationElement targetContentType= targetContentTypes[i]; RulerColumnTarget target= RulerColumnTarget.createContentTypeTarget(new ExtensionPointHelper(targetContentType, log).getNonNullAttribute(ID)); combined= combined == null ? target : RulerColumnTarget.createOrTarget(combined, target); } fTarget= combined; } IConfigurationElement[] placements= element.getChildren(PLACEMENT); switch (placements.length) { case 0: fRulerColumnPlacement= new RulerColumnPlacement(); break; case 1: fRulerColumnPlacement= new RulerColumnPlacement(placements[0]); break; default: helper.fail(RulerColumnMessages.RulerColumnDescriptor_invalid_placement_msg); fRulerColumnPlacement= null; // dummy break; } Assert.isTrue(fTarget != null); Assert.isTrue(fRulerColumnPlacement != null); } /** * Returns the identifier of the described extension. * * @return the identifier of the described extension */ public String getId() { return fId; } /** * Returns the name of the described extension. * * @return the name of the described extension */ public String getName() { return fName; } /** * Returns the image descriptor of the described extension. * * @return the image descriptor of the described extension */ public ImageDescriptor getIcon() { return fIcon; } RulerColumnTarget getTarget() { return fTarget; } RulerColumnPlacement getPlacement() { return fRulerColumnPlacement; } /** * Returns the default enablement of the described extension. Editors that support this * contribution should typically enable the column by default. * * @return the default enablement of the described extension */ public boolean getDefaultEnablement() { return fDefaultEnablement; } /** * Returns the global property of the described extension. Changing the visibility of a column * with the global property set to <code>true</code> should typically affect all matching * editors. Changing the visibility of a column with the global property set to * <code>false</code> should only affect the current editor. * * @return the global property of the described extension */ public boolean isGlobal() { return fIsGlobal; } /** * Returns the menu inclusion property of the described extension. A toggle menu entry should be * inluded in the ruler context menu for columns with this property set to <code>true</code>. * * @return the menu inclusion property of the described extension */ public boolean isIncludedInMenu() { return fIncludeInMenu; } /** * Returns <code>true</code> if this contribution matches the passed editor, <code>false</code> if not. * * @param editor the editor to check * @return <code>true</code> if this contribution targets the passed editor */ public boolean matchesEditor(ITextEditor editor) { Assert.isLegal(editor != null); RulerColumnTarget target= getTarget(); IWorkbenchPartSite site= editor.getSite(); if (site != null && target.matchesEditorId(site.getId())) return true; IContentType contentType= getContentType(editor); return contentType != null && target.matchesContentType(contentType); } /** * Creates a {@link RulerColumn} instance as described by the receiver. This may load the contributing plug-in. * * @param editor the editor that loads the contributed column * @return the instantiated column * @throws CoreException as thrown by {@link IConfigurationElement#createExecutableExtension(String)} * @throws InvalidRegistryObjectException as thrown by {@link IConfigurationElement#createExecutableExtension(String)} */ public RulerColumn createColumn(ITextEditor editor) throws CoreException, InvalidRegistryObjectException { Assert.isLegal(editor != null); RulerColumn column= (RulerColumn) fElement.createExecutableExtension(CLASS); column.setDescriptor(this); column.setEditor(editor); column.columnCreated(); return column; } /** * Notifies the descriptor of the fact that a column is no longer needed. Calls the * {@link RulerColumn#columnRemoved()} hook. * * @param column the column that is no longer used */ public void disposeColumn(RulerColumn column) { Assert.isLegal(column != null); column.columnRemoved(); } /* * @see java.lang.Object#toString() * @since 3.3 */ public String toString() { return "RulerColumnDescriptor[name=" + getName() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } IConfigurationElement getConfigurationElement() { return fElement; } /* * @see java.lang.Object#hashCode() */ public int hashCode() { final int prime= 31; int result= 1; result= prime * result + ((fId == null) ? 0 : fId.hashCode()); return result; } /* * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final RulerColumnDescriptor other= (RulerColumnDescriptor) obj; if (fId == null) { if (other.fId != null) return false; } else if (!fId.equals(other.fId)) return false; return true; } /** * Returns the content type of the editor's input, <code>null</code> if the editor input or * the document provider is <code>null</code> or the content type cannot be determined. * * @param editor the editor to get the content type from * @return the content type of the editor's input, <code>null</code> if it cannot be * determined */ private IContentType getContentType(ITextEditor editor) { IEditorInput input= editor.getEditorInput(); if (input == null) return null; IDocumentProvider provider= editor.getDocumentProvider(); if (provider instanceof IDocumentProviderExtension4) { IDocumentProviderExtension4 ext= (IDocumentProviderExtension4) provider; try { return ext.getContentType(input); } catch (CoreException x) { // ignore and return null; } } return null; } String getContributor() { try { return fElement.getContributor().getName(); } catch (InvalidRegistryObjectException e) { return "unknown"; //$NON-NLS-1$ } } }
true
true
RulerColumnDescriptor(IConfigurationElement element, RulerColumnRegistry registry) throws InvalidRegistryObjectException { Assert.isLegal(registry != null); Assert.isLegal(element != null); fElement= element; ILog log= TextEditorPlugin.getDefault().getLog(); ExtensionPointHelper helper= new ExtensionPointHelper(element, log); fId= helper.getNonNullAttribute(ID); fName= helper.getDefaultAttribute(NAME, fId); helper.getNonNullAttribute(CLASS); // just check validity fIcon= ImageDescriptor.createFromURL(helper.getDefaultResourceURL(ICON, null)); fDefaultEnablement= helper.getDefaultAttribute(ENABLED, true); fIsGlobal= helper.getDefaultAttribute(GLOBAL, true); fIncludeInMenu= helper.getDefaultAttribute(INCLUDE_IN_MENU, true); IConfigurationElement[] targetEditors= element.getChildren(TARGET_EDITOR); IConfigurationElement[] targetContentTypes= element.getChildren(TARGET_CONTENT_TYPE); if (targetContentTypes.length + targetEditors.length == 0) fTarget= RulerColumnTarget.createAllTarget(); else { RulerColumnTarget combined= null; for (int i= 0; i < targetEditors.length; i++) { IConfigurationElement targetEditor= targetEditors[i]; RulerColumnTarget target= RulerColumnTarget.createEditorIdTarget(new ExtensionPointHelper(targetEditor, log).getNonNullAttribute(ID)); combined= combined == null ? target : RulerColumnTarget.createOrTarget(combined, target); } for (int i= 0; i < targetContentTypes.length; i++) { IConfigurationElement targetContentType= targetEditors[i]; RulerColumnTarget target= RulerColumnTarget.createContentTypeTarget(new ExtensionPointHelper(targetContentType, log).getNonNullAttribute(ID)); combined= combined == null ? target : RulerColumnTarget.createOrTarget(combined, target); } fTarget= combined; } IConfigurationElement[] placements= element.getChildren(PLACEMENT); switch (placements.length) { case 0: fRulerColumnPlacement= new RulerColumnPlacement(); break; case 1: fRulerColumnPlacement= new RulerColumnPlacement(placements[0]); break; default: helper.fail(RulerColumnMessages.RulerColumnDescriptor_invalid_placement_msg); fRulerColumnPlacement= null; // dummy break; } Assert.isTrue(fTarget != null); Assert.isTrue(fRulerColumnPlacement != null); }
RulerColumnDescriptor(IConfigurationElement element, RulerColumnRegistry registry) throws InvalidRegistryObjectException { Assert.isLegal(registry != null); Assert.isLegal(element != null); fElement= element; ILog log= TextEditorPlugin.getDefault().getLog(); ExtensionPointHelper helper= new ExtensionPointHelper(element, log); fId= helper.getNonNullAttribute(ID); fName= helper.getDefaultAttribute(NAME, fId); helper.getNonNullAttribute(CLASS); // just check validity fIcon= ImageDescriptor.createFromURL(helper.getDefaultResourceURL(ICON, null)); fDefaultEnablement= helper.getDefaultAttribute(ENABLED, true); fIsGlobal= helper.getDefaultAttribute(GLOBAL, true); fIncludeInMenu= helper.getDefaultAttribute(INCLUDE_IN_MENU, true); IConfigurationElement[] targetEditors= element.getChildren(TARGET_EDITOR); IConfigurationElement[] targetContentTypes= element.getChildren(TARGET_CONTENT_TYPE); if (targetContentTypes.length + targetEditors.length == 0) fTarget= RulerColumnTarget.createAllTarget(); else { RulerColumnTarget combined= null; for (int i= 0; i < targetEditors.length; i++) { IConfigurationElement targetEditor= targetEditors[i]; RulerColumnTarget target= RulerColumnTarget.createEditorIdTarget(new ExtensionPointHelper(targetEditor, log).getNonNullAttribute(ID)); combined= combined == null ? target : RulerColumnTarget.createOrTarget(combined, target); } for (int i= 0; i < targetContentTypes.length; i++) { IConfigurationElement targetContentType= targetContentTypes[i]; RulerColumnTarget target= RulerColumnTarget.createContentTypeTarget(new ExtensionPointHelper(targetContentType, log).getNonNullAttribute(ID)); combined= combined == null ? target : RulerColumnTarget.createOrTarget(combined, target); } fTarget= combined; } IConfigurationElement[] placements= element.getChildren(PLACEMENT); switch (placements.length) { case 0: fRulerColumnPlacement= new RulerColumnPlacement(); break; case 1: fRulerColumnPlacement= new RulerColumnPlacement(placements[0]); break; default: helper.fail(RulerColumnMessages.RulerColumnDescriptor_invalid_placement_msg); fRulerColumnPlacement= null; // dummy break; } Assert.isTrue(fTarget != null); Assert.isTrue(fRulerColumnPlacement != null); }
diff --git a/src/me/stutiguias/mcmmorankup/command/MRUCommand.java b/src/me/stutiguias/mcmmorankup/command/MRUCommand.java index 9df1cbb..1626cbb 100644 --- a/src/me/stutiguias/mcmmorankup/command/MRUCommand.java +++ b/src/me/stutiguias/mcmmorankup/command/MRUCommand.java @@ -1,85 +1,85 @@ package me.stutiguias.mcmmorankup.command; import java.util.HashMap; import me.stutiguias.mcmmorankup.Mcmmorankup; import me.stutiguias.mcmmorankup.Util; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class MRUCommand extends Util implements CommandExecutor { private final HashMap<String,CommandHandler> avaibleCommands; private final HashMap<String,CommandHandler> consoleCommands; public MRUCommand(Mcmmorankup plugin) { super(plugin); avaibleCommands = new HashMap<>(); consoleCommands = new HashMap<>(); Help help = new Help(plugin); Reload reload = new Reload(plugin); Report report = new Report(plugin); Set set = new Set(plugin); avaibleCommands.put("buy", new Buy(plugin)); avaibleCommands.put("display", new Display(plugin)); avaibleCommands.put("feeds", new Feeds(plugin)); avaibleCommands.put("female", new Female(plugin)); avaibleCommands.put("hab", new Hab(plugin)); avaibleCommands.put("help", help); avaibleCommands.put("?", help); avaibleCommands.put("male", new Male(plugin)); avaibleCommands.put("pinfo", new Pinfo(plugin)); - avaibleCommands.put("rankup", new RankUp(plugin)); + avaibleCommands.put("rank", new RankUp(plugin)); avaibleCommands.put("reload", reload); avaibleCommands.put("report", report); avaibleCommands.put("set", set); avaibleCommands.put("stats", new Stats(plugin)); avaibleCommands.put("update", new Update(plugin)); avaibleCommands.put("ver", new Ver(plugin)); avaibleCommands.put("view", new View(plugin)); consoleCommands.put("reload", reload); consoleCommands.put("set", set); consoleCommands.put("report", report); } @Override public boolean onCommand(CommandSender sender, Command cmnd, String string, String[] args) { this.sender = sender; if (sender.getName().equalsIgnoreCase("CONSOLE")) return isConsole(args); if (!(sender instanceof Player)) return false; if(args.length < 0 || args.length == 0) return CommandNotFound(); String executedCommand = args[0].toLowerCase(); if(avaibleCommands.containsKey(executedCommand)) return avaibleCommands.get(executedCommand).OnCommand(sender,args); else return CommandNotFound(); } private boolean CommandNotFound() { SendMessage("&3&lThis command don't exists or you don't have permission"); SendMessage("&3&lTry /mru ? or help"); return true; } public boolean isConsole(String[] args) { if (args.length < 1) { return false; } String executedCommand = args[0].toLowerCase(); if(consoleCommands.containsKey(executedCommand)) return consoleCommands.get(executedCommand).OnCommand(sender,args); else return CommandNotFound(); } }
true
true
public MRUCommand(Mcmmorankup plugin) { super(plugin); avaibleCommands = new HashMap<>(); consoleCommands = new HashMap<>(); Help help = new Help(plugin); Reload reload = new Reload(plugin); Report report = new Report(plugin); Set set = new Set(plugin); avaibleCommands.put("buy", new Buy(plugin)); avaibleCommands.put("display", new Display(plugin)); avaibleCommands.put("feeds", new Feeds(plugin)); avaibleCommands.put("female", new Female(plugin)); avaibleCommands.put("hab", new Hab(plugin)); avaibleCommands.put("help", help); avaibleCommands.put("?", help); avaibleCommands.put("male", new Male(plugin)); avaibleCommands.put("pinfo", new Pinfo(plugin)); avaibleCommands.put("rankup", new RankUp(plugin)); avaibleCommands.put("reload", reload); avaibleCommands.put("report", report); avaibleCommands.put("set", set); avaibleCommands.put("stats", new Stats(plugin)); avaibleCommands.put("update", new Update(plugin)); avaibleCommands.put("ver", new Ver(plugin)); avaibleCommands.put("view", new View(plugin)); consoleCommands.put("reload", reload); consoleCommands.put("set", set); consoleCommands.put("report", report); }
public MRUCommand(Mcmmorankup plugin) { super(plugin); avaibleCommands = new HashMap<>(); consoleCommands = new HashMap<>(); Help help = new Help(plugin); Reload reload = new Reload(plugin); Report report = new Report(plugin); Set set = new Set(plugin); avaibleCommands.put("buy", new Buy(plugin)); avaibleCommands.put("display", new Display(plugin)); avaibleCommands.put("feeds", new Feeds(plugin)); avaibleCommands.put("female", new Female(plugin)); avaibleCommands.put("hab", new Hab(plugin)); avaibleCommands.put("help", help); avaibleCommands.put("?", help); avaibleCommands.put("male", new Male(plugin)); avaibleCommands.put("pinfo", new Pinfo(plugin)); avaibleCommands.put("rank", new RankUp(plugin)); avaibleCommands.put("reload", reload); avaibleCommands.put("report", report); avaibleCommands.put("set", set); avaibleCommands.put("stats", new Stats(plugin)); avaibleCommands.put("update", new Update(plugin)); avaibleCommands.put("ver", new Ver(plugin)); avaibleCommands.put("view", new View(plugin)); consoleCommands.put("reload", reload); consoleCommands.put("set", set); consoleCommands.put("report", report); }
diff --git a/src/main/java/net/minecraft/src/LoadingScreenRenderer.java b/src/main/java/net/minecraft/src/LoadingScreenRenderer.java index 8d9ccdfb..3982e1e3 100644 --- a/src/main/java/net/minecraft/src/LoadingScreenRenderer.java +++ b/src/main/java/net/minecraft/src/LoadingScreenRenderer.java @@ -1,152 +1,153 @@ package net.minecraft.src; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; public class LoadingScreenRenderer implements IProgressUpdate { private String field_73727_a = ""; /** A reference to the Minecraft object. */ private Minecraft mc; /** * The text currently displayed (i.e. the argument to the last call to printText or func_73722_d) */ private String currentlyDisplayedText = ""; private long field_73723_d = Minecraft.getSystemTime(); private boolean field_73724_e = false; public LoadingScreenRenderer(Minecraft par1Minecraft) { this.mc = par1Minecraft; } /** * this string, followed by "working..." and then the "% complete" are the 3 lines shown. This resets progress to 0, * and the WorkingString to "working...". */ public void resetProgressAndMessage(String par1Str) { this.field_73724_e = false; this.func_73722_d(par1Str); } /** * "Saving level", or the loading,or downloading equivelent */ public void displayProgressMessage(String par1Str) { this.field_73724_e = true; this.func_73722_d(par1Str); } public void func_73722_d(String par1Str) { this.currentlyDisplayedText = par1Str; if (!this.mc.running) { if (!this.field_73724_e) { throw new MinecraftError(); } } else { ScaledResolution var2 = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, var2.getScaledWidth_double(), var2.getScaledHeight_double(), 0.0D, 100.0D, 300.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -200.0F); } } /** * This is called with "Working..." by resetProgressAndMessage */ public void resetProgresAndWorkingMessage(String par1Str) { if (!this.mc.running) { if (!this.field_73724_e) { throw new MinecraftError(); } } else { this.field_73723_d = 0L; this.field_73727_a = par1Str; this.setLoadingProgress(-1); this.field_73723_d = 0L; } } /** * Updates the progress bar on the loading screen to the specified amount. Args: loadProgress */ public void setLoadingProgress(int par1) { if (!this.mc.running) { if (!this.field_73724_e) { throw new MinecraftError(); } } else { long var2 = Minecraft.getSystemTime(); if (var2 - this.field_73723_d >= 100L) { this.field_73723_d = var2; ScaledResolution var4 = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int var5 = var4.getScaledWidth(); int var6 = var4.getScaledHeight(); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, var4.getScaledWidth_double(), var4.getScaledHeight_double(), 0.0D, 100.0D, 300.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -200.0F); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); Tessellator var7 = Tessellator.instance; this.mc.renderEngine.bindTexture("/gui/background.png"); float var8 = 32.0F; var7.startDrawingQuads(); var7.setColorOpaque_I(4210752); var7.addVertexWithUV(0.0D, (double)var6, 0.0D, 0.0D, (double)((float)var6 / var8)); var7.addVertexWithUV((double)var5, (double)var6, 0.0D, (double)((float)var5 / var8), (double)((float)var6 / var8)); var7.addVertexWithUV((double)var5, 0.0D, 0.0D, (double)((float)var5 / var8), 0.0D); var7.addVertexWithUV(0.0D, 0.0D, 0.0D, 0.0D, 0.0D); var7.draw(); - // Spout Start - Shouldn't be needed, but it is. - GL11.glEnable(GL11.GL_TEXTURE_2D); - // Spout End if (par1 >= 0) { byte var9 = 100; byte var10 = 2; int var11 = var5 / 2 - var9 / 2; int var12 = var6 / 2 + 16; GL11.glDisable(GL11.GL_TEXTURE_2D); var7.startDrawingQuads(); var7.setColorOpaque_I(8421504); var7.addVertex((double)var11, (double)var12, 0.0D); var7.addVertex((double)var11, (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + var9), (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + var9), (double)var12, 0.0D); var7.setColorOpaque_I(8454016); var7.addVertex((double)var11, (double)var12, 0.0D); var7.addVertex((double)var11, (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + par1), (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + par1), (double)var12, 0.0D); var7.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); + // Spout Start + } else { + GL11.glEnable(GL11.GL_TEXTURE_2D); + // Spout End } this.mc.fontRenderer.drawStringWithShadow(this.currentlyDisplayedText, (var5 - this.mc.fontRenderer.getStringWidth(this.currentlyDisplayedText)) / 2, var6 / 2 - 4 - 16, 16777215); this.mc.fontRenderer.drawStringWithShadow(this.field_73727_a, (var5 - this.mc.fontRenderer.getStringWidth(this.field_73727_a)) / 2, var6 / 2 - 4 + 8, 16777215); Display.update(); try { Thread.yield(); } catch (Exception var13) { ; } } } } /** * called when there is no more progress to be had, both on completion and failure */ public void onNoMoreProgress() {} }
false
true
public void setLoadingProgress(int par1) { if (!this.mc.running) { if (!this.field_73724_e) { throw new MinecraftError(); } } else { long var2 = Minecraft.getSystemTime(); if (var2 - this.field_73723_d >= 100L) { this.field_73723_d = var2; ScaledResolution var4 = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int var5 = var4.getScaledWidth(); int var6 = var4.getScaledHeight(); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, var4.getScaledWidth_double(), var4.getScaledHeight_double(), 0.0D, 100.0D, 300.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -200.0F); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); Tessellator var7 = Tessellator.instance; this.mc.renderEngine.bindTexture("/gui/background.png"); float var8 = 32.0F; var7.startDrawingQuads(); var7.setColorOpaque_I(4210752); var7.addVertexWithUV(0.0D, (double)var6, 0.0D, 0.0D, (double)((float)var6 / var8)); var7.addVertexWithUV((double)var5, (double)var6, 0.0D, (double)((float)var5 / var8), (double)((float)var6 / var8)); var7.addVertexWithUV((double)var5, 0.0D, 0.0D, (double)((float)var5 / var8), 0.0D); var7.addVertexWithUV(0.0D, 0.0D, 0.0D, 0.0D, 0.0D); var7.draw(); // Spout Start - Shouldn't be needed, but it is. GL11.glEnable(GL11.GL_TEXTURE_2D); // Spout End if (par1 >= 0) { byte var9 = 100; byte var10 = 2; int var11 = var5 / 2 - var9 / 2; int var12 = var6 / 2 + 16; GL11.glDisable(GL11.GL_TEXTURE_2D); var7.startDrawingQuads(); var7.setColorOpaque_I(8421504); var7.addVertex((double)var11, (double)var12, 0.0D); var7.addVertex((double)var11, (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + var9), (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + var9), (double)var12, 0.0D); var7.setColorOpaque_I(8454016); var7.addVertex((double)var11, (double)var12, 0.0D); var7.addVertex((double)var11, (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + par1), (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + par1), (double)var12, 0.0D); var7.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); } this.mc.fontRenderer.drawStringWithShadow(this.currentlyDisplayedText, (var5 - this.mc.fontRenderer.getStringWidth(this.currentlyDisplayedText)) / 2, var6 / 2 - 4 - 16, 16777215); this.mc.fontRenderer.drawStringWithShadow(this.field_73727_a, (var5 - this.mc.fontRenderer.getStringWidth(this.field_73727_a)) / 2, var6 / 2 - 4 + 8, 16777215); Display.update(); try { Thread.yield(); } catch (Exception var13) { ; } } } }
public void setLoadingProgress(int par1) { if (!this.mc.running) { if (!this.field_73724_e) { throw new MinecraftError(); } } else { long var2 = Minecraft.getSystemTime(); if (var2 - this.field_73723_d >= 100L) { this.field_73723_d = var2; ScaledResolution var4 = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int var5 = var4.getScaledWidth(); int var6 = var4.getScaledHeight(); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, var4.getScaledWidth_double(), var4.getScaledHeight_double(), 0.0D, 100.0D, 300.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -200.0F); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); Tessellator var7 = Tessellator.instance; this.mc.renderEngine.bindTexture("/gui/background.png"); float var8 = 32.0F; var7.startDrawingQuads(); var7.setColorOpaque_I(4210752); var7.addVertexWithUV(0.0D, (double)var6, 0.0D, 0.0D, (double)((float)var6 / var8)); var7.addVertexWithUV((double)var5, (double)var6, 0.0D, (double)((float)var5 / var8), (double)((float)var6 / var8)); var7.addVertexWithUV((double)var5, 0.0D, 0.0D, (double)((float)var5 / var8), 0.0D); var7.addVertexWithUV(0.0D, 0.0D, 0.0D, 0.0D, 0.0D); var7.draw(); if (par1 >= 0) { byte var9 = 100; byte var10 = 2; int var11 = var5 / 2 - var9 / 2; int var12 = var6 / 2 + 16; GL11.glDisable(GL11.GL_TEXTURE_2D); var7.startDrawingQuads(); var7.setColorOpaque_I(8421504); var7.addVertex((double)var11, (double)var12, 0.0D); var7.addVertex((double)var11, (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + var9), (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + var9), (double)var12, 0.0D); var7.setColorOpaque_I(8454016); var7.addVertex((double)var11, (double)var12, 0.0D); var7.addVertex((double)var11, (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + par1), (double)(var12 + var10), 0.0D); var7.addVertex((double)(var11 + par1), (double)var12, 0.0D); var7.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); // Spout Start } else { GL11.glEnable(GL11.GL_TEXTURE_2D); // Spout End } this.mc.fontRenderer.drawStringWithShadow(this.currentlyDisplayedText, (var5 - this.mc.fontRenderer.getStringWidth(this.currentlyDisplayedText)) / 2, var6 / 2 - 4 - 16, 16777215); this.mc.fontRenderer.drawStringWithShadow(this.field_73727_a, (var5 - this.mc.fontRenderer.getStringWidth(this.field_73727_a)) / 2, var6 / 2 - 4 + 8, 16777215); Display.update(); try { Thread.yield(); } catch (Exception var13) { ; } } } }
diff --git a/zssapp/test/SS_149_Test.java b/zssapp/test/SS_149_Test.java index 6276df7..4b91c70 100644 --- a/zssapp/test/SS_149_Test.java +++ b/zssapp/test/SS_149_Test.java @@ -1,48 +1,47 @@ import org.zkoss.ztl.JQuery; import org.zkoss.ztl.util.ColorVerifingHelper; /* order_test_1Test.java Purpose: Description: History: Sep, 7, 2010 17:30:59 PM Copyright (C) 2010 Potix Corporation. All Rights Reserved. This program is distributed under Apache License Version 2.0 in the hope that it will be useful, but WITHOUT ANY WARRANTY. */ //right click "fill color" : B13 public class SS_149_Test extends SSAbstractTestCase { @Override protected void executeTest() { rightClickCell(1,12); click(jq("div[title=\"Fill color\"] img.z-colorbtn-btn:eq(2)")); waitResponse(); // Input color hex code, then press Enter. - JQuery colorTextbox = jq(".z-colorpalette-hex-inp:eq(5)"); + JQuery colorTextbox = jq(".z-colorbtn-pp:visible .z-colorpalette-hex-inp"); String bgColorStr = "#00ff00"; type(colorTextbox, bgColorStr); keyPressEnter(colorTextbox); //Verify JQuery cell_B_13_Outer = getSpecifiedCellOuter(1, 12); String style = cell_B_13_Outer.css("background-color"); //input "#00ff00", but it actually get "009900" //Is it acceptable in this spec? if (style != null) { verifyTrue("Unexcepted result: " + cell_B_13_Outer.css("background-color"), - ColorVerifingHelper.isEqualColor("#009900", style)); + ColorVerifingHelper.isEqualColor("#00ff00", style)); } else { verifyTrue("Cannot get style of specified cell!", false); } - sleep(5000); } }
false
true
protected void executeTest() { rightClickCell(1,12); click(jq("div[title=\"Fill color\"] img.z-colorbtn-btn:eq(2)")); waitResponse(); // Input color hex code, then press Enter. JQuery colorTextbox = jq(".z-colorpalette-hex-inp:eq(5)"); String bgColorStr = "#00ff00"; type(colorTextbox, bgColorStr); keyPressEnter(colorTextbox); //Verify JQuery cell_B_13_Outer = getSpecifiedCellOuter(1, 12); String style = cell_B_13_Outer.css("background-color"); //input "#00ff00", but it actually get "009900" //Is it acceptable in this spec? if (style != null) { verifyTrue("Unexcepted result: " + cell_B_13_Outer.css("background-color"), ColorVerifingHelper.isEqualColor("#009900", style)); } else { verifyTrue("Cannot get style of specified cell!", false); } sleep(5000); }
protected void executeTest() { rightClickCell(1,12); click(jq("div[title=\"Fill color\"] img.z-colorbtn-btn:eq(2)")); waitResponse(); // Input color hex code, then press Enter. JQuery colorTextbox = jq(".z-colorbtn-pp:visible .z-colorpalette-hex-inp"); String bgColorStr = "#00ff00"; type(colorTextbox, bgColorStr); keyPressEnter(colorTextbox); //Verify JQuery cell_B_13_Outer = getSpecifiedCellOuter(1, 12); String style = cell_B_13_Outer.css("background-color"); //input "#00ff00", but it actually get "009900" //Is it acceptable in this spec? if (style != null) { verifyTrue("Unexcepted result: " + cell_B_13_Outer.css("background-color"), ColorVerifingHelper.isEqualColor("#00ff00", style)); } else { verifyTrue("Cannot get style of specified cell!", false); } }
diff --git a/aufgabe8/src/Hunter.java b/aufgabe8/src/Hunter.java index 321d2cd..672e49a 100644 --- a/aufgabe8/src/Hunter.java +++ b/aufgabe8/src/Hunter.java @@ -1,136 +1,136 @@ import java.util.ArrayList; public class Hunter extends Character { private static final int MAXSTEPS = 1000; private String name; private int booty, posx, posy, steps, lastpos; private Game game; private Field pos; /** * (precondition) x and y have to be in the bounds of the games labyrinth, game must be a valid game instance * (not null), time has to be bigger than 0 * (postcondition) If all parameters were valid, a new instance of Hunter has been created, ready to be started, * if the start-coordinates were invalid, this Hunter will be terminated and removed. */ public Hunter(int time, int x, int y, String name, Game game) { super(time, game); this.name = name; this.booty = 0; this.posx = x; this.posy = y; this.steps = 0; this.lastpos = -1; this.game = game; try { pos = game.getLabyrith().getField(x, y); } catch (IndexOutOfBoundsException ex) { System.err.println("Hunter "+name+" in game "+game+" spawned on invalid field! Hunter will die now."); this.die(); } } /** * (precondition) Hunter is up and running, game is a valid game, the Hunter is on a valid position on * the field and able to move (not blocked by walls) * (postcondition) After this method was called, with all the preconditions fulfilled, the Hunter will * have moved one square, eventually being killed or winning the game in the process. The step counter * will be incremented. * If the conditions were not met, the Hunter will be terminated and removed */ @Override protected void move() { // List all directions ArrayList<Integer> directions = new ArrayList<Integer>(4); directions.add(Field.NORTH); // N directions.add(Field.EAST); // E directions.add(Field.SOUTH); // S directions.add(Field.WEST); // W Labyrinth lab = game.getLabyrith(); // Remove directions blocked by wall if (lab.hasWall(pos, Field.NORTH)) { directions.remove(new Integer(Field.NORTH)); } else if (lab.hasWall(pos, Field.EAST)) { directions.remove(new Integer(Field.EAST)); } else if (lab.hasWall(pos, Field.SOUTH)) { directions.remove(new Integer(Field.SOUTH)); } else if (lab.hasWall(pos, Field.WEST)) { directions.remove(new Integer(Field.WEST)); } // If list is empty and there's no where to go, die if (directions.size() == 0) { this.die(); return; } // If list size > 1 and lastpos defined, don't go there if (directions.size() > 1 && lastpos >= 0 && lastpos < 4) { directions.remove(lastpos); } // Pick random direction from list - int direction = directions.get( (int) Math.round(Math.random() * directions.size()) ); + int direction = directions.get( (int) Math.round(Math.random() * (directions.size()-1)) ); int newx, newy; newx = posx; newy = posy; if (direction == Field.NORTH) { newy--; } else if (direction == Field.EAST) { newx++; } else if (direction == Field.SOUTH) { newy++; } else if (direction == Field.WEST) { newx--; } // if win field, game is over if (game.getLabyrith().onWinField(newx, newy)) { game.hunterWin(); } else { pos.leave(this); // Leave field try { pos = game.getLabyrith().getField(newx, newy); } catch (IndexOutOfBoundsException ex) { // This cannot happen if this program is correct System.err.println("ERRO: Hunter "+name+" made illegal move! This should not happen, terminating program."); System.exit(1); } pos.enter(this); // Increment step count and end game if maxstep reached if (++steps >= MAXSTEPS) game.hunterWin(); // Update lastpos and coordinates if (direction == Field.NORTH) { lastpos = Field.SOUTH; } else if (direction == Field.EAST) { lastpos = Field.WEST; } else if (direction == Field.SOUTH) { lastpos = Field.NORTH; } else if (direction == Field.WEST) { lastpos = Field.EAST; } posx = newx; posy = newy; } } // (invariant) Name of this Hunter will be returned and not altered public String getName() { return name; } // (invariant) Value of collected treasures of this Hunter will be returned and not altered public int getBooty() { return booty; } // (postcondition) The Thread of this Hunter will stop at some point, it will be removed from // the game and not move anymore public void die() { this.stopThread(); game.killHunter(this); } }
true
true
protected void move() { // List all directions ArrayList<Integer> directions = new ArrayList<Integer>(4); directions.add(Field.NORTH); // N directions.add(Field.EAST); // E directions.add(Field.SOUTH); // S directions.add(Field.WEST); // W Labyrinth lab = game.getLabyrith(); // Remove directions blocked by wall if (lab.hasWall(pos, Field.NORTH)) { directions.remove(new Integer(Field.NORTH)); } else if (lab.hasWall(pos, Field.EAST)) { directions.remove(new Integer(Field.EAST)); } else if (lab.hasWall(pos, Field.SOUTH)) { directions.remove(new Integer(Field.SOUTH)); } else if (lab.hasWall(pos, Field.WEST)) { directions.remove(new Integer(Field.WEST)); } // If list is empty and there's no where to go, die if (directions.size() == 0) { this.die(); return; } // If list size > 1 and lastpos defined, don't go there if (directions.size() > 1 && lastpos >= 0 && lastpos < 4) { directions.remove(lastpos); } // Pick random direction from list int direction = directions.get( (int) Math.round(Math.random() * directions.size()) ); int newx, newy; newx = posx; newy = posy; if (direction == Field.NORTH) { newy--; } else if (direction == Field.EAST) { newx++; } else if (direction == Field.SOUTH) { newy++; } else if (direction == Field.WEST) { newx--; } // if win field, game is over if (game.getLabyrith().onWinField(newx, newy)) { game.hunterWin(); } else { pos.leave(this); // Leave field try { pos = game.getLabyrith().getField(newx, newy); } catch (IndexOutOfBoundsException ex) { // This cannot happen if this program is correct System.err.println("ERRO: Hunter "+name+" made illegal move! This should not happen, terminating program."); System.exit(1); } pos.enter(this); // Increment step count and end game if maxstep reached if (++steps >= MAXSTEPS) game.hunterWin(); // Update lastpos and coordinates if (direction == Field.NORTH) { lastpos = Field.SOUTH; } else if (direction == Field.EAST) { lastpos = Field.WEST; } else if (direction == Field.SOUTH) { lastpos = Field.NORTH; } else if (direction == Field.WEST) { lastpos = Field.EAST; } posx = newx; posy = newy; } }
protected void move() { // List all directions ArrayList<Integer> directions = new ArrayList<Integer>(4); directions.add(Field.NORTH); // N directions.add(Field.EAST); // E directions.add(Field.SOUTH); // S directions.add(Field.WEST); // W Labyrinth lab = game.getLabyrith(); // Remove directions blocked by wall if (lab.hasWall(pos, Field.NORTH)) { directions.remove(new Integer(Field.NORTH)); } else if (lab.hasWall(pos, Field.EAST)) { directions.remove(new Integer(Field.EAST)); } else if (lab.hasWall(pos, Field.SOUTH)) { directions.remove(new Integer(Field.SOUTH)); } else if (lab.hasWall(pos, Field.WEST)) { directions.remove(new Integer(Field.WEST)); } // If list is empty and there's no where to go, die if (directions.size() == 0) { this.die(); return; } // If list size > 1 and lastpos defined, don't go there if (directions.size() > 1 && lastpos >= 0 && lastpos < 4) { directions.remove(lastpos); } // Pick random direction from list int direction = directions.get( (int) Math.round(Math.random() * (directions.size()-1)) ); int newx, newy; newx = posx; newy = posy; if (direction == Field.NORTH) { newy--; } else if (direction == Field.EAST) { newx++; } else if (direction == Field.SOUTH) { newy++; } else if (direction == Field.WEST) { newx--; } // if win field, game is over if (game.getLabyrith().onWinField(newx, newy)) { game.hunterWin(); } else { pos.leave(this); // Leave field try { pos = game.getLabyrith().getField(newx, newy); } catch (IndexOutOfBoundsException ex) { // This cannot happen if this program is correct System.err.println("ERRO: Hunter "+name+" made illegal move! This should not happen, terminating program."); System.exit(1); } pos.enter(this); // Increment step count and end game if maxstep reached if (++steps >= MAXSTEPS) game.hunterWin(); // Update lastpos and coordinates if (direction == Field.NORTH) { lastpos = Field.SOUTH; } else if (direction == Field.EAST) { lastpos = Field.WEST; } else if (direction == Field.SOUTH) { lastpos = Field.NORTH; } else if (direction == Field.WEST) { lastpos = Field.EAST; } posx = newx; posy = newy; } }
diff --git a/common/crazypants/render/RenderUtil.java b/common/crazypants/render/RenderUtil.java index d4a8a8561..fa4f5288c 100644 --- a/common/crazypants/render/RenderUtil.java +++ b/common/crazypants/render/RenderUtil.java @@ -1,351 +1,351 @@ package crazypants.render; import static net.minecraftforge.common.ForgeDirection.DOWN; import static net.minecraftforge.common.ForgeDirection.EAST; import static net.minecraftforge.common.ForgeDirection.NORTH; import static net.minecraftforge.common.ForgeDirection.SOUTH; import static net.minecraftforge.common.ForgeDirection.UP; import static net.minecraftforge.common.ForgeDirection.WEST; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.item.ItemStack; import net.minecraft.util.Icon; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import org.lwjgl.opengl.GL11; import crazypants.util.BlockCoord; import crazypants.vecmath.Matrix4d; import crazypants.vecmath.VecmathUtil; import crazypants.vecmath.Vector2d; import crazypants.vecmath.Vector3d; import crazypants.vecmath.Vector3f; import crazypants.vecmath.Vector4d; public class RenderUtil { public static final Vector3d UP_V = new Vector3d(0, 1, 0); public static final Vector3d ZERO_V = new Vector3d(0, 0, 0); private static final FloatBuffer MATRIX_BUFFER = GLAllocation.createDirectFloatBuffer(16); public static final ResourceLocation BLOCK_TEX = TextureMap.field_110575_b; public static final ResourceLocation ITEM_TEX = TextureMap.field_110576_c; public static final ResourceLocation GLINT_TEX = new ResourceLocation("textures/misc/enchanted_item_glint.png"); public static void loadMatrix(Matrix4d mat) { MATRIX_BUFFER.rewind(); MATRIX_BUFFER.put((float) mat.m00); MATRIX_BUFFER.put((float) mat.m01); MATRIX_BUFFER.put((float) mat.m02); MATRIX_BUFFER.put((float) mat.m03); MATRIX_BUFFER.put((float) mat.m10); MATRIX_BUFFER.put((float) mat.m11); MATRIX_BUFFER.put((float) mat.m12); MATRIX_BUFFER.put((float) mat.m13); MATRIX_BUFFER.put((float) mat.m20); MATRIX_BUFFER.put((float) mat.m21); MATRIX_BUFFER.put((float) mat.m22); MATRIX_BUFFER.put((float) mat.m23); MATRIX_BUFFER.put((float) mat.m30); MATRIX_BUFFER.put((float) mat.m31); MATRIX_BUFFER.put((float) mat.m32); MATRIX_BUFFER.put((float) mat.m33); MATRIX_BUFFER.rewind(); GL11.glLoadMatrix(MATRIX_BUFFER); } public static TextureManager engine() { return Minecraft.getMinecraft().renderEngine; } public static void bindItemTexture(ItemStack stack) { engine().func_110577_a(stack.getItemSpriteNumber() == 0 ? BLOCK_TEX : ITEM_TEX); } public static void bindItemTexture() { engine().func_110577_a(ITEM_TEX); } public static void bindBlockTexture() { engine().func_110577_a(BLOCK_TEX); } public static void bindGlintTexture() { engine().func_110577_a(BLOCK_TEX); } public static void bindTexture(String string) { engine().func_110577_a(new ResourceLocation(string)); } public static void bindTexture(ResourceLocation tex) { engine().func_110577_a(tex); } public static FontRenderer fontRenderer() { return Minecraft.getMinecraft().fontRenderer; } public static float claculateTotalBrightnessForLocation(World worldObj, int xCoord, int yCoord, int zCoord) { int i = worldObj.getLightBrightnessForSkyBlocks(xCoord, yCoord, zCoord, 0); int j = i % 65536; int k = i / 65536; float minLight = 0; //0.2 - 1 float sunBrightness = worldObj.getSunBrightness(1); float percentRecievedFromSun = k / 255f; //Highest value recieved from a light float fromLights = j / 255f; // 0 - 1 for sun only, 0 - 0.6 for light only float recievedPercent = worldObj.getLightBrightness(xCoord, yCoord, zCoord); float highestValue = Math.max(fromLights, percentRecievedFromSun * sunBrightness); return Math.max(0.2f, highestValue); } public static float getColorMultiplierForFace(ForgeDirection face) { if(face == ForgeDirection.UP) { return 1; } if(face == ForgeDirection.DOWN) { return 0.5f; } if(face.offsetX != 0) { return 0.6f; } return 0.8f; // z } public static int setTesselatorBrightness(IBlockAccess world, int x, int y, int z) { Block block = Block.blocksList[world.getBlockId(x, y, z)]; int res = block == null ? world.getLightBrightnessForSkyBlocks(x, y, z, 0) : block.getMixedBrightnessForBlock(world, x, y, z); Tessellator.instance.setBrightness(res); Tessellator.instance.setColorRGBA_F(1, 1, 1, 1); return res; } public static void renderQuad2D(double x, double y, double z, double width, double height, int colorRGB) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_TEXTURE_2D); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.setColorOpaque_I(colorRGB); tessellator.addVertex(x, y + height, z); tessellator.addVertex(x + width, y + height, z); tessellator.addVertex(x + width, y, z); tessellator.addVertex(x, y, z); tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); } public static List<ForgeDirection> getEdgesForFace(ForgeDirection face) { List<ForgeDirection> result = new ArrayList<ForgeDirection>(4); if(face.offsetY != 0) { result.add(EAST); result.add(WEST); result.add(NORTH); result.add(SOUTH); } else if(face.offsetX != 0) { result.add(DOWN); result.add(UP); result.add(SOUTH); result.add(NORTH); } else { result.add(UP); result.add(DOWN); result.add(WEST); result.add(EAST); } return result; } public static void renderConnectedTextureFace(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face, Icon texture, boolean forceAllEdges) { renderConnectedTextureFace(blockAccess, x, y, z, face, texture, forceAllEdges, true, true); } public static void renderConnectedTextureFace(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face, Icon texture, boolean forceAllEdges, boolean translateToXYZ, boolean applyFaceShading) { - if(blockAccess == null || face == null || texture == null) { + if((blockAccess == null && !forceAllEdges) || face == null || texture == null) { return; } if(!forceAllEdges) { int blockID = blockAccess.getBlockId(x, y, z); if(blockID <= 0 || Block.blocksList[blockID] == null) { return; } if(!Block.blocksList[blockID].shouldSideBeRendered(blockAccess, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())) { return; } } BlockCoord bc = new BlockCoord(x, y, z); List<ForgeDirection> edges; if(forceAllEdges) { edges = RenderUtil.getEdgesForFace(face); } else { edges = RenderUtil.getNonConectedEdgesForFace(blockAccess, x, y, z, face); } Tessellator tes = Tessellator.instance; tes.setNormal(face.offsetX, face.offsetY, face.offsetZ); if(applyFaceShading) { float cm = RenderUtil.getColorMultiplierForFace(face); tes.setColorOpaque_F(cm, cm, cm); } float scaleFactor = 15f / 16f; Vector2d uv = new Vector2d(); for (ForgeDirection edge : edges) { float xLen = 1 - Math.abs(edge.offsetX) * scaleFactor; float yLen = 1 - Math.abs(edge.offsetY) * scaleFactor; float zLen = 1 - Math.abs(edge.offsetZ) * scaleFactor; BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); List<Vector3f> corners = bb.getCornersForFace(face); for (Vector3f unitCorn : corners) { Vector3d corner = new Vector3d(unitCorn); if(translateToXYZ) { corner.x += x; corner.y += y; corner.z += z; } corner.x += (float) (edge.offsetX * 0.5) - Math.signum(edge.offsetX) * xLen / 2f; corner.y += (float) (edge.offsetY * 0.5) - Math.signum(edge.offsetY) * yLen / 2f; corner.z += (float) (edge.offsetZ * 0.5) - Math.signum(edge.offsetZ) * zLen / 2f; if(translateToXYZ) { RenderUtil.getUvForCorner(uv, corner, x, y, z, face, texture); } else { RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); } tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); } } } public static List<ForgeDirection> getNonConectedEdgesForFace(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face) { int blockID = blockAccess.getBlockId(x, y, z); if(blockID <= 0 || Block.blocksList[blockID] == null) { return Collections.emptyList(); } if(!Block.blocksList[blockID].shouldSideBeRendered(blockAccess, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())) { return Collections.emptyList(); } BlockCoord bc = new BlockCoord(x, y, z); List<EdgeNeighbour> edges = new ArrayList<EdgeNeighbour>(4); for (ForgeDirection dir : getEdgesForFace(face)) { edges.add(new EdgeNeighbour(bc, dir)); } List<ForgeDirection> result = new ArrayList<ForgeDirection>(4); for (EdgeNeighbour edge : edges) { if(blockAccess.getBlockId(edge.bc.x, edge.bc.y, edge.bc.z) != blockID) { result.add(edge.dir); } // else if(blockAccess.getBlockId(edge.bc.x + face.offsetX, edge.bc.y + // face.offsetY, edge.bc.z + face.offsetZ) == blockID) { // result.add(edge.dir); //corner // } } return result; } public static void getUvForCorner(Vector2d uv, Vector3d corner, int x, int y, int z, ForgeDirection face, Icon icon) { if(icon == null) { return; } Vector3d p = new Vector3d(corner); p.x -= x; p.y -= y; p.z -= z; float uWidth = icon.getMaxU() - icon.getMinU(); float vWidth = icon.getMaxV() - icon.getMinV(); uv.x = VecmathUtil.distanceFromPointToPlane(getUPlaneForFace(face), p); uv.y = VecmathUtil.distanceFromPointToPlane(getVPlaneForFace(face), p); uv.x = icon.getMinU() + (uv.x * uWidth); uv.y = icon.getMinV() + (uv.y * vWidth); } public static Vector4d getVPlaneForFace(ForgeDirection face) { switch (face) { case DOWN: case UP: return new Vector4d(0, 0, 1, 0); case EAST: case WEST: case NORTH: case SOUTH: return new Vector4d(0, -1, 0, 1); case UNKNOWN: default: break; } return null; } public static Vector4d getUPlaneForFace(ForgeDirection face) { switch (face) { case DOWN: case UP: return new Vector4d(1, 0, 0, 0); case EAST: return new Vector4d(0, 0, -1, 1); case WEST: return new Vector4d(0, 0, 1, 0); case NORTH: return new Vector4d(-1, 0, 0, 1); case SOUTH: return new Vector4d(1, 0, 0, 0); case UNKNOWN: default: break; } return null; } private static class EdgeNeighbour { final ForgeDirection dir; final BlockCoord bc; public EdgeNeighbour(BlockCoord bc, ForgeDirection dir) { this.dir = dir; this.bc = bc.getLocation(dir); } } }
true
true
public static void renderConnectedTextureFace(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face, Icon texture, boolean forceAllEdges, boolean translateToXYZ, boolean applyFaceShading) { if(blockAccess == null || face == null || texture == null) { return; } if(!forceAllEdges) { int blockID = blockAccess.getBlockId(x, y, z); if(blockID <= 0 || Block.blocksList[blockID] == null) { return; } if(!Block.blocksList[blockID].shouldSideBeRendered(blockAccess, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())) { return; } } BlockCoord bc = new BlockCoord(x, y, z); List<ForgeDirection> edges; if(forceAllEdges) { edges = RenderUtil.getEdgesForFace(face); } else { edges = RenderUtil.getNonConectedEdgesForFace(blockAccess, x, y, z, face); } Tessellator tes = Tessellator.instance; tes.setNormal(face.offsetX, face.offsetY, face.offsetZ); if(applyFaceShading) { float cm = RenderUtil.getColorMultiplierForFace(face); tes.setColorOpaque_F(cm, cm, cm); } float scaleFactor = 15f / 16f; Vector2d uv = new Vector2d(); for (ForgeDirection edge : edges) { float xLen = 1 - Math.abs(edge.offsetX) * scaleFactor; float yLen = 1 - Math.abs(edge.offsetY) * scaleFactor; float zLen = 1 - Math.abs(edge.offsetZ) * scaleFactor; BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); List<Vector3f> corners = bb.getCornersForFace(face); for (Vector3f unitCorn : corners) { Vector3d corner = new Vector3d(unitCorn); if(translateToXYZ) { corner.x += x; corner.y += y; corner.z += z; } corner.x += (float) (edge.offsetX * 0.5) - Math.signum(edge.offsetX) * xLen / 2f; corner.y += (float) (edge.offsetY * 0.5) - Math.signum(edge.offsetY) * yLen / 2f; corner.z += (float) (edge.offsetZ * 0.5) - Math.signum(edge.offsetZ) * zLen / 2f; if(translateToXYZ) { RenderUtil.getUvForCorner(uv, corner, x, y, z, face, texture); } else { RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); } tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); } } }
public static void renderConnectedTextureFace(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face, Icon texture, boolean forceAllEdges, boolean translateToXYZ, boolean applyFaceShading) { if((blockAccess == null && !forceAllEdges) || face == null || texture == null) { return; } if(!forceAllEdges) { int blockID = blockAccess.getBlockId(x, y, z); if(blockID <= 0 || Block.blocksList[blockID] == null) { return; } if(!Block.blocksList[blockID].shouldSideBeRendered(blockAccess, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())) { return; } } BlockCoord bc = new BlockCoord(x, y, z); List<ForgeDirection> edges; if(forceAllEdges) { edges = RenderUtil.getEdgesForFace(face); } else { edges = RenderUtil.getNonConectedEdgesForFace(blockAccess, x, y, z, face); } Tessellator tes = Tessellator.instance; tes.setNormal(face.offsetX, face.offsetY, face.offsetZ); if(applyFaceShading) { float cm = RenderUtil.getColorMultiplierForFace(face); tes.setColorOpaque_F(cm, cm, cm); } float scaleFactor = 15f / 16f; Vector2d uv = new Vector2d(); for (ForgeDirection edge : edges) { float xLen = 1 - Math.abs(edge.offsetX) * scaleFactor; float yLen = 1 - Math.abs(edge.offsetY) * scaleFactor; float zLen = 1 - Math.abs(edge.offsetZ) * scaleFactor; BoundingBox bb = BoundingBox.UNIT_CUBE.scale(xLen, yLen, zLen); List<Vector3f> corners = bb.getCornersForFace(face); for (Vector3f unitCorn : corners) { Vector3d corner = new Vector3d(unitCorn); if(translateToXYZ) { corner.x += x; corner.y += y; corner.z += z; } corner.x += (float) (edge.offsetX * 0.5) - Math.signum(edge.offsetX) * xLen / 2f; corner.y += (float) (edge.offsetY * 0.5) - Math.signum(edge.offsetY) * yLen / 2f; corner.z += (float) (edge.offsetZ * 0.5) - Math.signum(edge.offsetZ) * zLen / 2f; if(translateToXYZ) { RenderUtil.getUvForCorner(uv, corner, x, y, z, face, texture); } else { RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture); } tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y); } } }
diff --git a/src/edu/gordian/values/expressions/NotEquals.java b/src/edu/gordian/values/expressions/NotEquals.java index bf3797e..6948505 100644 --- a/src/edu/gordian/values/expressions/NotEquals.java +++ b/src/edu/gordian/values/expressions/NotEquals.java @@ -1,21 +1,21 @@ package edu.gordian.values.expressions; import edu.gordian.Strings; import edu.gordian.scopes.Scope; import edu.gordian.values.gordian.GordianBoolean; public final class NotEquals extends GordianBoolean { public static boolean is(String v) { return Strings.contains(v, "!=") && v.indexOf("!=") > 0 && v.indexOf("!=") < v.length() - 2; } public static Equals valueOf(Scope s, String v) { - return new Equals(s.toValue(v.substring(0, v.indexOf("!="))).getValue(). + return new Equals(!s.toValue(v.substring(0, v.indexOf("!="))).getValue(). equals(s.toValue(v.substring(v.indexOf("!=") + 2)).getValue())); } public NotEquals(boolean value) { super(value); } }
true
true
public static Equals valueOf(Scope s, String v) { return new Equals(s.toValue(v.substring(0, v.indexOf("!="))).getValue(). equals(s.toValue(v.substring(v.indexOf("!=") + 2)).getValue())); }
public static Equals valueOf(Scope s, String v) { return new Equals(!s.toValue(v.substring(0, v.indexOf("!="))).getValue(). equals(s.toValue(v.substring(v.indexOf("!=") + 2)).getValue())); }
diff --git a/bndtools.core/src/bndtools/editor/pages/ResizeExpansionAdapter.java b/bndtools.core/src/bndtools/editor/pages/ResizeExpansionAdapter.java index 1cd2f336..a7496ce7 100644 --- a/bndtools.core/src/bndtools/editor/pages/ResizeExpansionAdapter.java +++ b/bndtools.core/src/bndtools/editor/pages/ResizeExpansionAdapter.java @@ -1,29 +1,29 @@ package bndtools.editor.pages; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.forms.events.ExpansionAdapter; import org.eclipse.ui.forms.events.ExpansionEvent; public class ResizeExpansionAdapter extends ExpansionAdapter { private final Composite layoutParent; private final Control control; public ResizeExpansionAdapter(Control control) { this(control.getParent(), control); } public ResizeExpansionAdapter(Composite layoutParent, Control control) { this.layoutParent = layoutParent; this.control = control; } @Override public void expansionStateChanged(ExpansionEvent e) { - Object layoutData = (e.data == Boolean.TRUE) ? PageLayoutUtils.createExpanded() : PageLayoutUtils.createCollapsed(); + Object layoutData = (Boolean.TRUE.equals(e.data)) ? PageLayoutUtils.createExpanded() : PageLayoutUtils.createCollapsed(); control.setLayoutData(layoutData); layoutParent.layout(true, true); } }
true
true
public void expansionStateChanged(ExpansionEvent e) { Object layoutData = (e.data == Boolean.TRUE) ? PageLayoutUtils.createExpanded() : PageLayoutUtils.createCollapsed(); control.setLayoutData(layoutData); layoutParent.layout(true, true); }
public void expansionStateChanged(ExpansionEvent e) { Object layoutData = (Boolean.TRUE.equals(e.data)) ? PageLayoutUtils.createExpanded() : PageLayoutUtils.createCollapsed(); control.setLayoutData(layoutData); layoutParent.layout(true, true); }
diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java index 0598b57c..1ce991b6 100644 --- a/Essentials/src/com/earth2me/essentials/User.java +++ b/Essentials/src/com/earth2me/essentials/User.java @@ -1,670 +1,672 @@ package com.earth2me.essentials; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.register.payment.Method; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class User extends UserData implements Comparable<User>, IReplyTo, IUser { private CommandSender replyTo = null; private transient User teleportRequester; private transient boolean teleportRequestHere; private transient boolean vanished; private transient final Teleport teleport; private transient long teleportRequestTime; private transient long lastOnlineActivity; private transient long lastActivity = System.currentTimeMillis(); private boolean hidden = false; private transient Location afkPosition = null; private boolean invSee = false; private static final Logger logger = Logger.getLogger("Minecraft"); User(final Player base, final IEssentials ess) { super(base, ess); teleport = new Teleport(this, ess); if (isAfk()) { afkPosition = getLocation(); } } User update(final Player base) { setBase(base); return this; } @Override public boolean isAuthorized(final IEssentialsCommand cmd) { return isAuthorized(cmd, "essentials."); } @Override public boolean isAuthorized(final IEssentialsCommand cmd, final String permissionPrefix) { return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName())); } @Override public boolean isAuthorized(final String node) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node); } if (base instanceof OfflinePlayer) { return false; } if (isOp()) { return true; } if (isJailed()) { return false; } try { return ess.getPermissionsHandler().hasPermission(base, node); } catch (Exception ex) { ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage()); return false; } } public void healCooldown() throws Exception { final Calendar now = new GregorianCalendar(); if (getLastHealTimestamp() > 0) { final double cooldown = ess.getSettings().getHealCooldown(); final Calendar cooldownTime = new GregorianCalendar(); cooldownTime.setTimeInMillis(getLastHealTimestamp()); cooldownTime.add(Calendar.SECOND, (int)cooldown); cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) { throw new Exception(_("timeBeforeHeal", Util.formatDateDiff(cooldownTime.getTimeInMillis()))); } } setLastHealTimestamp(now.getTimeInMillis()); } @Override public void giveMoney(final double value) { giveMoney(value, null); } public void giveMoney(final double value, final CommandSender initiator) { if (value == 0) { return; } setMoney(getMoney() + value); sendMessage(_("addedToAccount", Util.displayCurrency(value, ess))); if (initiator != null) { initiator.sendMessage(_("addedToOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName(), Util.displayCurrency(getMoney(), ess))); } } public void payUser(final User reciever, final double value) throws Exception { if (value == 0) { return; } if (canAfford(value)) { setMoney(getMoney() - value); reciever.setMoney(reciever.getMoney() + value); sendMessage(_("moneySentTo", Util.displayCurrency(value, ess), reciever.getDisplayName())); reciever.sendMessage(_("moneyRecievedFrom", Util.displayCurrency(value, ess), getDisplayName())); } else { throw new Exception(_("notEnoughMoney")); } } @Override public void takeMoney(final double value) { takeMoney(value, null); } public void takeMoney(final double value, final CommandSender initiator) { if (value == 0) { return; } setMoney(getMoney() - value); sendMessage(_("takenFromAccount", Util.displayCurrency(value, ess))); if (initiator != null) { initiator.sendMessage(_("takenFromOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName(), Util.displayCurrency(getMoney(), ess))); } } @Override public boolean canAfford(final double cost) { return canAfford(cost, true); } public boolean canAfford(final double cost, final boolean permcheck) { final double mon = getMoney(); if (!permcheck || isAuthorized("essentials.eco.loan")) { return (mon - cost) >= ess.getSettings().getMinMoney(); } return cost <= mon; } public void dispose() { this.base = new OfflinePlayer(getName(), ess); } @Override public void setReplyTo(final CommandSender user) { replyTo = user; } @Override public CommandSender getReplyTo() { return replyTo; } @Override public int compareTo(final User other) { return Util.stripFormat(this.getDisplayName()).compareToIgnoreCase(Util.stripFormat(other.getDisplayName())); } @Override public boolean equals(final Object object) { if (!(object instanceof User)) { return false; } return this.getName().equalsIgnoreCase(((User)object).getName()); } @Override public int hashCode() { return this.getName().hashCode(); } public Boolean canSpawnItem(final int itemId) { return !ess.getSettings().itemSpawnBlacklist().contains(itemId); } public Location getHome() throws Exception { return getHome(getHomes().get(0)); } public void setHome() { setHome("home", getLocation()); } public void setHome(final String name) { setHome(name, getLocation()); } @Override public void setLastLocation() { setLastLocation(getLocation()); } public void requestTeleport(final User player, final boolean here) { teleportRequestTime = System.currentTimeMillis(); teleportRequester = player; teleportRequestHere = here; } public User getTeleportRequest() { return teleportRequester; } public boolean isTpRequestHere() { return teleportRequestHere; } public String getNick(final boolean longnick) { final StringBuilder prefix = new StringBuilder(); String nickname; - String suffix = "§f"; + String suffix = ""; final String nick = getNickname(); if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) { nickname = getName(); } else { nickname = ess.getSettings().getNicknamePrefix() + nick; } if (isOp()) { try { final String opPrefix = ess.getSettings().getOperatorColor().toString(); if (opPrefix.length() > 0) { prefix.insert(0, opPrefix); + suffix = "§f"; } } catch (Exception e) { } } if (ess.getSettings().addPrefixSuffix()) { if (!ess.getSettings().disablePrefix()) { final String ptext = ess.getPermissionsHandler().getPrefix(base).replace('&', '§'); prefix.insert(0, ptext); + suffix = "§f"; } if (!ess.getSettings().disableSuffix()) { final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§'); suffix = stext + "§f"; suffix = suffix.replace("§f§f", "§f"); } } final String strPrefix = prefix.toString(); String output = strPrefix + nickname + suffix; if (!longnick && output.length() > 16) { output = strPrefix + nickname; } if (!longnick && output.length() > 16) { output = Util.lastCode(strPrefix) + nickname; } if (!longnick && output.length() > 16) { output = Util.lastCode(strPrefix) + nickname.substring(0, 14); } if (output.charAt(output.length() - 1) == '§') { output = output.substring(0, output.length() - 1); } return output; } public void setDisplayNick() { if (base.isOnline() && ess.getSettings().changeDisplayName()) { setDisplayName(getNick(true)); if (ess.getSettings().changePlayerListName()) { String name = getNick(false); try { setPlayerListName(name); } catch (IllegalArgumentException e) { if (ess.getSettings().isDebug()) { logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player."); } } } } } @Override public String getDisplayName() { return super.getDisplayName() == null ? super.getName() : super.getDisplayName(); } @Override public Teleport getTeleport() { return teleport; } public long getLastOnlineActivity() { return lastOnlineActivity; } public void setLastOnlineActivity(final long timestamp) { lastOnlineActivity = timestamp; } @Override public double getMoney() { if (ess.getPaymentMethod().hasMethod()) { try { final Method method = ess.getPaymentMethod().getMethod(); if (!method.hasAccount(this.getName())) { throw new Exception(); } final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); return account.balance(); } catch (Throwable ex) { } } return super.getMoney(); } @Override public void setMoney(final double value) { if (ess.getPaymentMethod().hasMethod()) { try { final Method method = ess.getPaymentMethod().getMethod(); if (!method.hasAccount(this.getName())) { throw new Exception(); } final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); account.set(value); } catch (Throwable ex) { } } super.setMoney(value); Trade.log("Update", "Set", "API", getName(), new Trade(value, ess), null, null, null, ess); } public void updateMoneyCache(final double value) { if (ess.getPaymentMethod().hasMethod() && super.getMoney() != value) { super.setMoney(value); } } @Override public void setAfk(final boolean set) { this.setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set); if (set && !isAfk()) { afkPosition = getLocation(); } else if (!set && isAfk()) { afkPosition = null; } super.setAfk(set); } @Override public boolean toggleAfk() { final boolean now = super.toggleAfk(); this.setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : now); return now; } @Override public boolean isHidden() { return hidden; } public void setHidden(final boolean hidden) { this.hidden = hidden; if (hidden == true) { setLastLogout(getLastOnlineActivity()); } } //Returns true if status expired during this check public boolean checkJailTimeout(final long currentTime) { if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed()) { setJailTimeout(0); setJailed(false); sendMessage(_("haveBeenReleased")); setJail(null); try { getTeleport().back(); } catch (Exception ex) { } return true; } return false; } //Returns true if status expired during this check public boolean checkMuteTimeout(final long currentTime) { if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) { setMuteTimeout(0); sendMessage(_("canTalkAgain")); setMuted(false); return true; } return false; } //Returns true if status expired during this check public boolean checkBanTimeout(final long currentTime) { if (getBanTimeout() > 0 && getBanTimeout() < currentTime && isBanned()) { setBanTimeout(0); setBanned(false); return true; } return false; } public void updateActivity(final boolean broadcast) { if (isAfk()) { setAfk(false); if (broadcast && !isHidden()) { setDisplayNick(); ess.broadcastMessage(this, _("userIsNotAway", getDisplayName())); } } lastActivity = System.currentTimeMillis(); } public void checkActivity() { final long autoafkkick = ess.getSettings().getAutoAfkKick(); if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis() && !isHidden() && !isAuthorized("essentials.kick.exempt") && !isAuthorized("essentials.afk.kickexempt")) { final String kickReason = _("autoAfkKickReason", autoafkkick / 60.0); lastActivity = 0; kickPlayer(kickReason); for (Player player : ess.getServer().getOnlinePlayers()) { final User user = ess.getUser(player); if (user.isAuthorized("essentials.kick.notify")) { player.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason)); } } } final long autoafk = ess.getSettings().getAutoAfk(); if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk")) { setAfk(true); if (!isHidden()) { setDisplayNick(); ess.broadcastMessage(this, _("userIsAway", getDisplayName())); } } } public Location getAfkPosition() { return afkPosition; } @Override public boolean isGodModeEnabled() { return (super.isGodModeEnabled() && !ess.getSettings().getNoGodWorlds().contains(getLocation().getWorld().getName())) || (isAfk() && ess.getSettings().getFreezeAfkPlayers()); } public boolean isGodModeEnabledRaw() { return super.isGodModeEnabled(); } @Override public String getGroup() { return ess.getPermissionsHandler().getGroup(base); } public boolean inGroup(final String group) { return ess.getPermissionsHandler().inGroup(base, group); } public boolean canBuild() { if (isOp()) { return true; } return ess.getPermissionsHandler().canBuild(base, getGroup()); } public long getTeleportRequestTime() { return teleportRequestTime; } public boolean isInvSee() { return invSee; } public void setInvSee(final boolean set) { invSee = set; } private transient long teleportInvulnerabilityTimestamp = 0; public void enableInvulnerabilityAfterTeleport() { final long time = ess.getSettings().getTeleportInvulnerability(); if (time > 0) { teleportInvulnerabilityTimestamp = System.currentTimeMillis() + time; } } public void resetInvulnerabilityAfterTeleport() { if (teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp < System.currentTimeMillis()) { teleportInvulnerabilityTimestamp = 0; } } public boolean hasInvulnerabilityAfterTeleport() { return teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp >= System.currentTimeMillis(); } public boolean isVanished() { return vanished; } public void setVanished(final boolean set) { vanished = set; if (set) { for (Player p : ess.getServer().getOnlinePlayers()) { if (!ess.getUser(p).isAuthorized("essentials.vanish.see")) { p.hidePlayer(getBase()); } } setHidden(true); ess.getVanishedPlayers().add(getName()); } else { for (Player p : ess.getServer().getOnlinePlayers()) { p.showPlayer(getBase()); } setHidden(false); ess.getVanishedPlayers().remove(getName()); } } public void toggleVanished() { final boolean set = !vanished; } }
false
true
public String getNick(final boolean longnick) { final StringBuilder prefix = new StringBuilder(); String nickname; String suffix = "§f"; final String nick = getNickname(); if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) { nickname = getName(); } else { nickname = ess.getSettings().getNicknamePrefix() + nick; } if (isOp()) { try { final String opPrefix = ess.getSettings().getOperatorColor().toString(); if (opPrefix.length() > 0) { prefix.insert(0, opPrefix); } } catch (Exception e) { } } if (ess.getSettings().addPrefixSuffix()) { if (!ess.getSettings().disablePrefix()) { final String ptext = ess.getPermissionsHandler().getPrefix(base).replace('&', '§'); prefix.insert(0, ptext); } if (!ess.getSettings().disableSuffix()) { final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§'); suffix = stext + "§f"; suffix = suffix.replace("§f§f", "§f"); } } final String strPrefix = prefix.toString(); String output = strPrefix + nickname + suffix; if (!longnick && output.length() > 16) { output = strPrefix + nickname; } if (!longnick && output.length() > 16) { output = Util.lastCode(strPrefix) + nickname; } if (!longnick && output.length() > 16) { output = Util.lastCode(strPrefix) + nickname.substring(0, 14); } if (output.charAt(output.length() - 1) == '§') { output = output.substring(0, output.length() - 1); } return output; }
public String getNick(final boolean longnick) { final StringBuilder prefix = new StringBuilder(); String nickname; String suffix = ""; final String nick = getNickname(); if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) { nickname = getName(); } else { nickname = ess.getSettings().getNicknamePrefix() + nick; } if (isOp()) { try { final String opPrefix = ess.getSettings().getOperatorColor().toString(); if (opPrefix.length() > 0) { prefix.insert(0, opPrefix); suffix = "§f"; } } catch (Exception e) { } } if (ess.getSettings().addPrefixSuffix()) { if (!ess.getSettings().disablePrefix()) { final String ptext = ess.getPermissionsHandler().getPrefix(base).replace('&', '§'); prefix.insert(0, ptext); suffix = "§f"; } if (!ess.getSettings().disableSuffix()) { final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§'); suffix = stext + "§f"; suffix = suffix.replace("§f§f", "§f"); } } final String strPrefix = prefix.toString(); String output = strPrefix + nickname + suffix; if (!longnick && output.length() > 16) { output = strPrefix + nickname; } if (!longnick && output.length() > 16) { output = Util.lastCode(strPrefix) + nickname; } if (!longnick && output.length() > 16) { output = Util.lastCode(strPrefix) + nickname.substring(0, 14); } if (output.charAt(output.length() - 1) == '§') { output = output.substring(0, output.length() - 1); } return output; }
diff --git a/src/main/java/org/elasticsearch/search/lookup/FieldsLookup.java b/src/main/java/org/elasticsearch/search/lookup/FieldsLookup.java index 543c7e6b8dc..9175dd1e69c 100644 --- a/src/main/java/org/elasticsearch/search/lookup/FieldsLookup.java +++ b/src/main/java/org/elasticsearch/search/lookup/FieldsLookup.java @@ -1,175 +1,173 @@ /* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search 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.elasticsearch.search.lookup; import com.google.common.collect.Maps; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.index.AtomicReaderContext; import org.elasticsearch.ElasticSearchIllegalArgumentException; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.lucene.document.SingleFieldVisitor; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.MapperService; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.Set; /** * */ public class FieldsLookup implements Map { private final MapperService mapperService; @Nullable private final String[] types; private AtomicReader reader; private int docId = -1; private final Map<String, FieldLookup> cachedFieldData = Maps.newHashMap(); private final SingleFieldVisitor fieldVisitor = new SingleFieldVisitor(); FieldsLookup(MapperService mapperService, @Nullable String[] types) { this.mapperService = mapperService; this.types = types; } public void setNextReader(AtomicReaderContext context) { if (this.reader == context.reader()) { // if we are called with the same reader, don't invalidate source return; } this.reader = context.reader(); clearCache(); this.docId = -1; } public void setNextDocId(int docId) { if (this.docId == docId) { // if we are called with the same docId, don't invalidate source return; } this.docId = docId; clearCache(); } @Override public Object get(Object key) { return loadFieldData(key.toString()); } @Override public boolean containsKey(Object key) { try { loadFieldData(key.toString()); return true; } catch (Exception e) { return false; } } @Override public int size() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public Set keySet() { throw new UnsupportedOperationException(); } @Override public Collection values() { throw new UnsupportedOperationException(); } @Override public Set entrySet() { throw new UnsupportedOperationException(); } @Override public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public Object remove(Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public void putAll(Map m) { throw new UnsupportedOperationException(); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } private FieldLookup loadFieldData(String name) { FieldLookup data = cachedFieldData.get(name); if (data == null) { FieldMapper mapper = mapperService.smartNameFieldMapper(name, types); if (mapper == null) { throw new ElasticSearchIllegalArgumentException("No field found for [" + name + "] in mapping with types " + Arrays.toString(types) + ""); } data = new FieldLookup(mapper); cachedFieldData.put(name, data); } if (data.doc() == null) { fieldVisitor.name(data.mapper().names().indexName()); try { reader.document(docId, fieldVisitor); // LUCENE 4 UPGRADE: Only one field we don't need document data.doc(fieldVisitor.createDocument()); } catch (IOException e) { throw new ElasticSearchParseException("failed to load field [" + name + "]", e); - } finally { - fieldVisitor.reset(); } } return data; } private void clearCache() { for (Entry<String, FieldLookup> entry : cachedFieldData.entrySet()) { entry.getValue().clear(); } } }
true
true
private FieldLookup loadFieldData(String name) { FieldLookup data = cachedFieldData.get(name); if (data == null) { FieldMapper mapper = mapperService.smartNameFieldMapper(name, types); if (mapper == null) { throw new ElasticSearchIllegalArgumentException("No field found for [" + name + "] in mapping with types " + Arrays.toString(types) + ""); } data = new FieldLookup(mapper); cachedFieldData.put(name, data); } if (data.doc() == null) { fieldVisitor.name(data.mapper().names().indexName()); try { reader.document(docId, fieldVisitor); // LUCENE 4 UPGRADE: Only one field we don't need document data.doc(fieldVisitor.createDocument()); } catch (IOException e) { throw new ElasticSearchParseException("failed to load field [" + name + "]", e); } finally { fieldVisitor.reset(); } } return data; }
private FieldLookup loadFieldData(String name) { FieldLookup data = cachedFieldData.get(name); if (data == null) { FieldMapper mapper = mapperService.smartNameFieldMapper(name, types); if (mapper == null) { throw new ElasticSearchIllegalArgumentException("No field found for [" + name + "] in mapping with types " + Arrays.toString(types) + ""); } data = new FieldLookup(mapper); cachedFieldData.put(name, data); } if (data.doc() == null) { fieldVisitor.name(data.mapper().names().indexName()); try { reader.document(docId, fieldVisitor); // LUCENE 4 UPGRADE: Only one field we don't need document data.doc(fieldVisitor.createDocument()); } catch (IOException e) { throw new ElasticSearchParseException("failed to load field [" + name + "]", e); } } return data; }
diff --git a/android/src/src/com/tech_tec/android/simplecalendar/model/PreviousMonth.java b/android/src/src/com/tech_tec/android/simplecalendar/model/PreviousMonth.java index 5557241..42ede08 100644 --- a/android/src/src/com/tech_tec/android/simplecalendar/model/PreviousMonth.java +++ b/android/src/src/com/tech_tec/android/simplecalendar/model/PreviousMonth.java @@ -1,48 +1,48 @@ package com.tech_tec.android.simplecalendar.model; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Iterator; public class PreviousMonth { private Month mMonth; private int mCount; PreviousMonth(Month month, int count) { mMonth = month; mCount = count; } public int getYear() { return getCalendar().get(Calendar.YEAR); } public int getMonth() { return getCalendar().get(Calendar.MONTH) + 1; } private Calendar getCalendar() { Calendar calendar = Calendar.getInstance(); calendar.set(mMonth.getYear(), mMonth.getMonth() - 1, 1); calendar.add(Calendar.MONTH, -1); return calendar; } public Iterator<Day> getDays() { Calendar calendar = getCalendar(); int maxDate = calendar.getActualMaximum(Calendar.DATE); calendar.set(Calendar.DATE, maxDate); ArrayList<Day> days = new ArrayList<Day>(); for (int i = 0; i < mCount; i++) { days.add(new Day(calendar.getTime())); - calendar.set(Calendar.DATE, -1); + calendar.add(Calendar.DATE, -1); } Collections.reverse(days); return days.iterator(); } }
true
true
public Iterator<Day> getDays() { Calendar calendar = getCalendar(); int maxDate = calendar.getActualMaximum(Calendar.DATE); calendar.set(Calendar.DATE, maxDate); ArrayList<Day> days = new ArrayList<Day>(); for (int i = 0; i < mCount; i++) { days.add(new Day(calendar.getTime())); calendar.set(Calendar.DATE, -1); } Collections.reverse(days); return days.iterator(); }
public Iterator<Day> getDays() { Calendar calendar = getCalendar(); int maxDate = calendar.getActualMaximum(Calendar.DATE); calendar.set(Calendar.DATE, maxDate); ArrayList<Day> days = new ArrayList<Day>(); for (int i = 0; i < mCount; i++) { days.add(new Day(calendar.getTime())); calendar.add(Calendar.DATE, -1); } Collections.reverse(days); return days.iterator(); }
diff --git a/src/com/android/contacts/ContactsListActivity.java b/src/com/android/contacts/ContactsListActivity.java index aeb401464..4169e3752 100644 --- a/src/com/android/contacts/ContactsListActivity.java +++ b/src/com/android/contacts/ContactsListActivity.java @@ -1,3566 +1,3568 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts; import com.android.contacts.TextHighlightingAnimation.TextWithHighlighting; import com.android.contacts.model.ContactsSource; import com.android.contacts.model.Sources; import com.android.contacts.ui.ContactsPreferences; import com.android.contacts.ui.ContactsPreferencesActivity; import com.android.contacts.ui.ContactsPreferencesActivity.Prefs; import com.android.contacts.util.AccountSelectionUtil; import com.android.contacts.util.Constants; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.IContentService; import android.content.Intent; import android.content.SharedPreferences; import android.content.UriMatcher; import android.content.res.ColorStateList; import android.content.res.Resources; import android.database.CharArrayBuffer; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.provider.Settings; import android.provider.Contacts.ContactMethods; import android.provider.Contacts.People; import android.provider.Contacts.PeopleColumns; import android.provider.Contacts.Phones; import android.provider.ContactsContract.ContactCounts; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.ProviderStatus; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.SearchSnippetColumns; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.Contacts.AggregationSuggestions; import android.provider.ContactsContract.Intents.Insert; import android.provider.ContactsContract.Intents.UI; import android.telephony.TelephonyManager; import android.text.Editable; import android.text.Html; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.ContextThemeWrapper; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.QuickContactBadge; import android.widget.SectionIndexer; import android.widget.TextView; import android.widget.Toast; import android.widget.AbsListView.OnScrollListener; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Displays a list of contacts. Usually is embedded into the ContactsActivity. */ @SuppressWarnings("deprecation") public class ContactsListActivity extends ListActivity implements View.OnCreateContextMenuListener, View.OnClickListener, View.OnKeyListener, TextWatcher, TextView.OnEditorActionListener, OnFocusChangeListener, OnTouchListener { public static class JoinContactActivity extends ContactsListActivity { } public static class ContactsSearchActivity extends ContactsListActivity { } private static final String TAG = "ContactsListActivity"; private static final boolean ENABLE_ACTION_ICON_OVERLAYS = true; private static final String LIST_STATE_KEY = "liststate"; private static final String SHORTCUT_ACTION_KEY = "shortcutAction"; static final int MENU_ITEM_VIEW_CONTACT = 1; static final int MENU_ITEM_CALL = 2; static final int MENU_ITEM_EDIT_BEFORE_CALL = 3; static final int MENU_ITEM_SEND_SMS = 4; static final int MENU_ITEM_SEND_IM = 5; static final int MENU_ITEM_EDIT = 6; static final int MENU_ITEM_DELETE = 7; static final int MENU_ITEM_TOGGLE_STAR = 8; private static final int SUBACTIVITY_NEW_CONTACT = 1; private static final int SUBACTIVITY_VIEW_CONTACT = 2; private static final int SUBACTIVITY_DISPLAY_GROUP = 3; private static final int SUBACTIVITY_SEARCH = 4; private static final int SUBACTIVITY_FILTER = 5; private static final int TEXT_HIGHLIGHTING_ANIMATION_DURATION = 350; /** * The action for the join contact activity. * <p> * Input: extra field {@link #EXTRA_AGGREGATE_ID} is the aggregate ID. * * TODO: move to {@link ContactsContract}. */ public static final String JOIN_AGGREGATE = "com.android.contacts.action.JOIN_AGGREGATE"; /** * Used with {@link #JOIN_AGGREGATE} to give it the target for aggregation. * <p> * Type: LONG */ public static final String EXTRA_AGGREGATE_ID = "com.android.contacts.action.AGGREGATE_ID"; /** * Used with {@link #JOIN_AGGREGATE} to give it the name of the aggregation target. * <p> * Type: STRING */ @Deprecated public static final String EXTRA_AGGREGATE_NAME = "com.android.contacts.action.AGGREGATE_NAME"; public static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final Uri CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS = buildSectionIndexerUri(Contacts.CONTENT_URI); /** Mask for picker mode */ static final int MODE_MASK_PICKER = 0x80000000; /** Mask for no presence mode */ static final int MODE_MASK_NO_PRESENCE = 0x40000000; /** Mask for enabling list filtering */ static final int MODE_MASK_NO_FILTER = 0x20000000; /** Mask for having a "create new contact" header in the list */ static final int MODE_MASK_CREATE_NEW = 0x10000000; /** Mask for showing photos in the list */ static final int MODE_MASK_SHOW_PHOTOS = 0x08000000; /** Mask for hiding additional information e.g. primary phone number in the list */ static final int MODE_MASK_NO_DATA = 0x04000000; /** Mask for showing a call button in the list */ static final int MODE_MASK_SHOW_CALL_BUTTON = 0x02000000; /** Mask to disable quickcontact (images will show as normal images) */ static final int MODE_MASK_DISABLE_QUIKCCONTACT = 0x01000000; /** Mask to show the total number of contacts at the top */ static final int MODE_MASK_SHOW_NUMBER_OF_CONTACTS = 0x00800000; /** Unknown mode */ static final int MODE_UNKNOWN = 0; /** Default mode */ static final int MODE_DEFAULT = 4 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Custom mode */ static final int MODE_CUSTOM = 8; /** Show all starred contacts */ static final int MODE_STARRED = 20 | MODE_MASK_SHOW_PHOTOS; /** Show frequently contacted contacts */ static final int MODE_FREQUENT = 30 | MODE_MASK_SHOW_PHOTOS; /** Show starred and the frequent */ static final int MODE_STREQUENT = 35 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_SHOW_CALL_BUTTON; /** Show all contacts and pick them when clicking */ static final int MODE_PICK_CONTACT = 40 | MODE_MASK_PICKER | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all contacts as well as the option to create a new one */ static final int MODE_PICK_OR_CREATE_CONTACT = 42 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all people through the legacy provider and pick them when clicking */ static final int MODE_LEGACY_PICK_PERSON = 43 | MODE_MASK_PICKER | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all people through the legacy provider as well as the option to create a new one */ static final int MODE_LEGACY_PICK_OR_CREATE_PERSON = 44 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all contacts and pick them when clicking, and allow creating a new contact */ static final int MODE_INSERT_OR_EDIT_CONTACT = 45 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all phone numbers and pick them when clicking */ static final int MODE_PICK_PHONE = 50 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE; /** Show all phone numbers through the legacy provider and pick them when clicking */ static final int MODE_LEGACY_PICK_PHONE = 51 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; /** Show all postal addresses and pick them when clicking */ static final int MODE_PICK_POSTAL = 55 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; /** Show all postal addresses and pick them when clicking */ static final int MODE_LEGACY_PICK_POSTAL = 56 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; static final int MODE_GROUP = 57 | MODE_MASK_SHOW_PHOTOS; /** Run a search query */ static final int MODE_QUERY = 60 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_NO_FILTER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in PICK mode, but that still launches to VIEW */ static final int MODE_QUERY_PICK_TO_VIEW = 65 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Show join suggestions followed by an A-Z list */ static final int MODE_JOIN_CONTACT = 70 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_DATA | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Run a search query in a PICK mode */ static final int MODE_QUERY_PICK = 75 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_NO_FILTER | MODE_MASK_PICKER | MODE_MASK_DISABLE_QUIKCCONTACT | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in a PICK_PHONE mode */ static final int MODE_QUERY_PICK_PHONE = 80 | MODE_MASK_NO_FILTER | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in PICK mode, but that still launches to EDIT */ static final int MODE_QUERY_PICK_TO_EDIT = 85 | MODE_MASK_NO_FILTER | MODE_MASK_SHOW_PHOTOS | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** * An action used to do perform search while in a contact picker. It is initiated * by the ContactListActivity itself. */ private static final String ACTION_SEARCH_INTERNAL = "com.android.contacts.INTERNAL_SEARCH"; /** Maximum number of suggestions shown for joining aggregates */ static final int MAX_SUGGESTIONS = 4; static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 Contacts.HAS_PHONE_NUMBER, // 10 }; static final String[] CONTACTS_SUMMARY_PROJECTION_FROM_EMAIL = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 // email lookup doesn't included HAS_PHONE_NUMBER in projection }; static final String[] CONTACTS_SUMMARY_FILTER_PROJECTION = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 Contacts.HAS_PHONE_NUMBER, // 10 SearchSnippetColumns.SNIPPET_MIMETYPE, // 11 SearchSnippetColumns.SNIPPET_DATA1, // 12 SearchSnippetColumns.SNIPPET_DATA4, // 13 }; static final String[] LEGACY_PEOPLE_PROJECTION = new String[] { People._ID, // 0 People.DISPLAY_NAME, // 1 People.DISPLAY_NAME, // 2 People.DISPLAY_NAME, // 3 People.STARRED, // 4 PeopleColumns.TIMES_CONTACTED, // 5 People.PRESENCE_STATUS, // 6 }; static final int SUMMARY_ID_COLUMN_INDEX = 0; static final int SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX = 1; static final int SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX = 2; static final int SUMMARY_SORT_KEY_PRIMARY_COLUMN_INDEX = 3; static final int SUMMARY_STARRED_COLUMN_INDEX = 4; static final int SUMMARY_TIMES_CONTACTED_COLUMN_INDEX = 5; static final int SUMMARY_PRESENCE_STATUS_COLUMN_INDEX = 6; static final int SUMMARY_PHOTO_ID_COLUMN_INDEX = 7; static final int SUMMARY_LOOKUP_KEY_COLUMN_INDEX = 8; static final int SUMMARY_PHONETIC_NAME_COLUMN_INDEX = 9; static final int SUMMARY_HAS_PHONE_COLUMN_INDEX = 10; static final int SUMMARY_SNIPPET_MIMETYPE_COLUMN_INDEX = 11; static final int SUMMARY_SNIPPET_DATA1_COLUMN_INDEX = 12; static final int SUMMARY_SNIPPET_DATA4_COLUMN_INDEX = 13; static final String[] PHONES_PROJECTION = new String[] { Phone._ID, //0 Phone.TYPE, //1 Phone.LABEL, //2 Phone.NUMBER, //3 Phone.DISPLAY_NAME, // 4 Phone.CONTACT_ID, // 5 }; static final String[] LEGACY_PHONES_PROJECTION = new String[] { Phones._ID, //0 Phones.TYPE, //1 Phones.LABEL, //2 Phones.NUMBER, //3 People.DISPLAY_NAME, // 4 }; static final int PHONE_ID_COLUMN_INDEX = 0; static final int PHONE_TYPE_COLUMN_INDEX = 1; static final int PHONE_LABEL_COLUMN_INDEX = 2; static final int PHONE_NUMBER_COLUMN_INDEX = 3; static final int PHONE_DISPLAY_NAME_COLUMN_INDEX = 4; static final int PHONE_CONTACT_ID_COLUMN_INDEX = 5; static final String[] POSTALS_PROJECTION = new String[] { StructuredPostal._ID, //0 StructuredPostal.TYPE, //1 StructuredPostal.LABEL, //2 StructuredPostal.DATA, //3 StructuredPostal.DISPLAY_NAME, // 4 }; static final String[] LEGACY_POSTALS_PROJECTION = new String[] { ContactMethods._ID, //0 ContactMethods.TYPE, //1 ContactMethods.LABEL, //2 ContactMethods.DATA, //3 People.DISPLAY_NAME, // 4 }; static final String[] RAW_CONTACTS_PROJECTION = new String[] { RawContacts._ID, //0 RawContacts.CONTACT_ID, //1 RawContacts.ACCOUNT_TYPE, //2 }; static final int POSTAL_ID_COLUMN_INDEX = 0; static final int POSTAL_TYPE_COLUMN_INDEX = 1; static final int POSTAL_LABEL_COLUMN_INDEX = 2; static final int POSTAL_ADDRESS_COLUMN_INDEX = 3; static final int POSTAL_DISPLAY_NAME_COLUMN_INDEX = 4; private static final int QUERY_TOKEN = 42; static final String KEY_PICKER_MODE = "picker_mode"; private ContactItemListAdapter mAdapter; int mMode = MODE_DEFAULT; private QueryHandler mQueryHandler; private boolean mJustCreated; private boolean mSyncEnabled; Uri mSelectedContactUri; // private boolean mDisplayAll; private boolean mDisplayOnlyPhones; private Uri mGroupUri; private long mQueryAggregateId; private ArrayList<Long> mWritableRawContactIds = new ArrayList<Long>(); private int mWritableSourcesCnt; private int mReadOnlySourcesCnt; /** * Used to keep track of the scroll state of the list. */ private Parcelable mListState = null; private String mShortcutAction; /** * Internal query type when in mode {@link #MODE_QUERY_PICK_TO_VIEW}. */ private int mQueryMode = QUERY_MODE_NONE; private static final int QUERY_MODE_NONE = -1; private static final int QUERY_MODE_MAILTO = 1; private static final int QUERY_MODE_TEL = 2; private int mProviderStatus = ProviderStatus.STATUS_NORMAL; private boolean mSearchMode; private boolean mSearchResultsMode; private boolean mShowNumberOfContacts; private boolean mShowSearchSnippets; private boolean mSearchInitiated; private String mInitialFilter; private static final String CLAUSE_ONLY_VISIBLE = Contacts.IN_VISIBLE_GROUP + "=1"; private static final String CLAUSE_ONLY_PHONES = Contacts.HAS_PHONE_NUMBER + "=1"; /** * In the {@link #MODE_JOIN_CONTACT} determines whether we display a list item with the label * "Show all contacts" or actually show all contacts */ private boolean mJoinModeShowAllContacts; /** * The ID of the special item described above. */ private static final long JOIN_MODE_SHOW_ALL_CONTACTS_ID = -2; // Uri matcher for contact id private static final int CONTACTS_ID = 1001; private static final UriMatcher sContactsIdMatcher; private ContactPhotoLoader mPhotoLoader; final String[] sLookupProjection = new String[] { Contacts.LOOKUP_KEY }; static { sContactsIdMatcher = new UriMatcher(UriMatcher.NO_MATCH); sContactsIdMatcher.addURI(ContactsContract.AUTHORITY, "contacts/#", CONTACTS_ID); } private class DeleteClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { if (mSelectedContactUri != null) { getContentResolver().delete(mSelectedContactUri, null, null); } } } /** * A {@link TextHighlightingAnimation} that redraws just the contact display name in a * list item. */ private static class NameHighlightingAnimation extends TextHighlightingAnimation { private final ListView mListView; private NameHighlightingAnimation(ListView listView, int duration) { super(duration); this.mListView = listView; } /** * Redraws all visible items of the list corresponding to contacts */ @Override protected void invalidate() { int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i++) { View itemView = mListView.getChildAt(i); if (itemView instanceof ContactListItemView) { final ContactListItemView view = (ContactListItemView)itemView; view.getNameTextView().invalidate(); } } } @Override protected void onAnimationStarted() { mListView.setScrollingCacheEnabled(false); } @Override protected void onAnimationEnded() { mListView.setScrollingCacheEnabled(true); } } // The size of a home screen shortcut icon. private int mIconSize; private ContactsPreferences mContactsPrefs; private int mDisplayOrder; private int mSortOrder; private boolean mHighlightWhenScrolling; private TextHighlightingAnimation mHighlightingAnimation; private SearchEditText mSearchEditText; /** * An approximation of the background color of the pinned header. This color * is used when the pinned header is being pushed up. At that point the header * "fades away". Rather than computing a faded bitmap based on the 9-patch * normally used for the background, we will use a solid color, which will * provide better performance and reduced complexity. */ private int mPinnedHeaderBackgroundColor; private ContentObserver mProviderStatusObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { checkProviderState(true); } }; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size); mContactsPrefs = new ContactsPreferences(this); mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } String action = intent.getAction(); String component = intent.getComponent().getClassName(); // When we get a FILTER_CONTACTS_ACTION, it represents search in the context // of some other action. Let's retrieve the original action to provide proper // context for the search queries. if (UI.FILTER_CONTACTS_ACTION.equals(action)) { mSearchMode = true; mShowSearchSnippets = true; Bundle extras = intent.getExtras(); if (extras != null) { mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY); String originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); if (originalAction != null) { action = originalAction; } String originalComponent = extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY); if (originalComponent != null) { component = originalComponent; } } else { mInitialFilter = null; } } Log.i(TAG, "Called with action: " + action); mMode = MODE_UNKNOWN; if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) { mMode = MODE_DEFAULT; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUri(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = false; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = true; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (Contacts.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PERSON; } else if (Phone.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (component.equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; + mShowSearchSnippets = false; setTitle(R.string.callShortcutActivityTitle); } else if (component.equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; + mShowSearchSnippets = false; setTitle(R.string.messageShortcutActivityTitle); } else if (mSearchMode) { mMode = MODE_PICK_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (Contacts.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_PICK_OR_CREATE_CONTACT; } } else if (Phone.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } else if (People.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_LEGACY_PICK_PERSON; } else { mMode = MODE_LEGACY_PICK_OR_CREATE_PERSON; } } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mInitialFilter = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; } else if (ACTION_SEARCH_INTERNAL.equals(action)) { String originalAction = null; Bundle extras = intent.getExtras(); if (extras != null) { originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); } mShortcutAction = intent.getStringExtra(SHORTCUT_ACTION_KEY); if (Intent.ACTION_INSERT_OR_EDIT.equals(originalAction)) { mMode = MODE_QUERY_PICK_TO_EDIT; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } else if (mShortcutAction != null && intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_PHONE; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { mMode = MODE_QUERY_PICK; mQueryMode = QUERY_MODE_NONE; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { Uri data = intent.getData(); Uri telUri = null; if (sContactsIdMatcher.match(data) == CONTACTS_ID) { long contactId = Long.valueOf(data.getLastPathSegment()); final Cursor cursor = queryPhoneNumbers(contactId); if (cursor != null) { if (cursor.getCount() == 1 && cursor.moveToFirst()) { int phoneNumberIndex = cursor.getColumnIndex(Phone.NUMBER); String phoneNumber = cursor.getString(phoneNumberIndex); telUri = Uri.parse("tel:" + phoneNumber); } cursor.close(); } } // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG)) && telUri != null) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, telUri); } else { newIntent = new Intent(Intent.ACTION_VIEW, data); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { // TODO actually support this in EditContactActivity. String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (JOIN_AGGREGATE.equals(action)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_JOIN_CONTACT; mQueryAggregateId = intent.getLongExtra(EXTRA_AGGREGATE_ID, -1); if (mQueryAggregateId == -1) { Log.e(TAG, "Intent " + action + " is missing required extra: " + EXTRA_AGGREGATE_ID); setResult(RESULT_CANCELED); finish(); } } } if (mMode == MODE_UNKNOWN) { mMode = MODE_DEFAULT; } if (((mMode & MODE_MASK_SHOW_NUMBER_OF_CONTACTS) != 0 || mSearchMode) && !mSearchResultsMode) { mShowNumberOfContacts = true; } if (mMode == MODE_JOIN_CONTACT) { setContentView(R.layout.contacts_list_content_join); TextView blurbView = (TextView)findViewById(R.id.join_contact_blurb); String blurb = getString(R.string.blurbJoinContactDataWith, getContactDisplayName(mQueryAggregateId)); blurbView.setText(blurb); mJoinModeShowAllContacts = true; } else if (mSearchMode) { setContentView(R.layout.contacts_search_content); } else if (mSearchResultsMode) { setContentView(R.layout.contacts_list_search_results); TextView titleText = (TextView)findViewById(R.id.search_results_for); titleText.setText(Html.fromHtml(getString(R.string.search_results_for, "<b>" + mInitialFilter + "</b>"))); } else { setContentView(R.layout.contacts_list_content); } setupListView(); if (mSearchMode) { setupSearchView(); } mQueryHandler = new QueryHandler(this); mJustCreated = true; mSyncEnabled = true; } /** * Register an observer for provider status changes - we will need to * reflect them in the UI. */ private void registerProviderStatusObserver() { getContentResolver().registerContentObserver(ProviderStatus.CONTENT_URI, false, mProviderStatusObserver); } /** * Register an observer for provider status changes - we will need to * reflect them in the UI. */ private void unregisterProviderStatusObserver() { getContentResolver().unregisterContentObserver(mProviderStatusObserver); } private void setupListView() { final ListView list = getListView(); final LayoutInflater inflater = getLayoutInflater(); mHighlightingAnimation = new NameHighlightingAnimation(list, TEXT_HIGHLIGHTING_ANIMATION_DURATION); // Tell list view to not show dividers. We'll do it ourself so that we can *not* show // them when an A-Z headers is visible. list.setDividerHeight(0); list.setOnCreateContextMenuListener(this); mAdapter = new ContactItemListAdapter(this); setListAdapter(mAdapter); if (list instanceof PinnedHeaderListView && mAdapter.getDisplaySectionHeadersEnabled()) { mPinnedHeaderBackgroundColor = getResources().getColor(R.color.pinned_header_background); PinnedHeaderListView pinnedHeaderList = (PinnedHeaderListView)list; View pinnedHeader = inflater.inflate(R.layout.list_section, list, false); pinnedHeaderList.setPinnedHeaderView(pinnedHeader); } list.setOnScrollListener(mAdapter); list.setOnKeyListener(this); list.setOnFocusChangeListener(this); list.setOnTouchListener(this); // We manually save/restore the listview state list.setSaveEnabled(false); } /** * Configures search UI. */ private void setupSearchView() { mSearchEditText = (SearchEditText)findViewById(R.id.search_src_text); mSearchEditText.addTextChangedListener(this); mSearchEditText.setOnEditorActionListener(this); mSearchEditText.setText(mInitialFilter); } private String getContactDisplayName(long contactId) { String contactName = null; Cursor c = getContentResolver().query( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), new String[] {Contacts.DISPLAY_NAME}, null, null, null); try { if (c != null && c.moveToFirst()) { contactName = c.getString(0); } } finally { if (c != null) { c.close(); } } if (contactName == null) { contactName = ""; } return contactName; } private int getSummaryDisplayNameColumnIndex() { if (mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { return SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX; } else { return SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX; } } /** {@inheritDoc} */ public void onClick(View v) { int id = v.getId(); switch (id) { // TODO a better way of identifying the button case android.R.id.button1: { final int position = (Integer)v.getTag(); Cursor c = mAdapter.getCursor(); if (c != null) { c.moveToPosition(position); callContact(c); } break; } } } private void setEmptyText() { if (mMode == MODE_JOIN_CONTACT || mSearchMode) { return; } TextView empty = (TextView) findViewById(R.id.emptyText); if (mDisplayOnlyPhones) { empty.setText(getText(R.string.noContactsWithPhoneNumbers)); } else if (mMode == MODE_STREQUENT || mMode == MODE_STARRED) { empty.setText(getText(R.string.noFavoritesHelpText)); } else if (mMode == MODE_QUERY || mMode == MODE_QUERY_PICK || mMode == MODE_QUERY_PICK_PHONE || mMode == MODE_QUERY_PICK_TO_VIEW || mMode == MODE_QUERY_PICK_TO_EDIT) { empty.setText(getText(R.string.noMatchingContacts)); } else { boolean hasSim = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)) .hasIccCard(); boolean createShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction()); if (isSyncActive()) { if (createShortcut) { // Help text is the same no matter whether there is SIM or not. empty.setText(getText(R.string.noContactsHelpTextWithSyncForCreateShortcut)); } else if (hasSim) { empty.setText(getText(R.string.noContactsHelpTextWithSync)); } else { empty.setText(getText(R.string.noContactsNoSimHelpTextWithSync)); } } else { if (createShortcut) { // Help text is the same no matter whether there is SIM or not. empty.setText(getText(R.string.noContactsHelpTextForCreateShortcut)); } else if (hasSim) { empty.setText(getText(R.string.noContactsHelpText)); } else { empty.setText(getText(R.string.noContactsNoSimHelpText)); } } } } private boolean isSyncActive() { Account[] accounts = AccountManager.get(this).getAccounts(); if (accounts != null && accounts.length > 0) { IContentService contentService = ContentResolver.getContentService(); for (Account account : accounts) { try { if (contentService.isSyncActive(account, ContactsContract.AUTHORITY)) { return true; } } catch (RemoteException e) { Log.e(TAG, "Could not get the sync status"); } } } return false; } private void buildUserGroupUri(String group) { mGroupUri = Uri.withAppendedPath(Contacts.CONTENT_GROUP_URI, group); } /** * Sets the mode when the request is for "default" */ private void setDefaultMode() { // Load the preferences SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mDisplayOnlyPhones = prefs.getBoolean(Prefs.DISPLAY_ONLY_PHONES, Prefs.DISPLAY_ONLY_PHONES_DEFAULT); } @Override protected void onDestroy() { super.onDestroy(); mPhotoLoader.stop(); } @Override protected void onPause() { super.onPause(); unregisterProviderStatusObserver(); } @Override protected void onResume() { super.onResume(); registerProviderStatusObserver(); mPhotoLoader.resume(); Activity parent = getParent(); // Do this before setting the filter. The filter thread relies // on some state that is initialized in setDefaultMode if (mMode == MODE_DEFAULT) { // If we're in default mode we need to possibly reset the mode due to a change // in the preferences activity while we weren't running setDefaultMode(); } // See if we were invoked with a filter if (mSearchMode) { mSearchEditText.requestFocus(); } if (!mSearchMode && !checkProviderState(mJustCreated)) { return; } if (mJustCreated) { // We need to start a query here the first time the activity is launched, as long // as we aren't doing a filter. startQuery(); } mJustCreated = false; mSearchInitiated = false; } /** * Obtains the contacts provider status and configures the UI accordingly. * * @param loadData true if the method needs to start a query when the * provider is in the normal state * @return true if the provider status is normal */ private boolean checkProviderState(boolean loadData) { View importFailureView = findViewById(R.id.import_failure); if (importFailureView == null) { return true; } TextView messageView = (TextView) findViewById(R.id.emptyText); // This query can be performed on the UI thread because // the API explicitly allows such use. Cursor cursor = getContentResolver().query(ProviderStatus.CONTENT_URI, new String[] { ProviderStatus.STATUS, ProviderStatus.DATA1 }, null, null, null); try { if (cursor.moveToFirst()) { int status = cursor.getInt(0); if (status != mProviderStatus) { mProviderStatus = status; switch (status) { case ProviderStatus.STATUS_NORMAL: mAdapter.notifyDataSetInvalidated(); if (loadData) { startQuery(); } break; case ProviderStatus.STATUS_CHANGING_LOCALE: messageView.setText(R.string.locale_change_in_progress); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; case ProviderStatus.STATUS_UPGRADING: messageView.setText(R.string.upgrade_in_progress); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; case ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY: long size = cursor.getLong(1); String message = getResources().getString( R.string.upgrade_out_of_memory, new Object[] {size}); messageView.setText(message); configureImportFailureView(importFailureView); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; } } } } finally { cursor.close(); } importFailureView.setVisibility( mProviderStatus == ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY ? View.VISIBLE : View.GONE); return mProviderStatus == ProviderStatus.STATUS_NORMAL; } private void configureImportFailureView(View importFailureView) { OnClickListener listener = new OnClickListener(){ public void onClick(View v) { switch(v.getId()) { case R.id.import_failure_uninstall_apps: { startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS)); break; } case R.id.import_failure_retry_upgrade: { // Send a provider status update, which will trigger a retry ContentValues values = new ContentValues(); values.put(ProviderStatus.STATUS, ProviderStatus.STATUS_UPGRADING); getContentResolver().update(ProviderStatus.CONTENT_URI, values, null, null); break; } } }}; Button uninstallApps = (Button) findViewById(R.id.import_failure_uninstall_apps); uninstallApps.setOnClickListener(listener); Button retryUpgrade = (Button) findViewById(R.id.import_failure_retry_upgrade); retryUpgrade.setOnClickListener(listener); } private String getTextFilter() { if (mSearchEditText != null) { return mSearchEditText.getText().toString(); } return null; } @Override protected void onRestart() { super.onRestart(); if (!checkProviderState(false)) { return; } // The cursor was killed off in onStop(), so we need to get a new one here // We do not perform the query if a filter is set on the list because the // filter will cause the query to happen anyway if (TextUtils.isEmpty(getTextFilter())) { startQuery(); } else { // Run the filtered query on the adapter mAdapter.onContentChanged(); } } @Override protected void onSaveInstanceState(Bundle icicle) { super.onSaveInstanceState(icicle); // Save list state in the bundle so we can restore it after the QueryHandler has run if (mList != null) { icicle.putParcelable(LIST_STATE_KEY, mList.onSaveInstanceState()); } } @Override protected void onRestoreInstanceState(Bundle icicle) { super.onRestoreInstanceState(icicle); // Retrieve list state. This will be applied after the QueryHandler has run mListState = icicle.getParcelable(LIST_STATE_KEY); } @Override protected void onStop() { super.onStop(); mAdapter.setSuggestionsCursor(null); mAdapter.changeCursor(null); if (mMode == MODE_QUERY) { // Make sure the search box is closed SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchManager.stopSearch(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the options menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return false; } MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { final boolean defaultMode = (mMode == MODE_DEFAULT); menu.findItem(R.id.menu_display_groups).setVisible(defaultMode); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_display_groups: { final Intent intent = new Intent(this, ContactsPreferencesActivity.class); startActivityForResult(intent, SUBACTIVITY_DISPLAY_GROUP); return true; } case R.id.menu_search: { onSearchRequested(); return true; } case R.id.menu_add: { final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); startActivity(intent); return true; } case R.id.menu_import_export: { displayImportExportDialog(); return true; } case R.id.menu_accounts: { final Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS); intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { ContactsContract.AUTHORITY }); startActivity(intent); return true; } } return false; } @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { if (mProviderStatus != ProviderStatus.STATUS_NORMAL) { return; } if (globalSearch) { super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); } else { if (!mSearchMode && (mMode & MODE_MASK_NO_FILTER) == 0) { if ((mMode & MODE_MASK_PICKER) != 0) { ContactsSearchManager.startSearchForResult(this, initialQuery, SUBACTIVITY_FILTER); } else { ContactsSearchManager.startSearch(this, initialQuery); } } } } /** * Performs filtering of the list based on the search query entered in the * search text edit. */ protected void onSearchTextChanged() { // Set the proper empty string setEmptyText(); Filter filter = mAdapter.getFilter(); filter.filter(getTextFilter()); } /** * Starts a new activity that will run a search query and display search results. */ private void doSearch() { String query = getTextFilter(); if (TextUtils.isEmpty(query)) { return; } Intent intent = new Intent(this, SearchResultsActivity.class); Intent originalIntent = getIntent(); Bundle originalExtras = originalIntent.getExtras(); if (originalExtras != null) { intent.putExtras(originalExtras); } intent.putExtra(SearchManager.QUERY, query); if ((mMode & MODE_MASK_PICKER) != 0) { intent.setAction(ACTION_SEARCH_INTERNAL); intent.putExtra(SHORTCUT_ACTION_KEY, mShortcutAction); if (mShortcutAction != null) { if (Intent.ACTION_CALL.equals(mShortcutAction) || Intent.ACTION_SENDTO.equals(mShortcutAction)) { intent.putExtra(Insert.PHONE, query); } } else { switch (mQueryMode) { case QUERY_MODE_MAILTO: intent.putExtra(Insert.EMAIL, query); break; case QUERY_MODE_TEL: intent.putExtra(Insert.PHONE, query); break; } } startActivityForResult(intent, SUBACTIVITY_SEARCH); } else { intent.setAction(Intent.ACTION_SEARCH); startActivity(intent); } } @Override protected Dialog onCreateDialog(int id, Bundle bundle) { switch (id) { case R.string.import_from_sim: case R.string.import_from_sdcard: { return AccountSelectionUtil.getSelectAccountDialog(this, id); } case R.id.dialog_sdcard_not_found: { return new AlertDialog.Builder(this) .setTitle(R.string.no_sdcard_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.no_sdcard_message) .setPositiveButton(android.R.string.ok, null).create(); } case R.id.dialog_delete_contact_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.deleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_readonly_contact_hide_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactWarning) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_readonly_contact_delete_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_multiple_contact_delete_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.multipleContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } } return super.onCreateDialog(id, bundle); } /** * Create a {@link Dialog} that allows the user to pick from a bulk import * or bulk export task across all contacts. */ private void displayImportExportDialog() { // Wrap our context to inflate list items using correct theme final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final Resources res = dialogContext.getResources(); final LayoutInflater dialogInflater = (LayoutInflater)dialogContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Adapter that shows a list of string resources final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_list_item_1) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } final int resId = this.getItem(position); ((TextView)convertView).setText(resId); return convertView; } }; if (TelephonyManager.getDefault().hasIccCard()) { adapter.add(R.string.import_from_sim); } if (res.getBoolean(R.bool.config_allow_import_from_sdcard)) { adapter.add(R.string.import_from_sdcard); } if (res.getBoolean(R.bool.config_allow_export_to_sdcard)) { adapter.add(R.string.export_to_sdcard); } if (res.getBoolean(R.bool.config_allow_share_visible_contacts)) { adapter.add(R.string.share_visible_contacts); } final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); final int resId = adapter.getItem(which); switch (resId) { case R.string.import_from_sim: case R.string.import_from_sdcard: { handleImportRequest(resId); break; } case R.string.export_to_sdcard: { Context context = ContactsListActivity.this; Intent exportIntent = new Intent(context, ExportVCardActivity.class); context.startActivity(exportIntent); break; } case R.string.share_visible_contacts: { doShareVisibleContacts(); break; } default: { Log.e(TAG, "Unexpected resource: " + getResources().getResourceEntryName(resId)); } } } }; new AlertDialog.Builder(this) .setTitle(R.string.dialog_import_export) .setNegativeButton(android.R.string.cancel, null) .setSingleChoiceItems(adapter, -1, clickListener) .show(); } private void doShareVisibleContacts() { final Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI, sLookupProjection, getContactSelection(), null, null); try { if (!cursor.moveToFirst()) { Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show(); return; } StringBuilder uriListBuilder = new StringBuilder(); int index = 0; for (;!cursor.isAfterLast(); cursor.moveToNext()) { if (index != 0) uriListBuilder.append(':'); uriListBuilder.append(cursor.getString(0)); index++; } Uri uri = Uri.withAppendedPath( Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode(uriListBuilder.toString())); final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(Contacts.CONTENT_VCARD_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(intent); } finally { cursor.close(); } } private void handleImportRequest(int resId) { // There's three possibilities: // - more than one accounts -> ask the user // - just one account -> use the account without asking the user // - no account -> use phone-local storage without asking the user final Sources sources = Sources.getInstance(this); final List<Account> accountList = sources.getAccounts(true); final int size = accountList.size(); if (size > 1) { showDialog(resId); return; } AccountSelectionUtil.doImport(this, resId, (size == 1 ? accountList.get(0) : null)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case SUBACTIVITY_NEW_CONTACT: if (resultCode == RESULT_OK) { returnPickerResult(null, data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME), data.getData()); } break; case SUBACTIVITY_VIEW_CONTACT: if (resultCode == RESULT_OK) { mAdapter.notifyDataSetChanged(); } break; case SUBACTIVITY_DISPLAY_GROUP: // Mark as just created so we re-run the view query mJustCreated = true; break; case SUBACTIVITY_FILTER: case SUBACTIVITY_SEARCH: // Pass through results of filter or search UI if (resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); } break; } } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the context menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return; } AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); if (cursor == null) { // For some reason the requested item isn't available, do nothing return; } long id = info.id; Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id); long rawContactId = ContactsUtils.queryForRawContactId(getContentResolver(), id); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); // Setup the menu header menu.setHeaderTitle(cursor.getString(getSummaryDisplayNameColumnIndex())); // View contact details menu.add(0, MENU_ITEM_VIEW_CONTACT, 0, R.string.menu_viewContact) .setIntent(new Intent(Intent.ACTION_VIEW, contactUri)); if (cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0) { // Calling contact menu.add(0, MENU_ITEM_CALL, 0, getString(R.string.menu_call)); // Send SMS item menu.add(0, MENU_ITEM_SEND_SMS, 0, getString(R.string.menu_sendSMS)); } // Star toggling int starState = cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX); if (starState == 0) { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_addStar); } else { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_removeStar); } // Contact editing menu.add(0, MENU_ITEM_EDIT, 0, R.string.menu_editContact) .setIntent(new Intent(Intent.ACTION_EDIT, rawContactUri)); menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_deleteContact); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); switch (item.getItemId()) { case MENU_ITEM_TOGGLE_STAR: { // Toggle the star ContentValues values = new ContentValues(1); values.put(Contacts.STARRED, cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX) == 0 ? 1 : 0); final Uri selectedUri = this.getContactUri(info.position); getContentResolver().update(selectedUri, values, null, null); return true; } case MENU_ITEM_CALL: { callContact(cursor); return true; } case MENU_ITEM_SEND_SMS: { smsContact(cursor); return true; } case MENU_ITEM_DELETE: { doContactDelete(getContactUri(info.position)); return true; } } return super.onContextItemSelected(item); } /** * Event handler for the use case where the user starts typing without * bringing up the search UI first. */ public boolean onKey(View v, int keyCode, KeyEvent event) { if (!mSearchMode && (mMode & MODE_MASK_NO_FILTER) == 0 && !mSearchInitiated) { int unicodeChar = event.getUnicodeChar(); if (unicodeChar != 0) { mSearchInitiated = true; startSearch(new String(new int[]{unicodeChar}, 0, 1), false, null, false); return true; } } return false; } /** * Event handler for search UI. */ public void afterTextChanged(Editable s) { onSearchTextChanged(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } /** * Event handler for search UI. */ public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { hideSoftKeyboard(); if (TextUtils.isEmpty(getTextFilter())) { finish(); } return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: { if (callSelection()) { return true; } break; } case KeyEvent.KEYCODE_DEL: { if (deleteSelection()) { return true; } break; } } return super.onKeyDown(keyCode, event); } private boolean deleteSelection() { if ((mMode & MODE_MASK_PICKER) != 0) { return false; } final int position = getListView().getSelectedItemPosition(); if (position != ListView.INVALID_POSITION) { Uri contactUri = getContactUri(position); if (contactUri != null) { doContactDelete(contactUri); return true; } } return false; } /** * Prompt the user before deleting the given {@link Contacts} entry. */ protected void doContactDelete(Uri contactUri) { mReadOnlySourcesCnt = 0; mWritableSourcesCnt = 0; mWritableRawContactIds.clear(); Sources sources = Sources.getInstance(ContactsListActivity.this); Cursor c = getContentResolver().query(RawContacts.CONTENT_URI, RAW_CONTACTS_PROJECTION, RawContacts.CONTACT_ID + "=" + ContentUris.parseId(contactUri), null, null); if (c != null) { try { while (c.moveToNext()) { final String accountType = c.getString(2); final long rawContactId = c.getLong(0); ContactsSource contactsSource = sources.getInflatedSource(accountType, ContactsSource.LEVEL_SUMMARY); if (contactsSource != null && contactsSource.readOnly) { mReadOnlySourcesCnt += 1; } else { mWritableSourcesCnt += 1; mWritableRawContactIds.add(rawContactId); } } } finally { c.close(); } } mSelectedContactUri = contactUri; if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt > 0) { showDialog(R.id.dialog_readonly_contact_delete_confirmation); } else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) { showDialog(R.id.dialog_readonly_contact_hide_confirmation); } else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) { showDialog(R.id.dialog_multiple_contact_delete_confirmation); } else { showDialog(R.id.dialog_delete_contact_confirmation); } } /** * Dismisses the soft keyboard when the list takes focus. */ public void onFocusChange(View view, boolean hasFocus) { if (view == getListView() && hasFocus) { hideSoftKeyboard(); } } /** * Dismisses the soft keyboard when the list takes focus. */ public boolean onTouch(View view, MotionEvent event) { if (view == getListView()) { hideSoftKeyboard(); } return false; } /** * Dismisses the search UI along with the keyboard if the filter text is empty. */ public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (mSearchMode && keyCode == KeyEvent.KEYCODE_BACK && TextUtils.isEmpty(getTextFilter())) { hideSoftKeyboard(); onBackPressed(); return true; } return false; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { hideSoftKeyboard(); if (mSearchMode && mAdapter.isSearchAllContactsItemPosition(position)) { doSearch(); } else if (mMode == MODE_INSERT_OR_EDIT_CONTACT || mMode == MODE_QUERY_PICK_TO_EDIT) { Intent intent; if (position == 0 && !mSearchMode && mMode != MODE_QUERY_PICK_TO_EDIT) { intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); } else { intent = new Intent(Intent.ACTION_EDIT, getSelectedUri(position)); } intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); Bundle extras = getIntent().getExtras(); if (extras != null) { intent.putExtras(extras); } intent.putExtra(KEY_PICKER_MODE, (mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER); startActivity(intent); finish(); } else if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW && position == 0) { Intent newContact = new Intent(Intents.Insert.ACTION, Contacts.CONTENT_URI); startActivityForResult(newContact, SUBACTIVITY_NEW_CONTACT); } else if (mMode == MODE_JOIN_CONTACT && id == JOIN_MODE_SHOW_ALL_CONTACTS_ID) { mJoinModeShowAllContacts = false; startQuery(); } else if (id > 0) { final Uri uri = getSelectedUri(position); if ((mMode & MODE_MASK_PICKER) == 0) { final Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivityForResult(intent, SUBACTIVITY_VIEW_CONTACT); } else if (mMode == MODE_JOIN_CONTACT) { returnPickerResult(null, null, uri); } else if (mMode == MODE_QUERY_PICK_TO_VIEW) { // Started with query that should launch to view contact final Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); finish(); } else if (mMode == MODE_PICK_PHONE || mMode == MODE_QUERY_PICK_PHONE) { Cursor c = (Cursor) mAdapter.getItem(position); returnPickerResult(c, c.getString(PHONE_DISPLAY_NAME_COLUMN_INDEX), uri); } else if ((mMode & MODE_MASK_PICKER) != 0) { Cursor c = (Cursor) mAdapter.getItem(position); returnPickerResult(c, c.getString(getSummaryDisplayNameColumnIndex()), uri); } else if (mMode == MODE_PICK_POSTAL || mMode == MODE_LEGACY_PICK_POSTAL || mMode == MODE_LEGACY_PICK_PHONE) { returnPickerResult(null, null, uri); } } else { signalError(); } } private void hideSoftKeyboard() { // Hide soft keyboard, if visible InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mList.getWindowToken(), 0); } /** * @param selectedUri In most cases, this should be a lookup {@link Uri}, possibly * generated through {@link Contacts#getLookupUri(long, String)}. */ private void returnPickerResult(Cursor c, String name, Uri selectedUri) { final Intent intent = new Intent(); if (mShortcutAction != null) { Intent shortcutIntent; if (Intent.ACTION_VIEW.equals(mShortcutAction)) { // This is a simple shortcut to view a contact. shortcutIntent = new Intent(ContactsContract.QuickContact.ACTION_QUICK_CONTACT); shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); shortcutIntent.setData(selectedUri); shortcutIntent.putExtra(ContactsContract.QuickContact.EXTRA_MODE, ContactsContract.QuickContact.MODE_LARGE); shortcutIntent.putExtra(ContactsContract.QuickContact.EXTRA_EXCLUDE_MIMES, (String[]) null); final Bitmap icon = framePhoto(loadContactPhoto(selectedUri, null)); if (icon != null) { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, scaleToAppIconSize(icon)); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher_shortcut_contact)); } } else { // This is a direct dial or sms shortcut. String number = c.getString(PHONE_NUMBER_COLUMN_INDEX); int type = c.getInt(PHONE_TYPE_COLUMN_INDEX); String scheme; int resid; if (Intent.ACTION_CALL.equals(mShortcutAction)) { scheme = Constants.SCHEME_TEL; resid = R.drawable.badge_action_call; } else { scheme = Constants.SCHEME_SMSTO; resid = R.drawable.badge_action_sms; } // Make the URI a direct tel: URI so that it will always continue to work Uri phoneUri = Uri.fromParts(scheme, number, null); shortcutIntent = new Intent(mShortcutAction, phoneUri); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, generatePhoneNumberIcon(selectedUri, type, resid)); } shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); setResult(RESULT_OK, intent); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); setResult(RESULT_OK, intent.setData(selectedUri)); } finish(); } private Bitmap framePhoto(Bitmap photo) { final Resources r = getResources(); final Drawable frame = r.getDrawable(com.android.internal.R.drawable.quickcontact_badge); final int width = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_width); final int height = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_height); frame.setBounds(0, 0, width, height); final Rect padding = new Rect(); frame.getPadding(padding); final Rect source = new Rect(0, 0, photo.getWidth(), photo.getHeight()); final Rect destination = new Rect(padding.left, padding.top, width - padding.right, height - padding.bottom); final int d = Math.max(width, height); final Bitmap b = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); c.translate((d - width) / 2.0f, (d - height) / 2.0f); frame.draw(c); c.drawBitmap(photo, source, destination, new Paint(Paint.FILTER_BITMAP_FLAG)); return b; } /** * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone * number, and if there is a photo also adds the call action icon. * * @param lookupUri The person the phone number belongs to * @param type The type of the phone number * @param actionResId The ID for the action resource * @return The bitmap for the icon */ private Bitmap generatePhoneNumberIcon(Uri lookupUri, int type, int actionResId) { final Resources r = getResources(); boolean drawPhoneOverlay = true; final float scaleDensity = getResources().getDisplayMetrics().scaledDensity; Bitmap photo = loadContactPhoto(lookupUri, null); if (photo == null) { // If there isn't a photo use the generic phone action icon instead Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { photo = phoneIcon; drawPhoneOverlay = false; } else { return null; } } // Setup the drawing classes Bitmap icon = createShortcutBitmap(); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, mIconSize, mIconSize); canvas.drawBitmap(photo, src, dst, photoPaint); // Create an overlay for the phone number type String overlay = null; switch (type) { case Phone.TYPE_HOME: overlay = getString(R.string.type_short_home); break; case Phone.TYPE_MOBILE: overlay = getString(R.string.type_short_mobile); break; case Phone.TYPE_WORK: overlay = getString(R.string.type_short_work); break; case Phone.TYPE_PAGER: overlay = getString(R.string.type_short_pager); break; case Phone.TYPE_OTHER: overlay = getString(R.string.type_short_other); break; } if (overlay != null) { Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); textPaint.setTextSize(20.0f * scaleDensity); textPaint.setTypeface(Typeface.DEFAULT_BOLD); textPaint.setColor(r.getColor(R.color.textColorIconOverlay)); textPaint.setShadowLayer(3f, 1, 1, r.getColor(R.color.textColorIconOverlayShadow)); canvas.drawText(overlay, 2 * scaleDensity, 16 * scaleDensity, textPaint); } // Draw the phone action icon as an overlay if (ENABLE_ACTION_ICON_OVERLAYS && drawPhoneOverlay) { Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { src.set(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight()); int iconWidth = icon.getWidth(); dst.set(iconWidth - ((int) (20 * scaleDensity)), -1, iconWidth, ((int) (19 * scaleDensity))); canvas.drawBitmap(phoneIcon, src, dst, photoPaint); } } return icon; } private Bitmap scaleToAppIconSize(Bitmap photo) { // Setup the drawing classes Bitmap icon = createShortcutBitmap(); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, mIconSize, mIconSize); canvas.drawBitmap(photo, src, dst, photoPaint); return icon; } private Bitmap createShortcutBitmap() { return Bitmap.createBitmap(mIconSize, mIconSize, Bitmap.Config.ARGB_8888); } /** * Returns the icon for the phone call action. * * @param r The resources to load the icon from * @param resId The resource ID to load * @return the icon for the phone call action */ private Bitmap getPhoneActionIcon(Resources r, int resId) { Drawable phoneIcon = r.getDrawable(resId); if (phoneIcon instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) phoneIcon; return bd.getBitmap(); } else { return null; } } private Uri getUriToQuery() { switch(mMode) { case MODE_JOIN_CONTACT: return getJoinSuggestionsUri(null); case MODE_FREQUENT: case MODE_STARRED: return Contacts.CONTENT_URI; case MODE_DEFAULT: case MODE_INSERT_OR_EDIT_CONTACT: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT:{ return CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS; } case MODE_STREQUENT: { return Contacts.CONTENT_STREQUENT_URI; } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return People.CONTENT_URI; } case MODE_PICK_PHONE: { return buildSectionIndexerUri(Phone.CONTENT_URI); } case MODE_LEGACY_PICK_PHONE: { return Phones.CONTENT_URI; } case MODE_PICK_POSTAL: { return buildSectionIndexerUri(StructuredPostal.CONTENT_URI); } case MODE_LEGACY_PICK_POSTAL: { return ContactMethods.CONTENT_URI; } case MODE_QUERY_PICK_TO_VIEW: { if (mQueryMode == QUERY_MODE_MAILTO) { return Uri.withAppendedPath(Email.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } else if (mQueryMode == QUERY_MODE_TEL) { return Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } return CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS; } case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_TO_EDIT: { return getContactFilterUri(mInitialFilter); } case MODE_QUERY_PICK_PHONE: { return Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } case MODE_GROUP: { return mGroupUri; } default: { throw new IllegalStateException("Can't generate URI: Unsupported Mode."); } } } /** * Build the {@link Contacts#CONTENT_LOOKUP_URI} for the given * {@link ListView} position, using {@link #mAdapter}. */ private Uri getContactUri(int position) { if (position == ListView.INVALID_POSITION) { throw new IllegalArgumentException("Position not in list bounds"); } final Cursor cursor = (Cursor)mAdapter.getItem(position); if (cursor == null) { return null; } switch(mMode) { case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { final long personId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); return ContentUris.withAppendedId(People.CONTENT_URI, personId); } default: { // Build and return soft, lookup reference final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); return Contacts.getLookupUri(contactId, lookupKey); } } } /** * Build the {@link Uri} for the given {@link ListView} position, which can * be used as result when in {@link #MODE_MASK_PICKER} mode. */ private Uri getSelectedUri(int position) { if (position == ListView.INVALID_POSITION) { throw new IllegalArgumentException("Position not in list bounds"); } final long id = mAdapter.getItemId(position); switch(mMode) { case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return ContentUris.withAppendedId(People.CONTENT_URI, id); } case MODE_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { return ContentUris.withAppendedId(Data.CONTENT_URI, id); } case MODE_LEGACY_PICK_PHONE: { return ContentUris.withAppendedId(Phones.CONTENT_URI, id); } case MODE_PICK_POSTAL: { return ContentUris.withAppendedId(Data.CONTENT_URI, id); } case MODE_LEGACY_PICK_POSTAL: { return ContentUris.withAppendedId(ContactMethods.CONTENT_URI, id); } default: { return getContactUri(position); } } } String[] getProjectionForQuery() { switch(mMode) { case MODE_JOIN_CONTACT: case MODE_STREQUENT: case MODE_FREQUENT: case MODE_STARRED: case MODE_DEFAULT: case MODE_INSERT_OR_EDIT_CONTACT: case MODE_GROUP: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: { return mSearchMode ? CONTACTS_SUMMARY_FILTER_PROJECTION : CONTACTS_SUMMARY_PROJECTION; } case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_TO_EDIT: { return CONTACTS_SUMMARY_FILTER_PROJECTION; } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return LEGACY_PEOPLE_PROJECTION ; } case MODE_QUERY_PICK_PHONE: case MODE_PICK_PHONE: { return PHONES_PROJECTION; } case MODE_LEGACY_PICK_PHONE: { return LEGACY_PHONES_PROJECTION; } case MODE_PICK_POSTAL: { return POSTALS_PROJECTION; } case MODE_LEGACY_PICK_POSTAL: { return LEGACY_POSTALS_PROJECTION; } case MODE_QUERY_PICK_TO_VIEW: { if (mQueryMode == QUERY_MODE_MAILTO) { return CONTACTS_SUMMARY_PROJECTION_FROM_EMAIL; } else if (mQueryMode == QUERY_MODE_TEL) { return PHONES_PROJECTION; } break; } } // Default to normal aggregate projection return CONTACTS_SUMMARY_PROJECTION; } private Bitmap loadContactPhoto(Uri selectedUri, BitmapFactory.Options options) { Uri contactUri = null; if (Contacts.CONTENT_ITEM_TYPE.equals(getContentResolver().getType(selectedUri))) { // TODO we should have a "photo" directory under the lookup URI itself contactUri = Contacts.lookupContact(getContentResolver(), selectedUri); } else { Cursor cursor = getContentResolver().query(selectedUri, new String[] { Data.CONTACT_ID }, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { final long contactId = cursor.getLong(0); contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); } } finally { if (cursor != null) cursor.close(); } } Cursor cursor = null; Bitmap bm = null; try { Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY); cursor = getContentResolver().query(photoUri, new String[] {Photo.PHOTO}, null, null, null); if (cursor != null && cursor.moveToFirst()) { bm = ContactsUtils.loadContactPhoto(cursor, 0, options); } } finally { if (cursor != null) { cursor.close(); } } if (bm == null) { final int[] fallbacks = { R.drawable.ic_contact_picture, R.drawable.ic_contact_picture_2, R.drawable.ic_contact_picture_3 }; bm = BitmapFactory.decodeResource(getResources(), fallbacks[new Random().nextInt(fallbacks.length)]); } return bm; } /** * Return the selection arguments for a default query based on the * {@link #mDisplayOnlyPhones} flag. */ private String getContactSelection() { if (mDisplayOnlyPhones) { return CLAUSE_ONLY_VISIBLE + " AND " + CLAUSE_ONLY_PHONES; } else { return CLAUSE_ONLY_VISIBLE; } } private Uri getContactFilterUri(String filter) { Uri baseUri; if (!TextUtils.isEmpty(filter)) { baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); } else { baseUri = Contacts.CONTENT_URI; } if (mAdapter.getDisplaySectionHeadersEnabled()) { return buildSectionIndexerUri(baseUri); } else { return baseUri; } } private Uri getPeopleFilterUri(String filter) { if (!TextUtils.isEmpty(filter)) { return Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(filter)); } else { return People.CONTENT_URI; } } private static Uri buildSectionIndexerUri(Uri uri) { return uri.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); } private Uri getJoinSuggestionsUri(String filter) { Builder builder = Contacts.CONTENT_URI.buildUpon(); builder.appendEncodedPath(String.valueOf(mQueryAggregateId)); builder.appendEncodedPath(AggregationSuggestions.CONTENT_DIRECTORY); if (!TextUtils.isEmpty(filter)) { builder.appendEncodedPath(Uri.encode(filter)); } builder.appendQueryParameter("limit", String.valueOf(MAX_SUGGESTIONS)); return builder.build(); } private String getSortOrder(String[] projectionType) { if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_PRIMARY) { return Contacts.SORT_KEY_PRIMARY; } else { return Contacts.SORT_KEY_ALTERNATIVE; } } void startQuery() { // Set the proper empty string setEmptyText(); if (mSearchResultsMode) { TextView foundContactsText = (TextView)findViewById(R.id.search_results_found); foundContactsText.setText(R.string.search_results_searching); } mAdapter.setLoading(true); // Cancel any pending queries mQueryHandler.cancelOperation(QUERY_TOKEN); mQueryHandler.setLoadingJoinSuggestions(false); mSortOrder = mContactsPrefs.getSortOrder(); mDisplayOrder = mContactsPrefs.getDisplayOrder(); // When sort order and display order contradict each other, we want to // highlight the part of the name used for sorting. mHighlightWhenScrolling = false; if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_PRIMARY && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_ALTERNATIVE) { mHighlightWhenScrolling = true; } else if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_ALTERNATIVE && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { mHighlightWhenScrolling = true; } String[] projection = getProjectionForQuery(); if (mSearchMode && TextUtils.isEmpty(getTextFilter())) { mAdapter.changeCursor(new MatrixCursor(projection)); return; } String callingPackage = getCallingPackage(); Uri uri = getUriToQuery(); if (!TextUtils.isEmpty(callingPackage)) { uri = uri.buildUpon() .appendQueryParameter(ContactsContract.REQUESTING_PACKAGE_PARAM_KEY, callingPackage) .build(); } // Kick off the new query switch (mMode) { case MODE_GROUP: case MODE_DEFAULT: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, getContactSelection(), null, getSortOrder(projection)); break; case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: case MODE_PICK_POSTAL: case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_PHONE: case MODE_QUERY_PICK_TO_VIEW: case MODE_QUERY_PICK_TO_EDIT: { mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, getSortOrder(projection)); break; } case MODE_STARRED: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, Contacts.STARRED + "=1", null, getSortOrder(projection)); break; case MODE_FREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, Contacts.TIMES_CONTACTED + " > 0", null, Contacts.TIMES_CONTACTED + " DESC, " + getSortOrder(projection)); break; case MODE_STREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, null); break; case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); break; case MODE_LEGACY_PICK_POSTAL: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, ContactMethods.KIND + "=" + android.provider.Contacts.KIND_POSTAL, null, getSortOrder(projection)); break; case MODE_JOIN_CONTACT: mQueryHandler.setLoadingJoinSuggestions(true); mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, null); break; } } /** * Called from a background thread to do the filter and return the resulting cursor. * * @param filter the text that was entered to filter on * @return a cursor with the results of the filter */ Cursor doFilter(String filter) { String[] projection = getProjectionForQuery(); if (mSearchMode && TextUtils.isEmpty(getTextFilter())) { return new MatrixCursor(projection); } final ContentResolver resolver = getContentResolver(); switch (mMode) { case MODE_DEFAULT: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: { return resolver.query(getContactFilterUri(filter), projection, getContactSelection(), null, getSortOrder(projection)); } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return resolver.query(getPeopleFilterUri(filter), projection, null, null, getSortOrder(projection)); } case MODE_STARRED: { return resolver.query(getContactFilterUri(filter), projection, Contacts.STARRED + "=1", null, getSortOrder(projection)); } case MODE_FREQUENT: { return resolver.query(getContactFilterUri(filter), projection, Contacts.TIMES_CONTACTED + " > 0", null, Contacts.TIMES_CONTACTED + " DESC, " + getSortOrder(projection)); } case MODE_STREQUENT: { Uri uri; if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(Contacts.CONTENT_STREQUENT_FILTER_URI, Uri.encode(filter)); } else { uri = Contacts.CONTENT_STREQUENT_URI; } return resolver.query(uri, projection, null, null, null); } case MODE_PICK_PHONE: { Uri uri = getUriToQuery(); if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(filter)); } return resolver.query(uri, projection, CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); } case MODE_LEGACY_PICK_PHONE: { //TODO: Support filtering here (bug 2092503) break; } case MODE_JOIN_CONTACT: { // We are on a background thread. Run queries one after the other synchronously Cursor cursor = resolver.query(getJoinSuggestionsUri(filter), projection, null, null, null); mAdapter.setSuggestionsCursor(cursor); mJoinModeShowAllContacts = false; return resolver.query(getContactFilterUri(filter), projection, Contacts._ID + " != " + mQueryAggregateId + " AND " + CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); } } throw new UnsupportedOperationException("filtering not allowed in mode " + mMode); } private Cursor getShowAllContactsLabelCursor(String[] projection) { MatrixCursor matrixCursor = new MatrixCursor(projection); Object[] row = new Object[projection.length]; // The only columns we care about is the id row[SUMMARY_ID_COLUMN_INDEX] = JOIN_MODE_SHOW_ALL_CONTACTS_ID; matrixCursor.addRow(row); return matrixCursor; } /** * Calls the currently selected list item. * @return true if the call was initiated, false otherwise */ boolean callSelection() { ListView list = getListView(); if (list.hasFocus()) { Cursor cursor = (Cursor) list.getSelectedItem(); return callContact(cursor); } return false; } boolean callContact(Cursor cursor) { return callOrSmsContact(cursor, false /*call*/); } boolean smsContact(Cursor cursor) { return callOrSmsContact(cursor, true /*sms*/); } /** * Calls the contact which the cursor is point to. * @return true if the call was initiated, false otherwise */ boolean callOrSmsContact(Cursor cursor, boolean sendSms) { if (cursor == null) { return false; } switch (mMode) { case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { String phone = cursor.getString(PHONE_NUMBER_COLUMN_INDEX); if (sendSms) { ContactsUtils.initiateSms(this, phone); } else { ContactsUtils.initiateCall(this, phone); } return true; } case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_POSTAL: { return false; } default: { boolean hasPhone = cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; if (!hasPhone) { // There is no phone number. signalError(); return false; } String phone = null; Cursor phonesCursor = null; phonesCursor = queryPhoneNumbers(cursor.getLong(SUMMARY_ID_COLUMN_INDEX)); if (phonesCursor == null || phonesCursor.getCount() == 0) { // No valid number signalError(); return false; } else if (phonesCursor.getCount() == 1) { // only one number, call it. phone = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); } else { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { if (phonesCursor.getInt(phonesCursor. getColumnIndex(Phone.IS_SUPER_PRIMARY)) != 0) { // Found super primary, call it. phone = phonesCursor. getString(phonesCursor.getColumnIndex(Phone.NUMBER)); break; } } } if (phone == null) { // Display dialog to choose a number to call. PhoneDisambigDialog phoneDialog = new PhoneDisambigDialog( this, phonesCursor, sendSms); phoneDialog.show(); } else { if (sendSms) { ContactsUtils.initiateSms(this, phone); } else { ContactsUtils.initiateCall(this, phone); } } } } return true; } private Cursor queryPhoneNumbers(long contactId) { Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri dataUri = Uri.withAppendedPath(baseUri, Contacts.Data.CONTENT_DIRECTORY); Cursor c = getContentResolver().query(dataUri, new String[] {Phone._ID, Phone.NUMBER, Phone.IS_SUPER_PRIMARY, RawContacts.ACCOUNT_TYPE, Phone.TYPE, Phone.LABEL}, Data.MIMETYPE + "=?", new String[] {Phone.CONTENT_ITEM_TYPE}, null); if (c != null && c.moveToFirst()) { return c; } return null; } // TODO: fix PluralRules to handle zero correctly and use Resources.getQuantityText directly protected String getQuantityText(int count, int zeroResourceId, int pluralResourceId) { if (count == 0) { return getString(zeroResourceId); } else { String format = getResources().getQuantityText(pluralResourceId, count).toString(); return String.format(format, count); } } /** * Signal an error to the user. */ void signalError() { //TODO play an error beep or something... } Cursor getItemForView(View view) { ListView listView = getListView(); int index = listView.getPositionForView(view); if (index < 0) { return null; } return (Cursor) listView.getAdapter().getItem(index); } private static class QueryHandler extends AsyncQueryHandler { protected final WeakReference<ContactsListActivity> mActivity; protected boolean mLoadingJoinSuggestions = false; public QueryHandler(Context context) { super(context.getContentResolver()); mActivity = new WeakReference<ContactsListActivity>((ContactsListActivity) context); } public void setLoadingJoinSuggestions(boolean flag) { mLoadingJoinSuggestions = flag; } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { final ContactsListActivity activity = mActivity.get(); if (activity != null && !activity.isFinishing()) { // Whenever we get a suggestions cursor, we need to immediately kick off // another query for the complete list of contacts if (cursor != null && mLoadingJoinSuggestions) { mLoadingJoinSuggestions = false; if (cursor.getCount() > 0) { activity.mAdapter.setSuggestionsCursor(cursor); } else { cursor.close(); activity.mAdapter.setSuggestionsCursor(null); } if (activity.mAdapter.mSuggestionsCursorCount == 0 || !activity.mJoinModeShowAllContacts) { startQuery(QUERY_TOKEN, null, activity.getContactFilterUri( activity.getTextFilter()), CONTACTS_SUMMARY_PROJECTION, Contacts._ID + " != " + activity.mQueryAggregateId + " AND " + CLAUSE_ONLY_VISIBLE, null, activity.getSortOrder(CONTACTS_SUMMARY_PROJECTION)); return; } cursor = activity.getShowAllContactsLabelCursor(CONTACTS_SUMMARY_PROJECTION); } activity.mAdapter.changeCursor(cursor); // Now that the cursor is populated again, it's possible to restore the list state if (activity.mListState != null) { activity.mList.onRestoreInstanceState(activity.mListState); activity.mListState = null; } } else { if (cursor != null) { cursor.close(); } } } } final static class ContactListItemCache { public CharArrayBuffer nameBuffer = new CharArrayBuffer(128); public CharArrayBuffer dataBuffer = new CharArrayBuffer(128); public CharArrayBuffer highlightedTextBuffer = new CharArrayBuffer(128); public TextWithHighlighting textWithHighlighting; public CharArrayBuffer phoneticNameBuffer = new CharArrayBuffer(128); } final static class PinnedHeaderCache { public TextView titleView; public ColorStateList textColor; public Drawable background; } private final class ContactItemListAdapter extends CursorAdapter implements SectionIndexer, OnScrollListener, PinnedHeaderListView.PinnedHeaderAdapter { private SectionIndexer mIndexer; private boolean mLoading = true; private CharSequence mUnknownNameText; private boolean mDisplayPhotos = false; private boolean mDisplayCallButton = false; private boolean mDisplayAdditionalData = true; private int mFrequentSeparatorPos = ListView.INVALID_POSITION; private boolean mDisplaySectionHeaders = true; private Cursor mSuggestionsCursor; private int mSuggestionsCursorCount; public ContactItemListAdapter(Context context) { super(context, null, false); mUnknownNameText = context.getText(android.R.string.unknownName); switch (mMode) { case MODE_LEGACY_PICK_POSTAL: case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_PHONE: case MODE_PICK_PHONE: case MODE_STREQUENT: case MODE_FREQUENT: mDisplaySectionHeaders = false; break; } if (mSearchMode) { mDisplaySectionHeaders = false; } // Do not display the second line of text if in a specific SEARCH query mode, usually for // matching a specific E-mail or phone number. Any contact details // shown would be identical, and columns might not even be present // in the returned cursor. if (mMode != MODE_QUERY_PICK_PHONE && mQueryMode != QUERY_MODE_NONE) { mDisplayAdditionalData = false; } if ((mMode & MODE_MASK_NO_DATA) == MODE_MASK_NO_DATA) { mDisplayAdditionalData = false; } if ((mMode & MODE_MASK_SHOW_CALL_BUTTON) == MODE_MASK_SHOW_CALL_BUTTON) { mDisplayCallButton = true; } if ((mMode & MODE_MASK_SHOW_PHOTOS) == MODE_MASK_SHOW_PHOTOS) { mDisplayPhotos = true; } } public boolean getDisplaySectionHeadersEnabled() { return mDisplaySectionHeaders; } public void setSuggestionsCursor(Cursor cursor) { if (mSuggestionsCursor != null) { mSuggestionsCursor.close(); } mSuggestionsCursor = cursor; mSuggestionsCursorCount = cursor == null ? 0 : cursor.getCount(); } /** * Callback on the UI thread when the content observer on the backing cursor fires. * Instead of calling requery we need to do an async query so that the requery doesn't * block the UI thread for a long time. */ @Override protected void onContentChanged() { CharSequence constraint = getTextFilter(); if (!TextUtils.isEmpty(constraint)) { // Reset the filter state then start an async filter operation Filter filter = getFilter(); filter.filter(constraint); } else { // Start an async query startQuery(); } } public void setLoading(boolean loading) { mLoading = loading; } @Override public boolean isEmpty() { if (mProviderStatus != ProviderStatus.STATUS_NORMAL) { return true; } if (mSearchMode) { return TextUtils.isEmpty(getTextFilter()); } else if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW) { // This mode mask adds a header and we always want it to show up, even // if the list is empty, so always claim the list is not empty. return false; } else { if (mCursor == null || mLoading) { // We don't want the empty state to show when loading. return false; } else { return super.isEmpty(); } } } @Override public int getItemViewType(int position) { if (position == 0 && (mShowNumberOfContacts || (mMode & MODE_MASK_CREATE_NEW) != 0)) { return IGNORE_ITEM_VIEW_TYPE; } if (isShowAllContactsItemPosition(position)) { return IGNORE_ITEM_VIEW_TYPE; } if (isSearchAllContactsItemPosition(position)) { return IGNORE_ITEM_VIEW_TYPE; } if (getSeparatorId(position) != 0) { // We don't want the separator view to be recycled. return IGNORE_ITEM_VIEW_TYPE; } return super.getItemViewType(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (!mDataValid) { throw new IllegalStateException( "this should only be called when the cursor is valid"); } // handle the total contacts item if (position == 0 && mShowNumberOfContacts) { return getTotalContactCountView(parent); } if (position == 0 && (mMode & MODE_MASK_CREATE_NEW) != 0) { // Add the header for creating a new contact return getLayoutInflater().inflate(R.layout.create_new_contact, parent, false); } if (isShowAllContactsItemPosition(position)) { return getLayoutInflater(). inflate(R.layout.contacts_list_show_all_item, parent, false); } if (isSearchAllContactsItemPosition(position)) { return getLayoutInflater(). inflate(R.layout.contacts_list_search_all_item, parent, false); } // Handle the separator specially int separatorId = getSeparatorId(position); if (separatorId != 0) { TextView view = (TextView) getLayoutInflater(). inflate(R.layout.list_separator, parent, false); view.setText(separatorId); return view; } boolean showingSuggestion; Cursor cursor; if (mSuggestionsCursorCount != 0 && position < mSuggestionsCursorCount + 2) { showingSuggestion = true; cursor = mSuggestionsCursor; } else { showingSuggestion = false; cursor = mCursor; } int realPosition = getRealPosition(position); if (!cursor.moveToPosition(realPosition)) { throw new IllegalStateException("couldn't move cursor to position " + position); } boolean newView; View v; if (convertView == null || convertView.getTag() == null) { newView = true; v = newView(mContext, cursor, parent); } else { newView = false; v = convertView; } bindView(v, mContext, cursor); bindSectionHeader(v, realPosition, mDisplaySectionHeaders && !showingSuggestion); return v; } private View getTotalContactCountView(ViewGroup parent) { final LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.total_contacts, parent, false); TextView totalContacts = (TextView) view.findViewById(R.id.totalContactsText); String text; int count = getRealCount(); if (mSearchMode && !TextUtils.isEmpty(getTextFilter())) { text = getQuantityText(count, R.string.listFoundAllContactsZero, R.plurals.searchFoundContacts); } else { if (mDisplayOnlyPhones) { text = getQuantityText(count, R.string.listTotalPhoneContactsZero, R.plurals.listTotalPhoneContacts); } else { text = getQuantityText(count, R.string.listTotalAllContactsZero, R.plurals.listTotalAllContacts); } } totalContacts.setText(text); return view; } private boolean isShowAllContactsItemPosition(int position) { return mMode == MODE_JOIN_CONTACT && mJoinModeShowAllContacts && mSuggestionsCursorCount != 0 && position == mSuggestionsCursorCount + 2; } private boolean isSearchAllContactsItemPosition(int position) { return mSearchMode && position == getCount() - 1; } private int getSeparatorId(int position) { int separatorId = 0; if (position == mFrequentSeparatorPos) { separatorId = R.string.favoritesFrquentSeparator; } if (mSuggestionsCursorCount != 0) { if (position == 0) { separatorId = R.string.separatorJoinAggregateSuggestions; } else if (position == mSuggestionsCursorCount + 1) { separatorId = R.string.separatorJoinAggregateAll; } } return separatorId; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final ContactListItemView view = new ContactListItemView(context, null); view.setOnCallButtonClickListener(ContactsListActivity.this); view.setTag(new ContactListItemCache()); return view; } @Override public void bindView(View itemView, Context context, Cursor cursor) { final ContactListItemView view = (ContactListItemView)itemView; final ContactListItemCache cache = (ContactListItemCache) view.getTag(); int typeColumnIndex; int dataColumnIndex; int labelColumnIndex; int defaultType; int nameColumnIndex; int phoneticNameColumnIndex; boolean displayAdditionalData = mDisplayAdditionalData; boolean highlightingEnabled = false; switch(mMode) { case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { nameColumnIndex = PHONE_DISPLAY_NAME_COLUMN_INDEX; phoneticNameColumnIndex = -1; dataColumnIndex = PHONE_NUMBER_COLUMN_INDEX; typeColumnIndex = PHONE_TYPE_COLUMN_INDEX; labelColumnIndex = PHONE_LABEL_COLUMN_INDEX; defaultType = Phone.TYPE_HOME; break; } case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_POSTAL: { nameColumnIndex = POSTAL_DISPLAY_NAME_COLUMN_INDEX; phoneticNameColumnIndex = -1; dataColumnIndex = POSTAL_ADDRESS_COLUMN_INDEX; typeColumnIndex = POSTAL_TYPE_COLUMN_INDEX; labelColumnIndex = POSTAL_LABEL_COLUMN_INDEX; defaultType = StructuredPostal.TYPE_HOME; break; } default: { nameColumnIndex = getSummaryDisplayNameColumnIndex(); phoneticNameColumnIndex = SUMMARY_PHONETIC_NAME_COLUMN_INDEX; dataColumnIndex = -1; typeColumnIndex = -1; labelColumnIndex = -1; defaultType = Phone.TYPE_HOME; displayAdditionalData = false; highlightingEnabled = mHighlightWhenScrolling && mMode != MODE_STREQUENT; } } // Set the name cursor.copyStringToBuffer(nameColumnIndex, cache.nameBuffer); TextView nameView = view.getNameTextView(); int size = cache.nameBuffer.sizeCopied; if (size != 0) { if (highlightingEnabled) { if (cache.textWithHighlighting == null) { cache.textWithHighlighting = mHighlightingAnimation.createTextWithHighlighting(); } buildDisplayNameWithHighlighting(nameView, cursor, cache.nameBuffer, cache.highlightedTextBuffer, cache.textWithHighlighting); } else { nameView.setText(cache.nameBuffer.data, 0, size); } } else { nameView.setText(mUnknownNameText); } boolean hasPhone = cursor.getColumnCount() >= SUMMARY_HAS_PHONE_COLUMN_INDEX && cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; // Make the call button visible if requested. if (mDisplayCallButton && hasPhone) { int pos = cursor.getPosition(); view.showCallButton(android.R.id.button1, pos); } else { view.hideCallButton(); } // Set the photo, if requested if (mDisplayPhotos) { boolean useQuickContact = (mMode & MODE_MASK_DISABLE_QUIKCCONTACT) == 0; long photoId = 0; if (!cursor.isNull(SUMMARY_PHOTO_ID_COLUMN_INDEX)) { photoId = cursor.getLong(SUMMARY_PHOTO_ID_COLUMN_INDEX); } ImageView viewToUse; if (useQuickContact) { // Build soft lookup reference final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); QuickContactBadge quickContact = view.getQuickContact(); quickContact.assignContactUri(Contacts.getLookupUri(contactId, lookupKey)); viewToUse = quickContact; } else { viewToUse = view.getPhotoView(); } final int position = cursor.getPosition(); mPhotoLoader.loadPhoto(viewToUse, photoId); } if ((mMode & MODE_MASK_NO_PRESENCE) == 0) { // Set the proper icon (star or presence or nothing) int serverStatus; if (!cursor.isNull(SUMMARY_PRESENCE_STATUS_COLUMN_INDEX)) { serverStatus = cursor.getInt(SUMMARY_PRESENCE_STATUS_COLUMN_INDEX); Drawable icon = ContactPresenceIconUtil.getPresenceIcon(mContext, serverStatus); if (icon != null) { view.setPresence(icon); } else { view.setPresence(null); } } else { view.setPresence(null); } } else { view.setPresence(null); } if (mShowSearchSnippets) { boolean showSnippet = false; String snippetMimeType = cursor.getString(SUMMARY_SNIPPET_MIMETYPE_COLUMN_INDEX); if (Email.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String email = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); if (!TextUtils.isEmpty(email)) { view.setSnippet(email); showSnippet = true; } } else if (Organization.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String company = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); String title = cursor.getString(SUMMARY_SNIPPET_DATA4_COLUMN_INDEX); if (!TextUtils.isEmpty(company)) { if (!TextUtils.isEmpty(title)) { view.setSnippet(company + " / " + title); } else { view.setSnippet(company); } showSnippet = true; } else if (!TextUtils.isEmpty(title)) { view.setSnippet(title); showSnippet = true; } } else if (Nickname.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String nickname = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); if (!TextUtils.isEmpty(nickname)) { view.setSnippet(nickname); showSnippet = true; } } if (!showSnippet) { view.setSnippet(null); } } if (!displayAdditionalData) { if (phoneticNameColumnIndex != -1) { // Set the name cursor.copyStringToBuffer(phoneticNameColumnIndex, cache.phoneticNameBuffer); int phoneticNameSize = cache.phoneticNameBuffer.sizeCopied; if (phoneticNameSize != 0) { view.setLabel(cache.phoneticNameBuffer.data, phoneticNameSize); } else { view.setLabel(null); } } else { view.setLabel(null); } return; } // Set the data. cursor.copyStringToBuffer(dataColumnIndex, cache.dataBuffer); size = cache.dataBuffer.sizeCopied; view.setData(cache.dataBuffer.data, size); // Set the label. if (!cursor.isNull(typeColumnIndex)) { final int type = cursor.getInt(typeColumnIndex); final String label = cursor.getString(labelColumnIndex); if (mMode == MODE_LEGACY_PICK_POSTAL || mMode == MODE_PICK_POSTAL) { // TODO cache view.setLabel(StructuredPostal.getTypeLabel(context.getResources(), type, label)); } else { // TODO cache view.setLabel(Phone.getTypeLabel(context.getResources(), type, label)); } } else { view.setLabel(null); } } /** * Computes the span of the display name that has highlighted parts and configures * the display name text view accordingly. */ private void buildDisplayNameWithHighlighting(TextView textView, Cursor cursor, CharArrayBuffer buffer1, CharArrayBuffer buffer2, TextWithHighlighting textWithHighlighting) { int oppositeDisplayOrderColumnIndex; if (mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { oppositeDisplayOrderColumnIndex = SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX; } else { oppositeDisplayOrderColumnIndex = SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX; } cursor.copyStringToBuffer(oppositeDisplayOrderColumnIndex, buffer2); textWithHighlighting.setText(buffer1, buffer2); textView.setText(textWithHighlighting); } private void bindSectionHeader(View itemView, int position, boolean displaySectionHeaders) { final ContactListItemView view = (ContactListItemView)itemView; final ContactListItemCache cache = (ContactListItemCache) view.getTag(); if (!displaySectionHeaders) { view.setSectionHeader(null); view.setDividerVisible(true); } else { final int section = getSectionForPosition(position); if (getPositionForSection(section) == position) { String title = (String)mIndexer.getSections()[section]; view.setSectionHeader(title); } else { view.setDividerVisible(false); view.setSectionHeader(null); } // move the divider for the last item in a section if (getPositionForSection(section + 1) - 1 == position) { view.setDividerVisible(false); } else { view.setDividerVisible(true); } } } @Override public void changeCursor(Cursor cursor) { if (cursor != null) { setLoading(false); } // Get the split between starred and frequent items, if the mode is strequent mFrequentSeparatorPos = ListView.INVALID_POSITION; int cursorCount = 0; if (cursor != null && (cursorCount = cursor.getCount()) > 0 && mMode == MODE_STREQUENT) { cursor.move(-1); for (int i = 0; cursor.moveToNext(); i++) { int starred = cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX); if (starred == 0) { if (i > 0) { // Only add the separator when there are starred items present mFrequentSeparatorPos = i; } break; } } } if (cursor != null && mSearchResultsMode) { TextView foundContactsText = (TextView)findViewById(R.id.search_results_found); String text = getQuantityText(cursor.getCount(), R.string.listFoundAllContactsZero, R.plurals.listFoundAllContacts); foundContactsText.setText(text); } super.changeCursor(cursor); // Update the indexer for the fast scroll widget updateIndexer(cursor); } private void updateIndexer(Cursor cursor) { if (cursor == null) { mIndexer = null; return; } Bundle bundle = cursor.getExtras(); if (bundle.containsKey(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES)) { String sections[] = bundle.getStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES); int counts[] = bundle.getIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS); mIndexer = new ContactsSectionIndexer(sections, counts); } else { mIndexer = null; } } /** * Run the query on a helper thread. Beware that this code does not run * on the main UI thread! */ @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { return doFilter(constraint.toString()); } public Object [] getSections() { if (mIndexer == null) { return new String[] { " " }; } else { return mIndexer.getSections(); } } public int getPositionForSection(int sectionIndex) { if (mIndexer == null) { return -1; } return mIndexer.getPositionForSection(sectionIndex); } public int getSectionForPosition(int position) { if (mIndexer == null) { return -1; } return mIndexer.getSectionForPosition(position); } @Override public boolean areAllItemsEnabled() { return mMode != MODE_STARRED && !mShowNumberOfContacts && mSuggestionsCursorCount == 0; } @Override public boolean isEnabled(int position) { if (mShowNumberOfContacts) { if (position == 0) { return false; } position--; } if (mSuggestionsCursorCount > 0) { return position != 0 && position != mSuggestionsCursorCount + 1; } return position != mFrequentSeparatorPos; } @Override public int getCount() { if (!mDataValid) { return 0; } int superCount = super.getCount(); if (mShowNumberOfContacts && (mSearchMode || superCount > 0)) { // We don't want to count this header if it's the only thing visible, so that // the empty text will display. superCount++; } if (mSearchMode) { // Last element in the list is the "Find superCount++; } // We do not show the "Create New" button in Search mode if ((mMode & MODE_MASK_CREATE_NEW) != 0 && !mSearchMode) { // Count the "Create new contact" line superCount++; } if (mSuggestionsCursorCount != 0) { // When showing suggestions, we have 2 additional list items: the "Suggestions" // and "All contacts" headers. return mSuggestionsCursorCount + superCount + 2; } else if (mFrequentSeparatorPos != ListView.INVALID_POSITION) { // When showing strequent list, we have an additional list item - the separator. return superCount + 1; } else { return superCount; } } /** * Gets the actual count of contacts and excludes all the headers. */ public int getRealCount() { return super.getCount(); } private int getRealPosition(int pos) { if (mShowNumberOfContacts) { pos--; } if ((mMode & MODE_MASK_CREATE_NEW) != 0 && !mSearchMode) { return pos - 1; } else if (mSuggestionsCursorCount != 0) { // When showing suggestions, we have 2 additional list items: the "Suggestions" // and "All contacts" separators. if (pos < mSuggestionsCursorCount + 2) { // We are in the upper partition (Suggestions). Adjusting for the "Suggestions" // separator. return pos - 1; } else { // We are in the lower partition (All contacts). Adjusting for the size // of the upper partition plus the two separators. return pos - mSuggestionsCursorCount - 2; } } else if (mFrequentSeparatorPos == ListView.INVALID_POSITION) { // No separator, identity map return pos; } else if (pos <= mFrequentSeparatorPos) { // Before or at the separator, identity map return pos; } else { // After the separator, remove 1 from the pos to get the real underlying pos return pos - 1; } } @Override public Object getItem(int pos) { if (mSuggestionsCursorCount != 0 && pos <= mSuggestionsCursorCount) { mSuggestionsCursor.moveToPosition(getRealPosition(pos)); return mSuggestionsCursor; } else if (isSearchAllContactsItemPosition(pos)){ return null; } else { int realPosition = getRealPosition(pos); if (realPosition < 0) { return null; } return super.getItem(realPosition); } } @Override public long getItemId(int pos) { if (mSuggestionsCursorCount != 0 && pos < mSuggestionsCursorCount + 2) { if (mSuggestionsCursor.moveToPosition(pos - 1)) { return mSuggestionsCursor.getLong(mRowIDColumn); } else { return 0; } } else if (isSearchAllContactsItemPosition(pos)) { return 0; } int realPosition = getRealPosition(pos); if (realPosition < 0) { return 0; } return super.getItemId(realPosition); } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (view instanceof PinnedHeaderListView) { ((PinnedHeaderListView)view).configureHeaderView(firstVisibleItem); } } public void onScrollStateChanged(AbsListView view, int scrollState) { if (mHighlightWhenScrolling) { if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) { mHighlightingAnimation.startHighlighting(); } else { mHighlightingAnimation.stopHighlighting(); } } if (scrollState == OnScrollListener.SCROLL_STATE_FLING) { mPhotoLoader.pause(); } else if (mDisplayPhotos) { mPhotoLoader.resume(); } } /** * Computes the state of the pinned header. It can be invisible, fully * visible or partially pushed up out of the view. */ public int getPinnedHeaderState(int position) { if (mIndexer == null || mCursor == null || mCursor.getCount() == 0) { return PINNED_HEADER_GONE; } int realPosition = getRealPosition(position); if (realPosition < 0) { return PINNED_HEADER_GONE; } // The header should get pushed up if the top item shown // is the last item in a section for a particular letter. int section = getSectionForPosition(realPosition); int nextSectionPosition = getPositionForSection(section + 1); if (nextSectionPosition != -1 && realPosition == nextSectionPosition - 1) { return PINNED_HEADER_PUSHED_UP; } return PINNED_HEADER_VISIBLE; } /** * Configures the pinned header by setting the appropriate text label * and also adjusting color if necessary. The color needs to be * adjusted when the pinned header is being pushed up from the view. */ public void configurePinnedHeader(View header, int position, int alpha) { PinnedHeaderCache cache = (PinnedHeaderCache)header.getTag(); if (cache == null) { cache = new PinnedHeaderCache(); cache.titleView = (TextView)header.findViewById(R.id.header_text); cache.textColor = cache.titleView.getTextColors(); cache.background = header.getBackground(); header.setTag(cache); } int realPosition = getRealPosition(position); int section = getSectionForPosition(realPosition); String title = (String)mIndexer.getSections()[section]; cache.titleView.setText(title); if (alpha == 255) { // Opaque: use the default background, and the original text color header.setBackgroundDrawable(cache.background); cache.titleView.setTextColor(cache.textColor); } else { // Faded: use a solid color approximation of the background, and // a translucent text color header.setBackgroundColor(Color.rgb( Color.red(mPinnedHeaderBackgroundColor) * alpha / 255, Color.green(mPinnedHeaderBackgroundColor) * alpha / 255, Color.blue(mPinnedHeaderBackgroundColor) * alpha / 255)); int textColor = cache.textColor.getDefaultColor(); cache.titleView.setTextColor(Color.argb(alpha, Color.red(textColor), Color.green(textColor), Color.blue(textColor))); } } } }
false
true
protected void onCreate(Bundle icicle) { super.onCreate(icicle); mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size); mContactsPrefs = new ContactsPreferences(this); mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } String action = intent.getAction(); String component = intent.getComponent().getClassName(); // When we get a FILTER_CONTACTS_ACTION, it represents search in the context // of some other action. Let's retrieve the original action to provide proper // context for the search queries. if (UI.FILTER_CONTACTS_ACTION.equals(action)) { mSearchMode = true; mShowSearchSnippets = true; Bundle extras = intent.getExtras(); if (extras != null) { mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY); String originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); if (originalAction != null) { action = originalAction; } String originalComponent = extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY); if (originalComponent != null) { component = originalComponent; } } else { mInitialFilter = null; } } Log.i(TAG, "Called with action: " + action); mMode = MODE_UNKNOWN; if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) { mMode = MODE_DEFAULT; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUri(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = false; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = true; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (Contacts.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PERSON; } else if (Phone.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (component.equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; setTitle(R.string.callShortcutActivityTitle); } else if (component.equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; setTitle(R.string.messageShortcutActivityTitle); } else if (mSearchMode) { mMode = MODE_PICK_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (Contacts.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_PICK_OR_CREATE_CONTACT; } } else if (Phone.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } else if (People.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_LEGACY_PICK_PERSON; } else { mMode = MODE_LEGACY_PICK_OR_CREATE_PERSON; } } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mInitialFilter = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; } else if (ACTION_SEARCH_INTERNAL.equals(action)) { String originalAction = null; Bundle extras = intent.getExtras(); if (extras != null) { originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); } mShortcutAction = intent.getStringExtra(SHORTCUT_ACTION_KEY); if (Intent.ACTION_INSERT_OR_EDIT.equals(originalAction)) { mMode = MODE_QUERY_PICK_TO_EDIT; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } else if (mShortcutAction != null && intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_PHONE; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { mMode = MODE_QUERY_PICK; mQueryMode = QUERY_MODE_NONE; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { Uri data = intent.getData(); Uri telUri = null; if (sContactsIdMatcher.match(data) == CONTACTS_ID) { long contactId = Long.valueOf(data.getLastPathSegment()); final Cursor cursor = queryPhoneNumbers(contactId); if (cursor != null) { if (cursor.getCount() == 1 && cursor.moveToFirst()) { int phoneNumberIndex = cursor.getColumnIndex(Phone.NUMBER); String phoneNumber = cursor.getString(phoneNumberIndex); telUri = Uri.parse("tel:" + phoneNumber); } cursor.close(); } } // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG)) && telUri != null) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, telUri); } else { newIntent = new Intent(Intent.ACTION_VIEW, data); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { // TODO actually support this in EditContactActivity. String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (JOIN_AGGREGATE.equals(action)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_JOIN_CONTACT; mQueryAggregateId = intent.getLongExtra(EXTRA_AGGREGATE_ID, -1); if (mQueryAggregateId == -1) { Log.e(TAG, "Intent " + action + " is missing required extra: " + EXTRA_AGGREGATE_ID); setResult(RESULT_CANCELED); finish(); } } } if (mMode == MODE_UNKNOWN) { mMode = MODE_DEFAULT; } if (((mMode & MODE_MASK_SHOW_NUMBER_OF_CONTACTS) != 0 || mSearchMode) && !mSearchResultsMode) { mShowNumberOfContacts = true; } if (mMode == MODE_JOIN_CONTACT) { setContentView(R.layout.contacts_list_content_join); TextView blurbView = (TextView)findViewById(R.id.join_contact_blurb); String blurb = getString(R.string.blurbJoinContactDataWith, getContactDisplayName(mQueryAggregateId)); blurbView.setText(blurb); mJoinModeShowAllContacts = true; } else if (mSearchMode) { setContentView(R.layout.contacts_search_content); } else if (mSearchResultsMode) { setContentView(R.layout.contacts_list_search_results); TextView titleText = (TextView)findViewById(R.id.search_results_for); titleText.setText(Html.fromHtml(getString(R.string.search_results_for, "<b>" + mInitialFilter + "</b>"))); } else { setContentView(R.layout.contacts_list_content); } setupListView(); if (mSearchMode) { setupSearchView(); } mQueryHandler = new QueryHandler(this); mJustCreated = true; mSyncEnabled = true; }
protected void onCreate(Bundle icicle) { super.onCreate(icicle); mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size); mContactsPrefs = new ContactsPreferences(this); mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } String action = intent.getAction(); String component = intent.getComponent().getClassName(); // When we get a FILTER_CONTACTS_ACTION, it represents search in the context // of some other action. Let's retrieve the original action to provide proper // context for the search queries. if (UI.FILTER_CONTACTS_ACTION.equals(action)) { mSearchMode = true; mShowSearchSnippets = true; Bundle extras = intent.getExtras(); if (extras != null) { mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY); String originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); if (originalAction != null) { action = originalAction; } String originalComponent = extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY); if (originalComponent != null) { component = originalComponent; } } else { mInitialFilter = null; } } Log.i(TAG, "Called with action: " + action); mMode = MODE_UNKNOWN; if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) { mMode = MODE_DEFAULT; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUri(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = false; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = true; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (Contacts.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PERSON; } else if (Phone.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (component.equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; mShowSearchSnippets = false; setTitle(R.string.callShortcutActivityTitle); } else if (component.equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; mShowSearchSnippets = false; setTitle(R.string.messageShortcutActivityTitle); } else if (mSearchMode) { mMode = MODE_PICK_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (Contacts.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_PICK_OR_CREATE_CONTACT; } } else if (Phone.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } else if (People.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_LEGACY_PICK_PERSON; } else { mMode = MODE_LEGACY_PICK_OR_CREATE_PERSON; } } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mInitialFilter = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; } else if (ACTION_SEARCH_INTERNAL.equals(action)) { String originalAction = null; Bundle extras = intent.getExtras(); if (extras != null) { originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); } mShortcutAction = intent.getStringExtra(SHORTCUT_ACTION_KEY); if (Intent.ACTION_INSERT_OR_EDIT.equals(originalAction)) { mMode = MODE_QUERY_PICK_TO_EDIT; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } else if (mShortcutAction != null && intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_PHONE; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { mMode = MODE_QUERY_PICK; mQueryMode = QUERY_MODE_NONE; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { Uri data = intent.getData(); Uri telUri = null; if (sContactsIdMatcher.match(data) == CONTACTS_ID) { long contactId = Long.valueOf(data.getLastPathSegment()); final Cursor cursor = queryPhoneNumbers(contactId); if (cursor != null) { if (cursor.getCount() == 1 && cursor.moveToFirst()) { int phoneNumberIndex = cursor.getColumnIndex(Phone.NUMBER); String phoneNumber = cursor.getString(phoneNumberIndex); telUri = Uri.parse("tel:" + phoneNumber); } cursor.close(); } } // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG)) && telUri != null) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, telUri); } else { newIntent = new Intent(Intent.ACTION_VIEW, data); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { // TODO actually support this in EditContactActivity. String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (JOIN_AGGREGATE.equals(action)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_JOIN_CONTACT; mQueryAggregateId = intent.getLongExtra(EXTRA_AGGREGATE_ID, -1); if (mQueryAggregateId == -1) { Log.e(TAG, "Intent " + action + " is missing required extra: " + EXTRA_AGGREGATE_ID); setResult(RESULT_CANCELED); finish(); } } } if (mMode == MODE_UNKNOWN) { mMode = MODE_DEFAULT; } if (((mMode & MODE_MASK_SHOW_NUMBER_OF_CONTACTS) != 0 || mSearchMode) && !mSearchResultsMode) { mShowNumberOfContacts = true; } if (mMode == MODE_JOIN_CONTACT) { setContentView(R.layout.contacts_list_content_join); TextView blurbView = (TextView)findViewById(R.id.join_contact_blurb); String blurb = getString(R.string.blurbJoinContactDataWith, getContactDisplayName(mQueryAggregateId)); blurbView.setText(blurb); mJoinModeShowAllContacts = true; } else if (mSearchMode) { setContentView(R.layout.contacts_search_content); } else if (mSearchResultsMode) { setContentView(R.layout.contacts_list_search_results); TextView titleText = (TextView)findViewById(R.id.search_results_for); titleText.setText(Html.fromHtml(getString(R.string.search_results_for, "<b>" + mInitialFilter + "</b>"))); } else { setContentView(R.layout.contacts_list_content); } setupListView(); if (mSearchMode) { setupSearchView(); } mQueryHandler = new QueryHandler(this); mJustCreated = true; mSyncEnabled = true; }
diff --git a/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobGraph.java b/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobGraph.java index b206e5274..16749b69e 100644 --- a/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobGraph.java +++ b/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobGraph.java @@ -1,850 +1,850 @@ /*********************************************************************************************************************** * * Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.nephele.jobgraph; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; 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 java.util.Stack; import java.util.Vector; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import eu.stratosphere.nephele.configuration.Configuration; import eu.stratosphere.nephele.execution.librarycache.LibraryCacheManager; import eu.stratosphere.nephele.fs.FSDataInputStream; import eu.stratosphere.nephele.fs.FileStatus; import eu.stratosphere.nephele.fs.FileSystem; import eu.stratosphere.nephele.fs.Path; import eu.stratosphere.nephele.types.Record; import eu.stratosphere.nephele.util.ClassUtils; import eu.stratosphere.nephele.util.StringUtils; /** * A job graph represents an entire job in Nephele. A job graph must consists at least of one job vertex * and must be acyclic. * * @author warneke */ public class JobGraph implements KryoSerializable { /** * List of input vertices included in this job graph. */ private Map<JobVertexID, AbstractJobInputVertex> inputVertices = new HashMap<JobVertexID, AbstractJobInputVertex>(); /** * List of output vertices included in this job graph. */ private Map<JobVertexID, AbstractJobOutputVertex> outputVertices = new HashMap<JobVertexID, AbstractJobOutputVertex>(); /** * List of task vertices included in this job graph. */ private Map<JobVertexID, JobTaskVertex> taskVertices = new HashMap<JobVertexID, JobTaskVertex>(); /** * ID of this job. */ private JobID jobID; /** * Name of this job. */ private String jobName; /** * The job configuration attached to this job. */ private Configuration jobConfiguration = new Configuration(); /** * The configuration which should be applied to the task managers involved in processing this job. */ private final Configuration taskManagerConfiguration = new Configuration(); /** * List of JAR files required to run this job. */ private final ArrayList<Path> userJars = new ArrayList<Path>(); /** * Size of the buffer to be allocated for transferring attached files. */ private static final int BUFFERSIZE = 8192; /** * Constructs a new job graph with a random job ID. */ public JobGraph() { this.jobID = JobID.generate(); } /** * Constructs a new job graph with the given name and a random job ID. * * @param jobName * the name for this job graph */ public JobGraph(final String jobName) { this(); this.jobName = jobName; } /** * Returns the name assigned to the job graph. * * @return the name assigned to the job graph */ public String getName() { return this.jobName; } /** * Returns the configuration object for this job if it is set. * * @return the configuration object for this job, or <code>null</code> if it is not set */ public Configuration getJobConfiguration() { return this.jobConfiguration; } /** * Returns the configuration object distributed among the task managers * before they start processing this job. * * @return the configuration object for the task managers, or <code>null</code> if it is not set */ public Configuration getTaskmanagerConfiguration() { return this.taskManagerConfiguration; } /** * Adds a new input vertex to the job graph if it is not already included. * * @param inputVertex * the new input vertex to be added */ public void addVertex(final AbstractJobInputVertex inputVertex) { if (!inputVertices.containsKey(inputVertex.getID())) { inputVertices.put(inputVertex.getID(), inputVertex); } } /** * Adds a new task vertex to the job graph if it is not already included. * * @param taskVertex * the new task vertex to be added */ public void addVertex(final JobTaskVertex taskVertex) { if (!taskVertices.containsKey(taskVertex.getID())) { taskVertices.put(taskVertex.getID(), taskVertex); } } /** * Adds a new output vertex to the job graph if it is not already included. * * @param outputVertex * the new output vertex to be added */ public void addVertex(final AbstractJobOutputVertex outputVertex) { if (!outputVertices.containsKey(outputVertex.getID())) { outputVertices.put(outputVertex.getID(), outputVertex); } } /** * Returns the number of input vertices registered with the job graph. * * @return the number of input vertices registered with the job graph */ public int getNumberOfInputVertices() { return this.inputVertices.size(); } /** * Returns the number of output vertices registered with the job graph. * * @return the number of output vertices registered with the job graph */ public int getNumberOfOutputVertices() { return this.outputVertices.size(); } /** * Returns the number of task vertices registered with the job graph. * * @return the number of task vertices registered with the job graph */ public int getNumberOfTaskVertices() { return this.taskVertices.size(); } /** * Returns an iterator to iterate all input vertices registered with the job graph. * * @return an iterator to iterate all input vertices registered with the job graph */ public Iterator<AbstractJobInputVertex> getInputVertices() { final Collection<AbstractJobInputVertex> coll = this.inputVertices.values(); return coll.iterator(); } /** * Returns an iterator to iterate all output vertices registered with the job graph. * * @return an iterator to iterate all output vertices registered with the job graph */ public Iterator<AbstractJobOutputVertex> getOutputVertices() { final Collection<AbstractJobOutputVertex> coll = this.outputVertices.values(); return coll.iterator(); } /** * Returns an iterator to iterate all task vertices registered with the job graph. * * @return an iterator to iterate all task vertices registered with the job graph */ public Iterator<JobTaskVertex> getTaskVertices() { final Collection<JobTaskVertex> coll = this.taskVertices.values(); return coll.iterator(); } /** * Returns the number of all job vertices registered with this job graph. * * @return the number of all job vertices registered with this job graph */ public int getNumberOfVertices() { return this.inputVertices.size() + this.outputVertices.size() + this.taskVertices.size(); } /** * Returns an array of all job vertices than can be reached when traversing the job graph from the input vertices. * * @return an array of all job vertices than can be reached when traversing the job graph from the input vertices */ public AbstractJobVertex[] getAllReachableJobVertices() { final Vector<AbstractJobVertex> collector = new Vector<AbstractJobVertex>(); collectVertices(null, collector); return collector.toArray(new AbstractJobVertex[0]); } /** * Returns an array of all job vertices that are registered with the job graph. The order in which the vertices * appear in the list is not defined. * * @return an array of all job vertices that are registered with the job graph */ public AbstractJobVertex[] getAllJobVertices() { int i = 0; final AbstractJobVertex[] vertices = new AbstractJobVertex[inputVertices.size() + outputVertices.size() + taskVertices.size()]; final Iterator<AbstractJobInputVertex> iv = getInputVertices(); while (iv.hasNext()) { vertices[i++] = iv.next(); } final Iterator<AbstractJobOutputVertex> ov = getOutputVertices(); while (ov.hasNext()) { vertices[i++] = ov.next(); } final Iterator<JobTaskVertex> tv = getTaskVertices(); while (tv.hasNext()) { vertices[i++] = tv.next(); } return vertices; } /** * Auxiliary method to collect all vertices which are reachable from the input vertices. * * @param jv * the currently considered job vertex * @param collector * a temporary list to store the vertices that have already been visisted */ private void collectVertices(final AbstractJobVertex jv, final List<AbstractJobVertex> collector) { if (jv == null) { final Iterator<AbstractJobInputVertex> iter = getInputVertices(); while (iter.hasNext()) { collectVertices(iter.next(), collector); } } else { if (!collector.contains(jv)) { collector.add(jv); } else { return; } for (int i = 0; i < jv.getNumberOfForwardConnections(); i++) { collectVertices(jv.getForwardConnection(i).getConnectedVertex(), collector); } } } /** * Returns the ID of the job. * * @return the ID of the job */ public JobID getJobID() { return this.jobID; } /** * Searches for a vertex with a matching ID and returns it. * * @param id * the ID of the vertex to search for * @return the vertex with the matching ID or <code>null</code> if no vertex with such ID could be found */ public AbstractJobVertex findVertexByID(final JobVertexID id) { if (this.inputVertices.containsKey(id)) { return this.inputVertices.get(id); } if (this.outputVertices.containsKey(id)) { return this.outputVertices.get(id); } if (this.taskVertices.containsKey(id)) { return this.taskVertices.get(id); } return null; } /** * Checks if the job vertex with the given ID is registered with the job graph. * * @param id * the ID of the vertex to search for * @return <code>true</code> if a vertex with the given ID is registered with the job graph, <code>false</code> * otherwise. */ private boolean includedInJobGraph(final JobVertexID id) { if (this.inputVertices.containsKey(id)) { return true; } if (this.outputVertices.containsKey(id)) { return true; } if (this.taskVertices.containsKey(id)) { return true; } return false; } /** * Checks if the job graph is weakly connected. * * @return <code>true</code> if the job graph is weakly connected, otherwise <code>false</code> */ public boolean isWeaklyConnected() { final AbstractJobVertex[] reachable = getAllReachableJobVertices(); final AbstractJobVertex[] all = getAllJobVertices(); // Check if number if reachable vertices matches number of registered vertices if (reachable.length != all.length) { return false; } final HashMap<JobVertexID, AbstractJobVertex> tmp = new HashMap<JobVertexID, AbstractJobVertex>(); for (int i = 0; i < reachable.length; i++) { tmp.put(reachable[i].getID(), reachable[i]); } // Check if all is subset of reachable for (int i = 0; i < all.length; i++) { if (!tmp.containsKey(all[i].getID())) { return false; } } // Check if reachable is a subset of all for (int i = 0; i < reachable.length; i++) { if (!includedInJobGraph(reachable[i].getID())) { return false; } } return true; } /** * Checks if the job graph is acyclic. * * @return <code>true</code> if the job graph is acyclic, <code>false</code> otherwise */ public boolean isAcyclic() { // Tarjan's algorithm to detect strongly connected componenent of a graph final AbstractJobVertex[] reachable = getAllReachableJobVertices(); final HashMap<AbstractJobVertex, Integer> indexMap = new HashMap<AbstractJobVertex, Integer>(); final HashMap<AbstractJobVertex, Integer> lowLinkMap = new HashMap<AbstractJobVertex, Integer>(); final Stack<AbstractJobVertex> stack = new Stack<AbstractJobVertex>(); final Integer index = Integer.valueOf(0); for (int i = 0; i < reachable.length; i++) { if (!indexMap.containsKey(reachable[i])) { if (!tarjan(reachable[i], index, indexMap, lowLinkMap, stack)) { return false; } } } return true; } /** * Auxiliary method implementing Tarjan's algorithm for strongly-connected components to determine whether the job * graph is acyclic. */ private boolean tarjan(final AbstractJobVertex jv, Integer index, final HashMap<AbstractJobVertex, Integer> indexMap, final HashMap<AbstractJobVertex, Integer> lowLinkMap, final Stack<AbstractJobVertex> stack) { indexMap.put(jv, Integer.valueOf(index)); lowLinkMap.put(jv, Integer.valueOf(index)); index = Integer.valueOf(index.intValue() + 1); stack.push(jv); for (int i = 0; i < jv.getNumberOfForwardConnections(); i++) { final AbstractJobVertex jv2 = jv.getForwardConnection(i).getConnectedVertex(); if (!indexMap.containsKey(jv2) || stack.contains(jv2)) { if (!indexMap.containsKey(jv2)) { if (!tarjan(jv2, index, indexMap, lowLinkMap, stack)) { return false; } } if (lowLinkMap.get(jv) > lowLinkMap.get(jv2)) { lowLinkMap.put(jv, Integer.valueOf(lowLinkMap.get(jv2))); } } } if (lowLinkMap.get(jv).equals(indexMap.get(jv))) { int count = 0; while (stack.size() > 0) { final AbstractJobVertex jv2 = stack.pop(); if (jv == jv2) { break; } count++; } if (count > 0) { return false; } } return true; } /** * Checks for all registered job vertices if their in-/out-degree is correct. * * @return <code>null</code> if the in-/out-degree of all vertices is correct or the first job vertex whose * in-/out-degree is incorrect. */ public AbstractJobVertex areVertexDegreesCorrect() { // Check input vertices final Iterator<AbstractJobInputVertex> iter = getInputVertices(); while (iter.hasNext()) { final AbstractJobVertex jv = iter.next(); if (jv.getNumberOfForwardConnections() < 1 || jv.getNumberOfBackwardConnections() > 0) { return jv; } } // Check task vertices final Iterator<JobTaskVertex> iter2 = getTaskVertices(); while (iter2.hasNext()) { final AbstractJobVertex jv = iter2.next(); if (jv.getNumberOfForwardConnections() < 1 || jv.getNumberOfBackwardConnections() < 1) { return jv; } } // Check output vertices final Iterator<AbstractJobOutputVertex> iter3 = getOutputVertices(); while (iter3.hasNext()) { final AbstractJobVertex jv = iter3.next(); if (jv.getNumberOfForwardConnections() > 0 || jv.getNumberOfBackwardConnections() < 1) { return jv; } } return null; } /** * Writes the JAR files of all vertices in array <code>jobVertices</code> to the specified output stream. * * @param kryo * the kryo object * @param out * the output stream to write the JAR files to * @param jobVertices * array of job vertices whose required JAR file are to be written to the output stream * @throws IOException * thrown if an error occurs while writing to the stream */ private void writeRequiredJarFiles(final Kryo kryo, final Output out, final AbstractJobVertex[] jobVertices) throws IOException { // Now check if all the collected jar files really exist final FileSystem fs = FileSystem.getLocalFileSystem(); for (int i = 0; i < this.userJars.size(); i++) { if (!fs.exists(this.userJars.get(i))) { throw new IOException("Cannot find jar file " + this.userJars.get(i)); } } // How many jar files follow? out.writeInt(this.userJars.size()); for (int i = 0; i < this.userJars.size(); i++) { final Path jar = this.userJars.get(i); // Write out the actual path jar.write(kryo, out); // Write out the length of the file final FileStatus file = fs.getFileStatus(jar); out.writeInt((int) file.getLen()); // Now write the jar file final FSDataInputStream inStream = fs.open(this.userJars.get(i)); final byte[] buf = new byte[BUFFERSIZE]; int read = inStream.read(buf, 0, buf.length); while (read > 0) { out.write(buf, 0, read); read = inStream.read(buf, 0, buf.length); } } } /** * Reads required JAR files from an input stream and adds them to the * library cache manager. * * @param kryo * the kryo object * @param input * the data stream to read the JAR files from * @throws IOException * thrown if an error occurs while reading the stream */ private void readRequiredJarFiles(final Kryo kryo, final Input input) throws IOException { // Do jar files follow; final int numJars = input.readInt(); if (numJars > 0) { for (int i = 0; i < numJars; i++) { final Path p = new Path(); p.read(kryo, input); this.userJars.add(p); // Read the size of the jar file final int sizeOfJar = input.readInt(); // Add the jar to the library manager LibraryCacheManager.addLibrary(this.jobID, p, sizeOfJar, input); } } // Register this job with the library cache manager LibraryCacheManager.register(this.jobID, this.userJars.toArray(new Path[0])); } /** * Adds the path of a JAR file required to run the job on a task manager. * * @param jar * path of the JAR file required to run the job on a task manager */ public void addJar(final Path jar) { if (jar == null) { return; } if (!userJars.contains(jar)) { userJars.add(jar); } } /** * Returns a (possibly empty) array of paths to JAR files which are required to run the job on a task manager. * * @return a (possibly empty) array of paths to JAR files which are required to run the job on a task manager */ public Path[] getJars() { return userJars.toArray(new Path[userJars.size()]); } /** * Checks if any vertex of this job graph has an outgoing edge which is set to <code>null</code>. If this is the * case the respective vertex is returned. * * @return the vertex which has an outgoing edge set to <code>null</code> or <code>null</code> if no such vertex * exists */ public AbstractJobVertex findVertexWithNullEdges() { final AbstractJobVertex[] allVertices = getAllJobVertices(); for (int i = 0; i < allVertices.length; i++) { for (int j = 0; j < allVertices[i].getNumberOfForwardConnections(); j++) { if (allVertices[i].getForwardConnection(j) == null) { return allVertices[i]; } } for (int j = 0; j < allVertices[i].getNumberOfBackwardConnections(); j++) { if (allVertices[i].getBackwardConnection(j) == null) { return allVertices[i]; } } } return null; } /** * Checks if the instance dependency chain created with the <code>setVertexToShareInstancesWith</code> method is * acyclic. * * @return <code>true</code> if the dependency chain is acyclic, <code>false</code> otherwise */ public boolean isInstanceDependencyChainAcyclic() { final AbstractJobVertex[] allVertices = this.getAllJobVertices(); final Set<AbstractJobVertex> alreadyVisited = new HashSet<AbstractJobVertex>(); for (AbstractJobVertex vertex : allVertices) { if (alreadyVisited.contains(vertex)) { continue; } AbstractJobVertex vertexToShareInstancesWith = vertex.getVertexToShareInstancesWith(); if (vertexToShareInstancesWith != null) { final Set<AbstractJobVertex> cycleMap = new HashSet<AbstractJobVertex>(); while (vertexToShareInstancesWith != null) { if (cycleMap.contains(vertexToShareInstancesWith)) { return false; } else { alreadyVisited.add(vertexToShareInstancesWith); cycleMap.add(vertexToShareInstancesWith); vertexToShareInstancesWith = vertexToShareInstancesWith.getVertexToShareInstancesWith(); } } } } return true; } /** * {@inheritDoc} */ @Override public void write(final Kryo kryo, final Output output) { // Write job ID kryo.writeObject(output, this.jobID); // Write out job name output.writeString(this.jobName); final AbstractJobVertex[] allVertices = this.getAllJobVertices(); // Write out all required jar files try { writeRequiredJarFiles(kryo, output, allVertices); } catch (IOException ioe) { throw new RuntimeException(ioe); } // Write total number of vertices output.writeInt(allVertices.length); // First write out class name and id for every vertex for (int i = 0; i < allVertices.length; i++) { final String className = allVertices[i].getClass().getName(); output.writeString(className); kryo.writeObject(output, allVertices[i].getID()); output.writeString(allVertices[i].getName()); } // Now write out vertices themselves for (int i = 0; i < allVertices.length; i++) { kryo.writeObject(output, allVertices[i].getID()); allVertices[i].write(kryo, output); } // Write out configuration objects this.jobConfiguration.write(kryo, output); this.taskManagerConfiguration.write(kryo, output); } /** * {@inheritDoc} */ @Override public void read(final Kryo kryo, final Input input) { // Read job id - this.jobID = kryo.readObjectOrNull(input, JobID.class); + this.jobID = kryo.readObject(input, JobID.class); // Read the job name this.jobName = input.readString(); // Read required jar files try { readRequiredJarFiles(kryo, input); } catch (IOException ioe) { new RuntimeException(ioe); } // First read total number of vertices; final int numVertices = input.readInt(); // First, recreate each vertex and add it to reconstructionMap for (int i = 0; i < numVertices; i++) { final String className = input.readString(); final JobVertexID id = kryo.readObject(input, JobVertexID.class); final String vertexName = input.readString(); Class<? extends Record> c; try { c = ClassUtils.getRecordByName(className); } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe.toString()); } // Find constructor Constructor<? extends Record> cst; try { cst = c.getConstructor(String.class, JobVertexID.class, JobGraph.class); cst.newInstance(vertexName, id, this); } catch (Exception e) { throw new RuntimeException(e.toString()); } } for (int i = 0; i < numVertices; i++) { AbstractJobVertex jv; final JobVertexID tmpID = kryo.readObject(input, JobVertexID.class); if (inputVertices.containsKey(tmpID)) { jv = inputVertices.get(tmpID); } else { if (outputVertices.containsKey(tmpID)) { jv = outputVertices.get(tmpID); } else { if (taskVertices.containsKey(tmpID)) { jv = taskVertices.get(tmpID); } else { throw new IllegalStateException("Cannot find vertex with ID " + tmpID + " in any vertex map."); } } } // Read the vertex data jv.read(kryo, input); } // Find the class loader for the job ClassLoader cl = null; try { cl = LibraryCacheManager.getClassLoader(this.jobID); } catch (IOException ioe) { throw new RuntimeException("Error initializing class loader: " + StringUtils.stringifyException(ioe)); } // Re-instantiate the job configuration object and read the configuration this.jobConfiguration = new Configuration(cl); this.jobConfiguration.read(kryo, input); // Read the task manager configuration this.taskManagerConfiguration.read(kryo, input); } }
true
true
public void read(final Kryo kryo, final Input input) { // Read job id this.jobID = kryo.readObjectOrNull(input, JobID.class); // Read the job name this.jobName = input.readString(); // Read required jar files try { readRequiredJarFiles(kryo, input); } catch (IOException ioe) { new RuntimeException(ioe); } // First read total number of vertices; final int numVertices = input.readInt(); // First, recreate each vertex and add it to reconstructionMap for (int i = 0; i < numVertices; i++) { final String className = input.readString(); final JobVertexID id = kryo.readObject(input, JobVertexID.class); final String vertexName = input.readString(); Class<? extends Record> c; try { c = ClassUtils.getRecordByName(className); } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe.toString()); } // Find constructor Constructor<? extends Record> cst; try { cst = c.getConstructor(String.class, JobVertexID.class, JobGraph.class); cst.newInstance(vertexName, id, this); } catch (Exception e) { throw new RuntimeException(e.toString()); } } for (int i = 0; i < numVertices; i++) { AbstractJobVertex jv; final JobVertexID tmpID = kryo.readObject(input, JobVertexID.class); if (inputVertices.containsKey(tmpID)) { jv = inputVertices.get(tmpID); } else { if (outputVertices.containsKey(tmpID)) { jv = outputVertices.get(tmpID); } else { if (taskVertices.containsKey(tmpID)) { jv = taskVertices.get(tmpID); } else { throw new IllegalStateException("Cannot find vertex with ID " + tmpID + " in any vertex map."); } } } // Read the vertex data jv.read(kryo, input); } // Find the class loader for the job ClassLoader cl = null; try { cl = LibraryCacheManager.getClassLoader(this.jobID); } catch (IOException ioe) { throw new RuntimeException("Error initializing class loader: " + StringUtils.stringifyException(ioe)); } // Re-instantiate the job configuration object and read the configuration this.jobConfiguration = new Configuration(cl); this.jobConfiguration.read(kryo, input); // Read the task manager configuration this.taskManagerConfiguration.read(kryo, input); }
public void read(final Kryo kryo, final Input input) { // Read job id this.jobID = kryo.readObject(input, JobID.class); // Read the job name this.jobName = input.readString(); // Read required jar files try { readRequiredJarFiles(kryo, input); } catch (IOException ioe) { new RuntimeException(ioe); } // First read total number of vertices; final int numVertices = input.readInt(); // First, recreate each vertex and add it to reconstructionMap for (int i = 0; i < numVertices; i++) { final String className = input.readString(); final JobVertexID id = kryo.readObject(input, JobVertexID.class); final String vertexName = input.readString(); Class<? extends Record> c; try { c = ClassUtils.getRecordByName(className); } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe.toString()); } // Find constructor Constructor<? extends Record> cst; try { cst = c.getConstructor(String.class, JobVertexID.class, JobGraph.class); cst.newInstance(vertexName, id, this); } catch (Exception e) { throw new RuntimeException(e.toString()); } } for (int i = 0; i < numVertices; i++) { AbstractJobVertex jv; final JobVertexID tmpID = kryo.readObject(input, JobVertexID.class); if (inputVertices.containsKey(tmpID)) { jv = inputVertices.get(tmpID); } else { if (outputVertices.containsKey(tmpID)) { jv = outputVertices.get(tmpID); } else { if (taskVertices.containsKey(tmpID)) { jv = taskVertices.get(tmpID); } else { throw new IllegalStateException("Cannot find vertex with ID " + tmpID + " in any vertex map."); } } } // Read the vertex data jv.read(kryo, input); } // Find the class loader for the job ClassLoader cl = null; try { cl = LibraryCacheManager.getClassLoader(this.jobID); } catch (IOException ioe) { throw new RuntimeException("Error initializing class loader: " + StringUtils.stringifyException(ioe)); } // Re-instantiate the job configuration object and read the configuration this.jobConfiguration = new Configuration(cl); this.jobConfiguration.read(kryo, input); // Read the task manager configuration this.taskManagerConfiguration.read(kryo, input); }
diff --git a/h2/src/test/org/h2/test/unit/TestShell.java b/h2/src/test/org/h2/test/unit/TestShell.java index 99c72c0d0..070474eb0 100644 --- a/h2/src/test/org/h2/test/unit/TestShell.java +++ b/h2/src/test/org/h2/test/unit/TestShell.java @@ -1,239 +1,237 @@ /* * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.test.unit; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import org.h2.test.TestBase; import org.h2.tools.Shell; import org.h2.util.Task; /** * Test the shell tool. */ public class TestShell extends TestBase { /** * The output stream of the tool. */ PrintStream toolOut; /** * The input stream of the tool. */ InputStream toolIn; private PrintStream testOut; private PipedInputStream testIn; private LineNumberReader lineReader; /** * Run just this test. * * @param a ignored */ public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); } public void test() throws Exception { Shell shell = new Shell(); ByteArrayOutputStream buff = new ByteArrayOutputStream(); shell.setOut(new PrintStream(buff)); shell.runTool("-url", "jdbc:h2:mem:", "-driver", "org.h2.Driver", "-user", "sa", "-password", "sa", "-properties", "null", "-sql", "select 'Hello ' || 'World' as hi"); String s = new String(buff.toByteArray()); assertContains(s, "HI"); assertContains(s, "Hello World"); assertContains(s, "(1 row, "); shell = new Shell(); buff = new ByteArrayOutputStream(); shell.setOut(new PrintStream(buff)); shell.runTool("-help"); s = new String(buff.toByteArray()); assertContains(s, "Interactive command line tool to access a database using JDBC."); test(true); test(false); } private void test(final boolean commandLineArgs) throws IOException { testIn = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(testIn); toolOut = new PrintStream(out, true); out = new PipedOutputStream(); testOut = new PrintStream(out, true); toolIn = new PipedInputStream(out); Task task = new Task() { public void call() throws Exception { try { Shell shell = new Shell(); shell.setIn(toolIn); shell.setOut(toolOut); shell.setErr(toolOut); if (commandLineArgs) { shell.runTool("-url", "jdbc:h2:mem:", "-user", "sa", "-password", "sa"); } else { shell.runTool(); } } finally { toolOut.close(); } } }; task.execute(); InputStreamReader reader = new InputStreamReader(testIn); lineReader = new LineNumberReader(reader); read(""); read("Welcome to H2 Shell"); read("Exit with"); if (!commandLineArgs) { read("[Enter]"); testOut.println("jdbc:h2:mem:"); read("URL"); testOut.println(""); read("Driver"); testOut.println("sa"); read("User"); testOut.println("sa"); read("Password"); } read("Commands are case insensitive"); read("help or ?"); read("list"); read("maxwidth"); read("autocommit"); read("history"); read("quit or exit"); read(""); testOut.println("history"); read("sql> No history"); testOut.println("1"); read("sql> Not found"); testOut.println("select 1 a;"); read("sql> A"); read("1"); read("(1 row,"); testOut.println("history"); read("sql> #1: select 1 a"); read("To re-run a statement, type the number and press and enter"); testOut.println("1"); read("sql> select 1 a"); read("A"); read("1"); read("(1 row,"); testOut.println("select 'x' || space(1000) large, 'y' small;"); read("sql> LARGE"); read("x"); read("(data is partially truncated)"); read("(1 row,"); testOut.println("select x, 's' s from system_range(0, 10001);"); read("sql> X | S"); for (int i = 0; i < 10000; i++) { read((i + " ").substring(0, 4) + " | s"); } for (int i = 10000; i <= 10001; i++) { read((i + " ").substring(0, 5) + " | s"); } read("(10002 rows,"); testOut.println("select error;"); read("sql> Error:"); if (read("").startsWith("Column \"ERROR\" not found")) { read(""); } testOut.println("create table test(id int primary key, name varchar)\n;"); read("sql> ...>"); testOut.println("insert into test values(1, 'Hello');"); read("sql>"); testOut.println("select null n, * from test;"); read("sql> N | ID | NAME"); read("null | 1 | Hello"); read("(1 row,"); // test history for (int i = 0; i < 30; i++) { testOut.println("select " + i + " ID from test;"); read("sql> ID"); read("" + i); read("(1 row,"); } testOut.println("20"); read("sql> select 10 ID from test"); read("ID"); read("10"); read("(1 row,"); testOut.println("maxwidth"); read("sql> Usage: maxwidth <integer value>"); read("Maximum column width is now 100"); testOut.println("maxwidth 80"); read("sql> Maximum column width is now 80"); testOut.println("autocommit"); read("sql> Usage: autocommit [true|false]"); read("Autocommit is now true"); testOut.println("autocommit false"); read("sql> Autocommit is now false"); testOut.println("autocommit true"); read("sql> Autocommit is now true"); - testOut.println("\n;"); - read("sql>"); testOut.println("list"); read("sql> Result list mode is now on"); testOut.println("select 1 first, 2 second;"); read("sql> FIRST : 1"); read("SECOND: 2"); read("(1 row, "); testOut.println("select x from system_range(1, 3);"); read("sql> X: 1"); read(""); read("X: 2"); read(""); read("X: 3"); read("(3 rows, "); testOut.println("select x, 2 as y from system_range(1, 3) where 1 = 0;"); read("sql> X"); read("Y"); read("(0 rows, "); testOut.println("list"); read("sql> Result list mode is now off"); testOut.println("help"); read("sql> Commands are case insensitive"); read("help or ?"); read("list"); read("maxwidth"); read("autocommit"); read("history"); read("quit or exit"); read(""); testOut.println("exit"); read("sql>"); task.get(); } private String read(String expectedStart) throws IOException { String line = lineReader.readLine(); // System.out.println(": " + line); assertStartsWith(line, expectedStart); return line; } }
true
true
private void test(final boolean commandLineArgs) throws IOException { testIn = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(testIn); toolOut = new PrintStream(out, true); out = new PipedOutputStream(); testOut = new PrintStream(out, true); toolIn = new PipedInputStream(out); Task task = new Task() { public void call() throws Exception { try { Shell shell = new Shell(); shell.setIn(toolIn); shell.setOut(toolOut); shell.setErr(toolOut); if (commandLineArgs) { shell.runTool("-url", "jdbc:h2:mem:", "-user", "sa", "-password", "sa"); } else { shell.runTool(); } } finally { toolOut.close(); } } }; task.execute(); InputStreamReader reader = new InputStreamReader(testIn); lineReader = new LineNumberReader(reader); read(""); read("Welcome to H2 Shell"); read("Exit with"); if (!commandLineArgs) { read("[Enter]"); testOut.println("jdbc:h2:mem:"); read("URL"); testOut.println(""); read("Driver"); testOut.println("sa"); read("User"); testOut.println("sa"); read("Password"); } read("Commands are case insensitive"); read("help or ?"); read("list"); read("maxwidth"); read("autocommit"); read("history"); read("quit or exit"); read(""); testOut.println("history"); read("sql> No history"); testOut.println("1"); read("sql> Not found"); testOut.println("select 1 a;"); read("sql> A"); read("1"); read("(1 row,"); testOut.println("history"); read("sql> #1: select 1 a"); read("To re-run a statement, type the number and press and enter"); testOut.println("1"); read("sql> select 1 a"); read("A"); read("1"); read("(1 row,"); testOut.println("select 'x' || space(1000) large, 'y' small;"); read("sql> LARGE"); read("x"); read("(data is partially truncated)"); read("(1 row,"); testOut.println("select x, 's' s from system_range(0, 10001);"); read("sql> X | S"); for (int i = 0; i < 10000; i++) { read((i + " ").substring(0, 4) + " | s"); } for (int i = 10000; i <= 10001; i++) { read((i + " ").substring(0, 5) + " | s"); } read("(10002 rows,"); testOut.println("select error;"); read("sql> Error:"); if (read("").startsWith("Column \"ERROR\" not found")) { read(""); } testOut.println("create table test(id int primary key, name varchar)\n;"); read("sql> ...>"); testOut.println("insert into test values(1, 'Hello');"); read("sql>"); testOut.println("select null n, * from test;"); read("sql> N | ID | NAME"); read("null | 1 | Hello"); read("(1 row,"); // test history for (int i = 0; i < 30; i++) { testOut.println("select " + i + " ID from test;"); read("sql> ID"); read("" + i); read("(1 row,"); } testOut.println("20"); read("sql> select 10 ID from test"); read("ID"); read("10"); read("(1 row,"); testOut.println("maxwidth"); read("sql> Usage: maxwidth <integer value>"); read("Maximum column width is now 100"); testOut.println("maxwidth 80"); read("sql> Maximum column width is now 80"); testOut.println("autocommit"); read("sql> Usage: autocommit [true|false]"); read("Autocommit is now true"); testOut.println("autocommit false"); read("sql> Autocommit is now false"); testOut.println("autocommit true"); read("sql> Autocommit is now true"); testOut.println("\n;"); read("sql>"); testOut.println("list"); read("sql> Result list mode is now on"); testOut.println("select 1 first, 2 second;"); read("sql> FIRST : 1"); read("SECOND: 2"); read("(1 row, "); testOut.println("select x from system_range(1, 3);"); read("sql> X: 1"); read(""); read("X: 2"); read(""); read("X: 3"); read("(3 rows, "); testOut.println("select x, 2 as y from system_range(1, 3) where 1 = 0;"); read("sql> X"); read("Y"); read("(0 rows, "); testOut.println("list"); read("sql> Result list mode is now off"); testOut.println("help"); read("sql> Commands are case insensitive"); read("help or ?"); read("list"); read("maxwidth"); read("autocommit"); read("history"); read("quit or exit"); read(""); testOut.println("exit"); read("sql>"); task.get(); }
private void test(final boolean commandLineArgs) throws IOException { testIn = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(testIn); toolOut = new PrintStream(out, true); out = new PipedOutputStream(); testOut = new PrintStream(out, true); toolIn = new PipedInputStream(out); Task task = new Task() { public void call() throws Exception { try { Shell shell = new Shell(); shell.setIn(toolIn); shell.setOut(toolOut); shell.setErr(toolOut); if (commandLineArgs) { shell.runTool("-url", "jdbc:h2:mem:", "-user", "sa", "-password", "sa"); } else { shell.runTool(); } } finally { toolOut.close(); } } }; task.execute(); InputStreamReader reader = new InputStreamReader(testIn); lineReader = new LineNumberReader(reader); read(""); read("Welcome to H2 Shell"); read("Exit with"); if (!commandLineArgs) { read("[Enter]"); testOut.println("jdbc:h2:mem:"); read("URL"); testOut.println(""); read("Driver"); testOut.println("sa"); read("User"); testOut.println("sa"); read("Password"); } read("Commands are case insensitive"); read("help or ?"); read("list"); read("maxwidth"); read("autocommit"); read("history"); read("quit or exit"); read(""); testOut.println("history"); read("sql> No history"); testOut.println("1"); read("sql> Not found"); testOut.println("select 1 a;"); read("sql> A"); read("1"); read("(1 row,"); testOut.println("history"); read("sql> #1: select 1 a"); read("To re-run a statement, type the number and press and enter"); testOut.println("1"); read("sql> select 1 a"); read("A"); read("1"); read("(1 row,"); testOut.println("select 'x' || space(1000) large, 'y' small;"); read("sql> LARGE"); read("x"); read("(data is partially truncated)"); read("(1 row,"); testOut.println("select x, 's' s from system_range(0, 10001);"); read("sql> X | S"); for (int i = 0; i < 10000; i++) { read((i + " ").substring(0, 4) + " | s"); } for (int i = 10000; i <= 10001; i++) { read((i + " ").substring(0, 5) + " | s"); } read("(10002 rows,"); testOut.println("select error;"); read("sql> Error:"); if (read("").startsWith("Column \"ERROR\" not found")) { read(""); } testOut.println("create table test(id int primary key, name varchar)\n;"); read("sql> ...>"); testOut.println("insert into test values(1, 'Hello');"); read("sql>"); testOut.println("select null n, * from test;"); read("sql> N | ID | NAME"); read("null | 1 | Hello"); read("(1 row,"); // test history for (int i = 0; i < 30; i++) { testOut.println("select " + i + " ID from test;"); read("sql> ID"); read("" + i); read("(1 row,"); } testOut.println("20"); read("sql> select 10 ID from test"); read("ID"); read("10"); read("(1 row,"); testOut.println("maxwidth"); read("sql> Usage: maxwidth <integer value>"); read("Maximum column width is now 100"); testOut.println("maxwidth 80"); read("sql> Maximum column width is now 80"); testOut.println("autocommit"); read("sql> Usage: autocommit [true|false]"); read("Autocommit is now true"); testOut.println("autocommit false"); read("sql> Autocommit is now false"); testOut.println("autocommit true"); read("sql> Autocommit is now true"); testOut.println("list"); read("sql> Result list mode is now on"); testOut.println("select 1 first, 2 second;"); read("sql> FIRST : 1"); read("SECOND: 2"); read("(1 row, "); testOut.println("select x from system_range(1, 3);"); read("sql> X: 1"); read(""); read("X: 2"); read(""); read("X: 3"); read("(3 rows, "); testOut.println("select x, 2 as y from system_range(1, 3) where 1 = 0;"); read("sql> X"); read("Y"); read("(0 rows, "); testOut.println("list"); read("sql> Result list mode is now off"); testOut.println("help"); read("sql> Commands are case insensitive"); read("help or ?"); read("list"); read("maxwidth"); read("autocommit"); read("history"); read("quit or exit"); read(""); testOut.println("exit"); read("sql>"); task.get(); }
diff --git a/src/de/schildbach/wallet/WalletActivity.java b/src/de/schildbach/wallet/WalletActivity.java index 435e4aa..e55e2a3 100644 --- a/src/de/schildbach/wallet/WalletActivity.java +++ b/src/de/schildbach/wallet/WalletActivity.java @@ -1,218 +1,218 @@ /* * Copyright 2010 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; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.net.UnknownHostException; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.BlockChain; import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.NetworkConnection; import com.google.bitcoin.core.Peer; import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.TransactionInput; import com.google.bitcoin.core.Utils; import com.google.bitcoin.core.Wallet; import com.google.bitcoin.core.WalletEventListener; /** * @author Andreas Schildbach */ public class WalletActivity extends Activity implements WalletEventListener { private static final String WALLET_FILENAME = Constants.TEST ? "wallet-test" : "wallet"; private Wallet wallet; private Peer peer; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Uri intentUri = getIntent().getData(); if (intentUri != null && "bitcoin".equals(intentUri.getScheme())) Toast.makeText(this, "sending coins to " + intentUri.getSchemeSpecificPart() + " not yet implemented", Toast.LENGTH_LONG).show(); setContentView(R.layout.wallet_content); ((TextView) findViewById(R.id.bitcoin_network)).setText(Constants.TEST ? "testnet" : "prodnet"); loadWallet(); updateGUI(); final ECKey key = wallet.keychain.get(0); - final Address address = new Address(Constants.NETWORK_PARAMS, key.getPubKey()); + final Address address = key.toAddress(Constants.NETWORK_PARAMS); final String addressStr = address.toString(); System.out.println("my bitcoin address: " + addressStr + (Constants.TEST ? " (testnet!)" : "")); ((TextView) findViewById(R.id.bitcoin_address)).setText(addressStr); ((ImageView) findViewById(R.id.bitcoin_address_qr)).setImageBitmap(getQRCodeBitmap("bitcoin:" + addressStr)); try { final InetAddress inetAddress = Constants.TEST ? InetAddress.getByName(Constants.TEST_SEED_NODE) : inetAddressFromUnsignedInt(Constants.SEED_NODES[0]); final NetworkConnection conn = new NetworkConnection(inetAddress, Constants.NETWORK_PARAMS); final BlockChain chain = new BlockChain(Constants.NETWORK_PARAMS, wallet); peer = new Peer(Constants.NETWORK_PARAMS, conn, chain); peer.start(); // peer.startBlockChainDownload(); ((TextView) findViewById(R.id.peer_host)).setText(inetAddress.getHostAddress()); wallet.addEventListener(this); } catch (Exception x) { throw new RuntimeException(x); } } public void onCoinsReceived(final Wallet w, final Transaction tx, final BigInteger prevBalance, final BigInteger newBalance) { try { final TransactionInput input = tx.getInputs().get(0); final Address from = input.getFromAddress(); final BigInteger value = tx.getValueSentToMe(w); System.out.println("!!!!!!!!!!!!! got bitcoins: " + from + " " + value + " " + Thread.currentThread().getName()); runOnUiThread(new Runnable() { public void run() { saveWallet(); updateGUI(); } }); } catch (Exception x) { throw new RuntimeException(x); } } @Override protected void onDestroy() { if (peer != null) { peer.disconnect(); peer = null; } saveWallet(); super.onDestroy(); } private void updateGUI() { ((TextView) findViewById(R.id.wallet_balance)).setText(Utils.bitcoinValueToFriendlyString(wallet.getBalance())); } private void loadWallet() { try { final File file = walletFile(); wallet = Wallet.loadFromFile(file); System.out.println("wallet loaded from: " + file); } catch (IOException x) { wallet = new Wallet(Constants.NETWORK_PARAMS); wallet.keychain.add(new ECKey()); } } private void saveWallet() { try { final File file = walletFile(); wallet.saveToFile(file); System.out.println("wallet saved to: " + file); } catch (IOException x) { throw new RuntimeException(x); } } private File walletFile() { return new File(Constants.TEST ? getDir("testnet", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE) : getFilesDir(), WALLET_FILENAME); } private static InetAddress inetAddressFromUnsignedInt(final long l) { final byte[] bytes = { (byte) (l & 0x000000ff), (byte) ((l & 0x0000ff00) >> 8), (byte) ((l & 0x00ff0000) >> 16), (byte) ((l & 0xff000000) >> 24) }; try { return InetAddress.getByAddress(bytes); } catch (final UnknownHostException x) { throw new RuntimeException(x); } } private Bitmap getQRCodeBitmap(final String url) { try { final URLConnection connection = new URL("http://chart.apis.google.com/chart?cht=qr&chs=250x250&chl=" + URLEncoder.encode(url, "ISO-8859-1")).openConnection(); connection.connect(); final BufferedInputStream is = new BufferedInputStream(connection.getInputStream()); final Bitmap bm = BitmapFactory.decodeStream(is); is.close(); return bm; } catch (final IOException x) { x.printStackTrace(); return null; } } }
true
true
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Uri intentUri = getIntent().getData(); if (intentUri != null && "bitcoin".equals(intentUri.getScheme())) Toast.makeText(this, "sending coins to " + intentUri.getSchemeSpecificPart() + " not yet implemented", Toast.LENGTH_LONG).show(); setContentView(R.layout.wallet_content); ((TextView) findViewById(R.id.bitcoin_network)).setText(Constants.TEST ? "testnet" : "prodnet"); loadWallet(); updateGUI(); final ECKey key = wallet.keychain.get(0); final Address address = new Address(Constants.NETWORK_PARAMS, key.getPubKey()); final String addressStr = address.toString(); System.out.println("my bitcoin address: " + addressStr + (Constants.TEST ? " (testnet!)" : "")); ((TextView) findViewById(R.id.bitcoin_address)).setText(addressStr); ((ImageView) findViewById(R.id.bitcoin_address_qr)).setImageBitmap(getQRCodeBitmap("bitcoin:" + addressStr)); try { final InetAddress inetAddress = Constants.TEST ? InetAddress.getByName(Constants.TEST_SEED_NODE) : inetAddressFromUnsignedInt(Constants.SEED_NODES[0]); final NetworkConnection conn = new NetworkConnection(inetAddress, Constants.NETWORK_PARAMS); final BlockChain chain = new BlockChain(Constants.NETWORK_PARAMS, wallet); peer = new Peer(Constants.NETWORK_PARAMS, conn, chain); peer.start(); // peer.startBlockChainDownload(); ((TextView) findViewById(R.id.peer_host)).setText(inetAddress.getHostAddress()); wallet.addEventListener(this); } catch (Exception x) { throw new RuntimeException(x); } }
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Uri intentUri = getIntent().getData(); if (intentUri != null && "bitcoin".equals(intentUri.getScheme())) Toast.makeText(this, "sending coins to " + intentUri.getSchemeSpecificPart() + " not yet implemented", Toast.LENGTH_LONG).show(); setContentView(R.layout.wallet_content); ((TextView) findViewById(R.id.bitcoin_network)).setText(Constants.TEST ? "testnet" : "prodnet"); loadWallet(); updateGUI(); final ECKey key = wallet.keychain.get(0); final Address address = key.toAddress(Constants.NETWORK_PARAMS); final String addressStr = address.toString(); System.out.println("my bitcoin address: " + addressStr + (Constants.TEST ? " (testnet!)" : "")); ((TextView) findViewById(R.id.bitcoin_address)).setText(addressStr); ((ImageView) findViewById(R.id.bitcoin_address_qr)).setImageBitmap(getQRCodeBitmap("bitcoin:" + addressStr)); try { final InetAddress inetAddress = Constants.TEST ? InetAddress.getByName(Constants.TEST_SEED_NODE) : inetAddressFromUnsignedInt(Constants.SEED_NODES[0]); final NetworkConnection conn = new NetworkConnection(inetAddress, Constants.NETWORK_PARAMS); final BlockChain chain = new BlockChain(Constants.NETWORK_PARAMS, wallet); peer = new Peer(Constants.NETWORK_PARAMS, conn, chain); peer.start(); // peer.startBlockChainDownload(); ((TextView) findViewById(R.id.peer_host)).setText(inetAddress.getHostAddress()); wallet.addEventListener(this); } catch (Exception x) { throw new RuntimeException(x); } }
diff --git a/src/main/java/com/googlecode/meiyo/filter/ContainsMethod.java b/src/main/java/com/googlecode/meiyo/filter/ContainsMethod.java index 2546f34..3659f86 100644 --- a/src/main/java/com/googlecode/meiyo/filter/ContainsMethod.java +++ b/src/main/java/com/googlecode/meiyo/filter/ContainsMethod.java @@ -1,67 +1,67 @@ /* * Copyright 2010 The Meiyo Team * * 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.googlecode.meiyo.filter; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; /** * * @version $Id$ */ final class ContainsMethod implements Filter { private final String name; private final Class<?>[] argumentsType; public ContainsMethod(String name, Class<?>...argumentsType) { this.name = name; this.argumentsType = argumentsType; } /** * {@inheritDoc} */ public boolean matches(Class<?> clazz) { Class<?> current = clazz; - while (current != Object.class) { + while (current != null) { for (Method method : getDeclaredMethods(current)) { if (this.name.equals(method.getName()) && Arrays.equals(this.argumentsType, method.getParameterTypes())) { return true; } } current = current.getSuperclass(); } return false; } private static Method[] getDeclaredMethods(final Class<?> type) { return AccessController.doPrivileged( new PrivilegedAction<Method[]>() { public Method[] run() { final Method[] declaredMethods = type.getDeclaredMethods(); AccessibleObject.setAccessible(declaredMethods, true); return declaredMethods; } }); } }
true
true
public boolean matches(Class<?> clazz) { Class<?> current = clazz; while (current != Object.class) { for (Method method : getDeclaredMethods(current)) { if (this.name.equals(method.getName()) && Arrays.equals(this.argumentsType, method.getParameterTypes())) { return true; } } current = current.getSuperclass(); } return false; }
public boolean matches(Class<?> clazz) { Class<?> current = clazz; while (current != null) { for (Method method : getDeclaredMethods(current)) { if (this.name.equals(method.getName()) && Arrays.equals(this.argumentsType, method.getParameterTypes())) { return true; } } current = current.getSuperclass(); } return false; }
diff --git a/src/net/rptools/maptool/client/MapToolLineParser.java b/src/net/rptools/maptool/client/MapToolLineParser.java index e4876f61..2f2df62f 100644 --- a/src/net/rptools/maptool/client/MapToolLineParser.java +++ b/src/net/rptools/maptool/client/MapToolLineParser.java @@ -1,293 +1,295 @@ /* * 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 net.rptools.maptool.client; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.rptools.common.expression.ExpressionParser; import net.rptools.common.expression.Result; import net.rptools.maptool.client.functions.AbortFunction; import net.rptools.maptool.client.functions.AddAllToInitiativeFunction; import net.rptools.maptool.client.functions.CurrentInitiativeFunction; import net.rptools.maptool.client.functions.InitiativeRoundFunction; import net.rptools.maptool.client.functions.InputFunction; import net.rptools.maptool.client.functions.MiscInitiativeFunction; import net.rptools.maptool.client.functions.RemoveAllFromInitiativeFunction; import net.rptools.maptool.client.functions.StrListFunctions; import net.rptools.maptool.client.functions.StrPropFunctions; import net.rptools.maptool.client.functions.TokenAddToInitiativeFunction; import net.rptools.maptool.client.functions.TokenBarFunction; import net.rptools.maptool.client.functions.TokenGMNameFunction; import net.rptools.maptool.client.functions.TokenHaloFunction; import net.rptools.maptool.client.functions.TokenInitFunction; import net.rptools.maptool.client.functions.TokenInitHoldFunction; import net.rptools.maptool.client.functions.TokenLabelFunction; import net.rptools.maptool.client.functions.LookupTableFunction; import net.rptools.maptool.client.functions.TokenNameFunction; import net.rptools.maptool.client.functions.StateImageFunction; import net.rptools.maptool.client.functions.TokenImage; import net.rptools.maptool.client.functions.TokenRemoveFromInitiativeFunction; import net.rptools.maptool.client.functions.TokenStateFunction; import net.rptools.maptool.client.functions.TokenVisibleFunction; import net.rptools.maptool.model.Token; import net.rptools.parser.ParserException; import net.rptools.parser.VariableResolver; import net.rptools.parser.function.Function; public class MapToolLineParser { private static final int PARSER_MAX_RECURSE = 50; private enum Output { NONE, PLAIN, TOOLTIP, EXPANDED, } private int parserRecurseDepth; /** MapTool functions to add to the parser. */ private static final Function[] mapToolParserFunctions = { StateImageFunction.getInstance(), LookupTableFunction.getInstance(), TokenImage.getInstance(), AddAllToInitiativeFunction.getInstance(), MiscInitiativeFunction.getInstance(), RemoveAllFromInitiativeFunction.getInstance(), CurrentInitiativeFunction.getInstance(), InitiativeRoundFunction.getInstance(), InputFunction.getInstance(), StrPropFunctions.getInstance(), StrListFunctions.getInstance(), AbortFunction.getInstance(), }; /** MapTool functions to add to the parser when a token is in context. */ private static final Function[] mapToolContextParserFunctions = { TokenGMNameFunction.getInstance(), TokenHaloFunction.getInstance(), TokenLabelFunction.getInstance(), TokenNameFunction.getInstance(), TokenStateFunction.getInstance(), TokenVisibleFunction.getInstance(), TokenInitFunction.getInstance(), TokenInitHoldFunction.getInstance(), TokenAddToInitiativeFunction.getInstance(), TokenRemoveFromInitiativeFunction.getInstance(), TokenBarFunction.getInstance(), }; public String parseLine(String line) throws ParserException { return parseLine(null, line); } // This is starting to get ridiculous... I sense an incoming rewrite using ANTLR private static final Pattern roll_pattern = Pattern.compile("\\[\\s*(?:((?:[^\\]:(]|\\((?:[^()\"]|\"[^\"]*\"|\\((?:[^)\"]|\"[^\"]*\")+\\))+\\))*):\\s*)?((?:[^\\]\"]|\"[^\"]*\")*?)\\s*]|\\{\\s*((?:[^}\"]|\"[^\"]*\")*?)\\s*}"); private static final Pattern opt_pattern = Pattern.compile("(\\w+(?:\\((?:[^()\"]|\"[^\"]*\"|\\((?:[^()\"]|\"[^\"]*\")+\\))+\\))?)\\s*,\\s*"); public String parseLine(Token tokenInContext, String line) throws ParserException { if (line == null) { return ""; } line = line.trim(); if (line.length() == 0) { return ""; } // Keep the same context for this line MapToolVariableResolver resolver = new MapToolVariableResolver(tokenInContext); StringBuilder builder = new StringBuilder(); Matcher matcher = roll_pattern.matcher(line); int start; for (start = 0; matcher.find(start); start = matcher.end()) { builder.append(line.substring(start, matcher.start())); // add everything before the roll Output output = Output.TOOLTIP; int count = 1; // used for C option String separator = ", ", text = null; // used for C and T options, respectively if (matcher.group().startsWith("[")) { String opts = matcher.group(1); String roll = matcher.group(2); if (opts != null) { Matcher opt_matcher = opt_pattern.matcher(opts + ","); int region_end = opt_matcher.regionEnd(); for ( ; opt_matcher.lookingAt(); opt_matcher.region(opt_matcher.end(), region_end)) { String opt = opt_matcher.group(1); if (opt.equalsIgnoreCase("h") || opt.equalsIgnoreCase("hide") || opt.equalsIgnoreCase("hidden")) output = Output.NONE; else if (opt.equalsIgnoreCase("p") || opt.equalsIgnoreCase("plain")) output = Output.PLAIN; else if (opt.equalsIgnoreCase("e") || opt.equalsIgnoreCase("expanded")) output = Output.EXPANDED; else if (opt.startsWith("t") || opt.startsWith("T")) { Matcher m = Pattern.compile("t(?:ooltip)?(?:\\(((?:[^()\"]|\"[^\"]*\"|\\((?:[^()\"]|\"[^\"]*\")*\\))+?)\\))?", Pattern.CASE_INSENSITIVE).matcher(opt); if (m.matches()) { output = Output.TOOLTIP; text = m.group(1); if (text != null) text = parseExpression(resolver, tokenInContext, text).getValue().toString(); } else { throw new ParserException("Invalid option: " + opt); } } else if (opt.startsWith("c") || opt.startsWith("C")) { Matcher m = Pattern.compile("c(?:ount)?\\(((?:[^()\"]|\"[^\"]*\"|\\((?:[^()\"]|\"[^\"]*\")*\\))+?)\\)", Pattern.CASE_INSENSITIVE).matcher(opt); if (m.matches()) { String args[] = m.group(1).split(",", 2); Result result = parseExpression(resolver, tokenInContext, args[0]); try { count = ((Number)result.getValue()).intValue(); if (count < 0) throw new ParserException("Invalid count: " + String.valueOf(count)); } catch (ClassCastException e) { throw new ParserException("Invalid count: " + result.getValue().toString()); } if (args.length > 1) { separator = args[1]; } } else { throw new ParserException("Invalid option: " + opt); } } else { throw new ParserException("Invalid option: " + opt); } } if (!opt_matcher.hitEnd()) { throw new ParserException("Invalid option: " + opts.substring(opt_matcher.regionStart())); } } StringBuilder expressionBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { - if (i != 0 && output != Output.NONE) - expressionBuilder.append(parseExpression(resolver, tokenInContext, separator).getValue()); + if (i != 0 && output != Output.NONE) { +// expressionBuilder.append(parseExpression(resolver, tokenInContext, separator).getValue()); + expressionBuilder.append(separator); + } resolver.setVariable("roll.count", i + 1); Result result; switch (output) { case NONE: parseExpression(resolver, tokenInContext, roll); break; case PLAIN: result = parseExpression(resolver, tokenInContext, roll); expressionBuilder.append(result != null ? result.getValue().toString() : ""); break; case TOOLTIP: String tooltip = roll + " = "; String output_text = null; if (text == null) { result = parseExpression(resolver, tokenInContext, roll); if (result != null) { tooltip += result.getDetailExpression(); output_text = result.getValue().toString(); } } else { tooltip += expandRoll(resolver, tokenInContext, roll); output_text = text; } tooltip = tooltip.replaceAll("'", "&#39;"); expressionBuilder.append(output_text != null ? "\036" + tooltip + "\037" + output_text + "\036" : ""); break; case EXPANDED: expressionBuilder.append("\036" + roll + " = " + expandRoll(resolver, tokenInContext, roll) + "\36" ); break; } } builder.append(expressionBuilder); } else if (matcher.group().startsWith("{")) { String roll = matcher.group(3); Result result = parseExpression(resolver, tokenInContext, roll); builder.append(result != null ? result.getValue().toString() : ""); } } builder.append(line.substring(start)); return builder.toString(); } public Result parseExpression(String expression) throws ParserException { return parseExpression(null, expression); } public Result parseExpression(Token tokenInContext, String expression) throws ParserException { return parseExpression(new MapToolVariableResolver(tokenInContext), tokenInContext, expression); } public Result parseExpression(VariableResolver resolver, Token tokenInContext, String expression) throws ParserException { if (parserRecurseDepth > PARSER_MAX_RECURSE) { throw new ParserException("Max recurse limit reached"); } try { parserRecurseDepth ++; return createParser(resolver, tokenInContext == null ? false : true).evaluate(expression); } catch (RuntimeException re) { if (re.getCause() instanceof ParserException) { throw (ParserException) re.getCause(); } throw re; } finally { parserRecurseDepth--; } } public String expandRoll(String roll) { return expandRoll(null, roll); } public String expandRoll(Token tokenInContext, String roll) { return expandRoll(new MapToolVariableResolver(tokenInContext), tokenInContext, roll); } public String expandRoll(MapToolVariableResolver resolver, Token tokenInContext, String roll) { try { Result result = parseExpression(resolver, tokenInContext, roll); StringBuilder sb = new StringBuilder(); if (result.getDetailExpression().equals(result.getValue().toString())) { sb.append(result.getDetailExpression()); } else { sb.append(result.getDetailExpression()).append(" = ").append(result.getValue()); } return sb.toString(); } catch (ParserException e) { return "Invalid expression: " + roll; } } private ExpressionParser createParser(VariableResolver resolver, boolean hasTokenInContext) { ExpressionParser parser = new ExpressionParser(resolver); parser.getParser().addFunctions(mapToolParserFunctions); if (hasTokenInContext) { parser.getParser().addFunctions(mapToolContextParserFunctions); } return parser; } }
true
true
public String parseLine(Token tokenInContext, String line) throws ParserException { if (line == null) { return ""; } line = line.trim(); if (line.length() == 0) { return ""; } // Keep the same context for this line MapToolVariableResolver resolver = new MapToolVariableResolver(tokenInContext); StringBuilder builder = new StringBuilder(); Matcher matcher = roll_pattern.matcher(line); int start; for (start = 0; matcher.find(start); start = matcher.end()) { builder.append(line.substring(start, matcher.start())); // add everything before the roll Output output = Output.TOOLTIP; int count = 1; // used for C option String separator = ", ", text = null; // used for C and T options, respectively if (matcher.group().startsWith("[")) { String opts = matcher.group(1); String roll = matcher.group(2); if (opts != null) { Matcher opt_matcher = opt_pattern.matcher(opts + ","); int region_end = opt_matcher.regionEnd(); for ( ; opt_matcher.lookingAt(); opt_matcher.region(opt_matcher.end(), region_end)) { String opt = opt_matcher.group(1); if (opt.equalsIgnoreCase("h") || opt.equalsIgnoreCase("hide") || opt.equalsIgnoreCase("hidden")) output = Output.NONE; else if (opt.equalsIgnoreCase("p") || opt.equalsIgnoreCase("plain")) output = Output.PLAIN; else if (opt.equalsIgnoreCase("e") || opt.equalsIgnoreCase("expanded")) output = Output.EXPANDED; else if (opt.startsWith("t") || opt.startsWith("T")) { Matcher m = Pattern.compile("t(?:ooltip)?(?:\\(((?:[^()\"]|\"[^\"]*\"|\\((?:[^()\"]|\"[^\"]*\")*\\))+?)\\))?", Pattern.CASE_INSENSITIVE).matcher(opt); if (m.matches()) { output = Output.TOOLTIP; text = m.group(1); if (text != null) text = parseExpression(resolver, tokenInContext, text).getValue().toString(); } else { throw new ParserException("Invalid option: " + opt); } } else if (opt.startsWith("c") || opt.startsWith("C")) { Matcher m = Pattern.compile("c(?:ount)?\\(((?:[^()\"]|\"[^\"]*\"|\\((?:[^()\"]|\"[^\"]*\")*\\))+?)\\)", Pattern.CASE_INSENSITIVE).matcher(opt); if (m.matches()) { String args[] = m.group(1).split(",", 2); Result result = parseExpression(resolver, tokenInContext, args[0]); try { count = ((Number)result.getValue()).intValue(); if (count < 0) throw new ParserException("Invalid count: " + String.valueOf(count)); } catch (ClassCastException e) { throw new ParserException("Invalid count: " + result.getValue().toString()); } if (args.length > 1) { separator = args[1]; } } else { throw new ParserException("Invalid option: " + opt); } } else { throw new ParserException("Invalid option: " + opt); } } if (!opt_matcher.hitEnd()) { throw new ParserException("Invalid option: " + opts.substring(opt_matcher.regionStart())); } } StringBuilder expressionBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { if (i != 0 && output != Output.NONE) expressionBuilder.append(parseExpression(resolver, tokenInContext, separator).getValue()); resolver.setVariable("roll.count", i + 1); Result result; switch (output) { case NONE: parseExpression(resolver, tokenInContext, roll); break; case PLAIN: result = parseExpression(resolver, tokenInContext, roll); expressionBuilder.append(result != null ? result.getValue().toString() : ""); break; case TOOLTIP: String tooltip = roll + " = "; String output_text = null; if (text == null) { result = parseExpression(resolver, tokenInContext, roll); if (result != null) { tooltip += result.getDetailExpression(); output_text = result.getValue().toString(); } } else { tooltip += expandRoll(resolver, tokenInContext, roll); output_text = text; } tooltip = tooltip.replaceAll("'", "&#39;"); expressionBuilder.append(output_text != null ? "\036" + tooltip + "\037" + output_text + "\036" : ""); break; case EXPANDED: expressionBuilder.append("\036" + roll + " = " + expandRoll(resolver, tokenInContext, roll) + "\36" ); break; } } builder.append(expressionBuilder); } else if (matcher.group().startsWith("{")) { String roll = matcher.group(3); Result result = parseExpression(resolver, tokenInContext, roll); builder.append(result != null ? result.getValue().toString() : ""); } } builder.append(line.substring(start)); return builder.toString(); }
public String parseLine(Token tokenInContext, String line) throws ParserException { if (line == null) { return ""; } line = line.trim(); if (line.length() == 0) { return ""; } // Keep the same context for this line MapToolVariableResolver resolver = new MapToolVariableResolver(tokenInContext); StringBuilder builder = new StringBuilder(); Matcher matcher = roll_pattern.matcher(line); int start; for (start = 0; matcher.find(start); start = matcher.end()) { builder.append(line.substring(start, matcher.start())); // add everything before the roll Output output = Output.TOOLTIP; int count = 1; // used for C option String separator = ", ", text = null; // used for C and T options, respectively if (matcher.group().startsWith("[")) { String opts = matcher.group(1); String roll = matcher.group(2); if (opts != null) { Matcher opt_matcher = opt_pattern.matcher(opts + ","); int region_end = opt_matcher.regionEnd(); for ( ; opt_matcher.lookingAt(); opt_matcher.region(opt_matcher.end(), region_end)) { String opt = opt_matcher.group(1); if (opt.equalsIgnoreCase("h") || opt.equalsIgnoreCase("hide") || opt.equalsIgnoreCase("hidden")) output = Output.NONE; else if (opt.equalsIgnoreCase("p") || opt.equalsIgnoreCase("plain")) output = Output.PLAIN; else if (opt.equalsIgnoreCase("e") || opt.equalsIgnoreCase("expanded")) output = Output.EXPANDED; else if (opt.startsWith("t") || opt.startsWith("T")) { Matcher m = Pattern.compile("t(?:ooltip)?(?:\\(((?:[^()\"]|\"[^\"]*\"|\\((?:[^()\"]|\"[^\"]*\")*\\))+?)\\))?", Pattern.CASE_INSENSITIVE).matcher(opt); if (m.matches()) { output = Output.TOOLTIP; text = m.group(1); if (text != null) text = parseExpression(resolver, tokenInContext, text).getValue().toString(); } else { throw new ParserException("Invalid option: " + opt); } } else if (opt.startsWith("c") || opt.startsWith("C")) { Matcher m = Pattern.compile("c(?:ount)?\\(((?:[^()\"]|\"[^\"]*\"|\\((?:[^()\"]|\"[^\"]*\")*\\))+?)\\)", Pattern.CASE_INSENSITIVE).matcher(opt); if (m.matches()) { String args[] = m.group(1).split(",", 2); Result result = parseExpression(resolver, tokenInContext, args[0]); try { count = ((Number)result.getValue()).intValue(); if (count < 0) throw new ParserException("Invalid count: " + String.valueOf(count)); } catch (ClassCastException e) { throw new ParserException("Invalid count: " + result.getValue().toString()); } if (args.length > 1) { separator = args[1]; } } else { throw new ParserException("Invalid option: " + opt); } } else { throw new ParserException("Invalid option: " + opt); } } if (!opt_matcher.hitEnd()) { throw new ParserException("Invalid option: " + opts.substring(opt_matcher.regionStart())); } } StringBuilder expressionBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { if (i != 0 && output != Output.NONE) { // expressionBuilder.append(parseExpression(resolver, tokenInContext, separator).getValue()); expressionBuilder.append(separator); } resolver.setVariable("roll.count", i + 1); Result result; switch (output) { case NONE: parseExpression(resolver, tokenInContext, roll); break; case PLAIN: result = parseExpression(resolver, tokenInContext, roll); expressionBuilder.append(result != null ? result.getValue().toString() : ""); break; case TOOLTIP: String tooltip = roll + " = "; String output_text = null; if (text == null) { result = parseExpression(resolver, tokenInContext, roll); if (result != null) { tooltip += result.getDetailExpression(); output_text = result.getValue().toString(); } } else { tooltip += expandRoll(resolver, tokenInContext, roll); output_text = text; } tooltip = tooltip.replaceAll("'", "&#39;"); expressionBuilder.append(output_text != null ? "\036" + tooltip + "\037" + output_text + "\036" : ""); break; case EXPANDED: expressionBuilder.append("\036" + roll + " = " + expandRoll(resolver, tokenInContext, roll) + "\36" ); break; } } builder.append(expressionBuilder); } else if (matcher.group().startsWith("{")) { String roll = matcher.group(3); Result result = parseExpression(resolver, tokenInContext, roll); builder.append(result != null ? result.getValue().toString() : ""); } } builder.append(line.substring(start)); return builder.toString(); }
diff --git a/api/src/main/java/org/openmrs/module/reporting/data/encounter/evaluator/EncounterProviderDataEvaluator.java b/api/src/main/java/org/openmrs/module/reporting/data/encounter/evaluator/EncounterProviderDataEvaluator.java index 7137b1d2..01d5fd95 100644 --- a/api/src/main/java/org/openmrs/module/reporting/data/encounter/evaluator/EncounterProviderDataEvaluator.java +++ b/api/src/main/java/org/openmrs/module/reporting/data/encounter/evaluator/EncounterProviderDataEvaluator.java @@ -1,99 +1,99 @@ package org.openmrs.module.reporting.data.encounter.evaluator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.openmrs.OpenmrsMetadata; import org.openmrs.annotation.Handler; import org.openmrs.module.reporting.data.encounter.EncounterDataUtil; import org.openmrs.module.reporting.data.encounter.EvaluatedEncounterData; import org.openmrs.module.reporting.data.encounter.definition.EncounterDataDefinition; import org.openmrs.module.reporting.data.encounter.definition.EncounterProviderDataDefinition; import org.openmrs.module.reporting.evaluation.EvaluationContext; import org.openmrs.module.reporting.evaluation.EvaluationException; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Evaluates a EncounterProviderDataDefinition * (Only works with OpenMRS 1.9 and above) */ @Handler(supports=EncounterProviderDataDefinition.class, order=50) public class EncounterProviderDataEvaluator implements EncounterDataEvaluator { /** * Logger */ protected final Log log = LogFactory.getLog(getClass()); @Autowired private SessionFactory sessionFactory; @Override public EvaluatedEncounterData evaluate(EncounterDataDefinition definition, EvaluationContext context) throws EvaluationException { EncounterProviderDataDefinition def = (EncounterProviderDataDefinition) definition; // check to make sure parameter is an encounter role (method signature is type OpenmrsMetadata so it can compile again OpenMRS 1.6.x) if (def.getEncounterRole() != null && !def.getEncounterRole().getClass().getName().equals("org.openmrs.EncounterRole")) { throw new EvaluationException("EncounterRole parameter must be of type EncounterRole"); } EvaluatedEncounterData data = new EvaluatedEncounterData(definition, context); Set<Integer> encIds = EncounterDataUtil.getEncounterIdsForContext(context, false); // just return empty set if input set is empty if (encIds.size() == 0) { return data; } StringBuilder hql = new StringBuilder(); hql.append("select ep.encounter.id, ep.provider from EncounterProvider as ep "); hql.append("where ep.encounter.id in (:ids) and ep.voided='false' "); if (def.getEncounterRole() != null) { hql.append("and ep.encounterRole.id = " + def.getEncounterRole().getId()); } Query query = sessionFactory.getCurrentSession().createQuery(hql.toString()); query.setParameterList("ids", encIds); // create an entry for each encounter for (Integer encId : encIds) { if (!def.isSingleProvider()) { data.addData(encId, new ArrayList<OpenmrsMetadata>()); } else { data.addData(encId, null); } } // now populate with actual results for (Object r : query.list()) { Object[] result = (Object []) r; if (!def.isSingleProvider()) { ((List<OpenmrsMetadata>) data.getData().get(result[0])).add((OpenmrsMetadata) result[1]); } else { - // note that if there are multiple matching obs and we are in singleObs mode then last one wins + // note that if there are multiple matching providers and we are in singleProvider mode then last one wins if (data.getData().get(result[0]) != null) { log.warn("Multiple matching providers for encounter " + result[0] + "... picking one"); } data.addData((Integer) result[0], result[1]); } } return data; } }
true
true
public EvaluatedEncounterData evaluate(EncounterDataDefinition definition, EvaluationContext context) throws EvaluationException { EncounterProviderDataDefinition def = (EncounterProviderDataDefinition) definition; // check to make sure parameter is an encounter role (method signature is type OpenmrsMetadata so it can compile again OpenMRS 1.6.x) if (def.getEncounterRole() != null && !def.getEncounterRole().getClass().getName().equals("org.openmrs.EncounterRole")) { throw new EvaluationException("EncounterRole parameter must be of type EncounterRole"); } EvaluatedEncounterData data = new EvaluatedEncounterData(definition, context); Set<Integer> encIds = EncounterDataUtil.getEncounterIdsForContext(context, false); // just return empty set if input set is empty if (encIds.size() == 0) { return data; } StringBuilder hql = new StringBuilder(); hql.append("select ep.encounter.id, ep.provider from EncounterProvider as ep "); hql.append("where ep.encounter.id in (:ids) and ep.voided='false' "); if (def.getEncounterRole() != null) { hql.append("and ep.encounterRole.id = " + def.getEncounterRole().getId()); } Query query = sessionFactory.getCurrentSession().createQuery(hql.toString()); query.setParameterList("ids", encIds); // create an entry for each encounter for (Integer encId : encIds) { if (!def.isSingleProvider()) { data.addData(encId, new ArrayList<OpenmrsMetadata>()); } else { data.addData(encId, null); } } // now populate with actual results for (Object r : query.list()) { Object[] result = (Object []) r; if (!def.isSingleProvider()) { ((List<OpenmrsMetadata>) data.getData().get(result[0])).add((OpenmrsMetadata) result[1]); } else { // note that if there are multiple matching obs and we are in singleObs mode then last one wins if (data.getData().get(result[0]) != null) { log.warn("Multiple matching providers for encounter " + result[0] + "... picking one"); } data.addData((Integer) result[0], result[1]); } } return data; }
public EvaluatedEncounterData evaluate(EncounterDataDefinition definition, EvaluationContext context) throws EvaluationException { EncounterProviderDataDefinition def = (EncounterProviderDataDefinition) definition; // check to make sure parameter is an encounter role (method signature is type OpenmrsMetadata so it can compile again OpenMRS 1.6.x) if (def.getEncounterRole() != null && !def.getEncounterRole().getClass().getName().equals("org.openmrs.EncounterRole")) { throw new EvaluationException("EncounterRole parameter must be of type EncounterRole"); } EvaluatedEncounterData data = new EvaluatedEncounterData(definition, context); Set<Integer> encIds = EncounterDataUtil.getEncounterIdsForContext(context, false); // just return empty set if input set is empty if (encIds.size() == 0) { return data; } StringBuilder hql = new StringBuilder(); hql.append("select ep.encounter.id, ep.provider from EncounterProvider as ep "); hql.append("where ep.encounter.id in (:ids) and ep.voided='false' "); if (def.getEncounterRole() != null) { hql.append("and ep.encounterRole.id = " + def.getEncounterRole().getId()); } Query query = sessionFactory.getCurrentSession().createQuery(hql.toString()); query.setParameterList("ids", encIds); // create an entry for each encounter for (Integer encId : encIds) { if (!def.isSingleProvider()) { data.addData(encId, new ArrayList<OpenmrsMetadata>()); } else { data.addData(encId, null); } } // now populate with actual results for (Object r : query.list()) { Object[] result = (Object []) r; if (!def.isSingleProvider()) { ((List<OpenmrsMetadata>) data.getData().get(result[0])).add((OpenmrsMetadata) result[1]); } else { // note that if there are multiple matching providers and we are in singleProvider mode then last one wins if (data.getData().get(result[0]) != null) { log.warn("Multiple matching providers for encounter " + result[0] + "... picking one"); } data.addData((Integer) result[0], result[1]); } } return data; }
diff --git a/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java b/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java index 2867686018..70f871d8b2 100644 --- a/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java +++ b/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java @@ -1,924 +1,924 @@ /* Copyright (c) 2001, 2003 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.vfny.geoserver.servlets; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.Reader; import java.net.SocketException; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.web.context.WebApplicationContext; import org.vfny.geoserver.ExceptionHandler; import org.vfny.geoserver.Request; import org.vfny.geoserver.Response; import org.vfny.geoserver.ServiceException; import org.vfny.geoserver.global.Data; import org.vfny.geoserver.global.GeoServer; import org.vfny.geoserver.global.Service; import org.vfny.geoserver.util.requests.XmlCharsetDetector; import org.vfny.geoserver.util.requests.readers.KvpRequestReader; import org.vfny.geoserver.util.requests.readers.XmlRequestReader; /** * Represents a service that all others extend from. Subclasses should provide * response and exception handlers as appropriate. * * <p> * It is <b>really</b> important to adhere to the following workflow: * * <ol> * <li> * get a Request reader * </li> * <li> * ask the Request Reader for the Request object * </li> * <li> * Provide the resulting Request with the ServletRequest that generated it * </li> * <li> * get the appropiate ResponseHandler * </li> * <li> * ask it to execute the Request * </li> * <li> * set the response content type * </li> * <li> * write to the http response's output stream * </li> * <li> * pending - call Response cleanup * </li> * </ol> * </p> * * <p> * If anything goes wrong a ServiceException can be thrown and will be written * to the output stream instead. * </p> * * <p> * This is because we have to be sure that no exception have been produced * before setting the response's content type, so we can set the exception * specific content type; and that Response.getContentType is called AFTER * Response.execute, since the MIME type can depend on any request parameter * or another kind of desission making during the execute process. (i.e. * FORMAT in WMS GetMap) * </p> * * <p> * TODO: We need to call Response.abort() if anything goes wrong to allow the * Response a chance to cleanup after itself. * </p> * * @author Gabriel Rold?n * @author Chris Holmes * @author Jody Garnett, Refractions Research * @version $Id: AbstractService.java,v 1.23 2004/09/08 17:34:38 cholmesny Exp $ */ public abstract class AbstractService extends HttpServlet implements ApplicationContextAware { /** Class logger */ protected static Logger LOGGER = Logger.getLogger( "org.vfny.geoserver.servlets"); /** * Servivce group (maps to 'SERVICE' parameter in OGC service urls) */ String service; /** * Request type (maps to 'REQUEST' parameter in OGC service urls) */ String request; /** * Application context used to look up "Services" */ WebApplicationContext context; /** * Reference to the global geoserver instnace. */ GeoServer geoServer; /** * Reference to the catalog. */ Data catalog; /** * Id of the service strategy to use. */ String serviceStrategy; /** * buffer size to use when PARTIAL-BUFFER is being used */ int partialBufferSize; /** * Cached service strategy object */ ServiceStrategy strategy; /** * Reference to the service */ Service serviceRef; /** DOCUMENT ME! */ protected HttpServletRequest curRequest; /** * Constructor for abstract service. * * @param service The service group the service falls into (WFS,WMS,...) * @param request The service being requested (GetCapabilities, GetMap, ...) * @param serviceRef The global service this "servlet" falls into */ public AbstractService(String service, String request, Service serviceRef) { this.service = service; this.request = request; this.serviceRef = serviceRef; } /** * @return Returns the "service group" that this service falls into. */ public String getService() { return service; } /** * @return Returns the "request" this service maps to. */ public String getRequest() { return request; } /** * Sets a refeference to the global service instance. */ public void setServiceRef(Service serviceRef) { this.serviceRef = serviceRef; } /** * @return The reference to the global service instance. */ public Service getServiceRef() { return serviceRef; } /** * Sets the application context. * <p> * Used to process the {@link Service} extension point. * </p> */ public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = (WebApplicationContext) context; } /** * @return The application context. */ public WebApplicationContext getApplicationContext() { return context; } /** * Sets the reference to the global geoserver instance. */ public void setGeoServer(GeoServer geoServer) { this.geoServer = geoServer; } /** * @return the reference to the global geoserver instance. */ public GeoServer getGeoServer() { return geoServer; } /** * @return The reference to the global catalog instance. */ public Data getCatalog() { return catalog; } /** * Sets the reference to the global catalog instance. * */ public void setCatalog(Data catalog) { this.catalog = catalog; } /** * @return The id used to identify the service strategy to be used. * @see ServiceStrategy#getId() */ public String getServiceStrategy() { return serviceStrategy; } /** * Sets the id used to identify the service strategy to be used. */ public void setServiceStrategy(String serviceStrategy) { this.serviceStrategy = serviceStrategy; } /** * Determines if the service is enabled. * <p> * Subclass should override this method if the service can be turned on/off. * This implementation returns <code>true</code> * </p> */ protected boolean isServiceEnabled(HttpServletRequest req) { return true; } /** * DOCUMENT ME! * * @param request DOCUMENT ME! * @param response DOCUMENT ME! * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // implements the main request/response logic this.curRequest = request; Request serviceRequest = null; if (!isServiceEnabled(request)) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } try { String qString = request.getQueryString(); LOGGER.fine("reading request: " + qString); //Map requestParams = KvpRequestReader.parseKvpSet(qString); Map requestParams = new HashMap(); String paramName; String paramValue; for (Enumeration pnames = request.getParameterNames(); pnames.hasMoreElements();) { paramName = (String) pnames.nextElement(); paramValue = request.getParameter(paramName); requestParams.put(paramName.toUpperCase(), paramValue); } KvpRequestReader requestReader = getKvpReader(requestParams ); serviceRequest = requestReader.getRequest(request); LOGGER.finer("serviceRequest provided with HttpServletRequest: " + request); //serviceRequest.setHttpServletRequest(request); } catch (ServiceException se) { sendError(response, se); return; } catch (Throwable e) { sendError(response, e); return; } doService(request, response, serviceRequest); } /** * Performs the post method. Simply passes itself on to the three argument * doPost method, with null for the reader, because the * request.getReader() will not have been used if this servlet is called * directly. * * @param request DOCUMENT ME! * @param response DOCUMENT ME! * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response, null); } /** * Performs the post method. Gets the appropriate xml reader and * determines the request from that, and then passes the request on to * doService. * * @param request The request made. * @param response The response to be returned. * @param requestXml A reader of the xml to be read. This is only used by * the dispatcher, everyone else should just pass in null. This is * needed because afaik HttpServletRequest.getReader() can not be * used twice. So in a dispatched case we write it to a temp file, * which we can then read in twice. * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ public void doPost(HttpServletRequest request, HttpServletResponse response, Reader requestXml) throws ServletException, IOException { this.curRequest = request; Request serviceRequest = null; //TODO: This isn't a proper ogc service response. if (!isServiceEnabled(request)) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // implements the main request/response logic try { XmlRequestReader requestReader = getXmlRequestReader(); //JD: GEOS-323, adding support for character encoding detection // Reader xml = (requestXml != null) ? requestXml : request.getReader(); Reader xml; if (null != requestXml) { xml = requestXml; } else { /* * `getCharsetAwareReader` returns a reader which not support * mark/reset. So it is a good idea to wrap it into BufferedReader. * In this case the below debug output will work. */ xml = new BufferedReader( XmlCharsetDetector.getCharsetAwareReader( request.getInputStream())); } //JD: GEOS-323 //DJB: add support for POST loggin if (LOGGER.isLoggable(Level.FINE)) { if (xml.markSupported()) { // a little protection for large POSTs (ie. updates) // for FINE, I assume people just want to see the "normal" ones - not the big ones // for FINER, I assume they would want to see a bit more // for FINEST, I assume they would want to see even more int maxChars = 16000; if (LOGGER.isLoggable(Level.FINER)) maxChars = 64000; if (LOGGER.isLoggable(Level.FINEST)) maxChars = 640000; // Bill gates says 640k is good enough for anyone xml.mark(maxChars+1); // +1 so if you read the whole thing you can still reset() char buffer[] = new char[maxChars]; int actualRead = xml.read(buffer); xml.reset(); LOGGER.fine("------------XML POST START-----------\n"+new String(buffer,0,actualRead)+"\n------------XML POST END-----------"); if (actualRead ==maxChars ) LOGGER.fine("------------XML POST REPORT WAS TRUNCATED AT "+maxChars+" CHARACTERS. RUN WITH HIGHER LOGGING LEVEL TO SEE MORE"); } else { LOGGER.fine("ATTEMPTED TO LOG POST XML, BUT WAS PREVENTED BECAUSE markSupported() IS FALSE"); } } serviceRequest = requestReader.read(xml, request); serviceRequest.setHttpServletRequest(request); } catch (ServiceException se) { sendError(response, se); return; } catch (Throwable e) { sendError(response, e); return; } doService(request, response, serviceRequest); } /** * Peforms service according to ServiceStrategy. * * <p> * This method has very strict requirements, please see the class * description for the specifics. * </p> * * <p> * It has a lot of try/catch blocks, but they are fairly necessary to * handle things correctly and to avoid as many ugly servlet responses, so * that everything is wrapped correctly. * </p> * * @param request The httpServlet of the request. * @param response The response to be returned. * @param serviceRequest The OGC request to service. * * @throws ServletException if the strategy can't be instantiated */ protected void doService(HttpServletRequest request, HttpServletResponse response, Request serviceRequest) throws ServletException { LOGGER.info("handling request: " + serviceRequest); if (!isServiceEnabled(request)) { try { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (IOException e) { // do nothing } return; } ServiceStrategy strategy = null; Response serviceResponse = null; try { strategy = createServiceStrategy(); LOGGER.fine("strategy is: " + strategy.getId()); serviceResponse = getResponseHandler(); } catch (Throwable t) { sendError(response, t); return; } Map services = context.getBeansOfType(Service.class); Service s = null; for (Iterator itr = services.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String id = (String) entry.getKey(); Service service = (Service) entry.getValue(); if (id.equalsIgnoreCase(serviceRequest.getService())) { s = service; break; } } if (s == null) { String msg = "No service found matching: " + serviceRequest.getService(); sendError(response,new ServiceException ( msg )); return; } try { // execute request LOGGER.finer("executing request"); serviceResponse.execute(serviceRequest); LOGGER.finer("execution succeed"); } catch (ServiceException serviceException) { LOGGER.warning("service exception while executing request: " + serviceRequest + "\ncause: " + serviceException.getMessage()); serviceResponse.abort(s); sendError(response, serviceException); return; } catch (Throwable t) { //we can safelly send errors here, since we have not touched response yet serviceResponse.abort(s); sendError(response, t); return; } OutputStream strategyOuput = null; //obtain the strategy output stream try { LOGGER.finest("getting strategy output"); strategyOuput = strategy.getDestination(response); LOGGER.finer("strategy output is: " + strategyOuput.getClass().getName()); String mimeType = serviceResponse.getContentType(s.getGeoServer()); LOGGER.fine("mime type is: " + mimeType); response.setContentType(mimeType); String encoding = serviceResponse.getContentEncoding(); if (encoding != null) { LOGGER.fine("content encoding is: " + encoding); - response.setHeader("content-encoding", encoding); + response.setHeader("Content-Encoding", encoding); } } catch (SocketException socketException) { LOGGER.fine( "it seems that the user has closed the request stream: " + socketException.getMessage()); // It seems the user has closed the request stream // Apparently this is a "cancel" and will quietly go away // // I will still give strategy and serviceResponse // a chance to clean up // serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ex) { serviceResponse.abort(s); strategy.abort(); sendError(response, ex); return; } try { // gather response serviceResponse.writeTo(strategyOuput); strategyOuput.flush(); strategy.flush(); } catch (java.net.SocketException sockEx) { // user cancel serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ioException) { // strategyOutput error serviceResponse.abort(s); strategy.abort(); sendError(response, ioException); return; } catch (ServiceException writeToFailure) { // writeTo Failure serviceResponse.abort(s); strategy.abort(); sendError(response, writeToFailure); return; } catch (Throwable help) { // This is an unexpected error(!) help.printStackTrace(); serviceResponse.abort(s); strategy.abort(); sendError(response, help); return; } // Finish Response // I have moved closing the output stream out here, it was being // done by a few of the ServiceStrategy // // By this time serviceResponse has finished successfully // and strategy is also finished // try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (SocketException sockEx) { // user cancel LOGGER.warning("Could not send completed response to user:" + sockEx); return; } catch (IOException ioException) { // This is bad, the user did not get the completed response LOGGER.warning("Could not send completed response to user:" + ioException); return; } LOGGER.info("Service handled"); } /** * Gets the response class that should handle the request of this service. * All subclasses must implement. * <p> * This method is not abstract to support subclasses that use the * request-response mechanism. * </p> * * @return The response that the request read by this servlet should be * passed to. */ protected Response getResponseHandler() { return null; } /** * Gets a reader that will figure out the correct Key Vaule Pairs for this * service. * <p> * Subclasses should override to supply a specific kvp reader. Default * implementation returns <code>null</code> * </p> * @param params A map of the kvp pairs. * * @return An initialized KVP reader to decode the request. */ protected KvpRequestReader getKvpReader(Map params) { return null; } /** * Gets a reader that will handle a posted xml request for this servlet. * <p> * Subclasses should override to supply a specific xml reader. Default * implementation returns <code>null</code> * </p> * @return An XmlRequestReader appropriate to this service. */ protected XmlRequestReader getXmlRequestReader() { return null; } /** * Gets the exception handler for this service. * * @return The correct ExceptionHandler */ protected abstract ExceptionHandler getExceptionHandler(); /** * Gets the strategy for outputting the response. This method gets the * strategy from the serviceStrategy param in the web.xml file. This is * sort of odd behavior, as all other such parameters are set in the * services and catalog xml files, and this param may move there. But as * it is much more of a programmer configuration than a user * configuration there is no rush to move it. * * <p> * Subclasses may choose to override this method in order to get a strategy * more suited to their response. Currently only Transaction will do * this, since the commit is only called after writeTo, and it often * messes up, so we want to be able to see the error message (SPEED writes * the output directly, so errors in writeTo do not show up.) * </p> * * <p> * Most subclasses should not override, this method will most always return * the SPEED strategy, since it is the fastest response and should work * fine if everything is well tested. FILE and BUFFER should be used when * there are errors in writeTo methods of child classes, set by the * programmer in the web.xml file. * </p> * * @return The service strategy found in the web.xml serviceStrategy * parameter. The code that finds this is in the init method * * @throws ServiceException If the service strategy set in #init() is not * valid. * * @see #init() for the code that sets the serviceStrategy. */ protected ServiceStrategy createServiceStrategy() throws ServiceException { //If verbose exceptions is on then lets make sure they actually get the //exception by using the file strategy. if (geoServer.isVerboseExceptions()) { strategy = (ServiceStrategy) context.getBean("fileServiceStrategy"); } else { //do we have a prototype? if (strategy != null) { //yes, make sure it still matched up with id set if (!strategy.getId().equals(serviceStrategy)) { //clear prototype to force another lookup strategy = null; } } if (strategy == null) { //do a lookup Map strategies = context.getBeansOfType(ServiceStrategy.class); for (Iterator itr = strategies.values().iterator(); itr.hasNext();) { ServiceStrategy bean = (ServiceStrategy) itr.next(); if (bean.getId().equals(serviceStrategy)) { strategy = bean; break; } } } if (strategy == null) { //default to buffer strategy = (ServiceStrategy) context.getBean("bufferServiceStrategy"); } } ServiceStrategy theStrategy = null; try { theStrategy = (ServiceStrategy) strategy.clone(); } catch(CloneNotSupportedException e) { String msg = "Service strategy: " + strategy.getId() + " not cloneable"; throw new ServiceException(msg,e); } //TODO: this hack should be removed once modules have their own config if (theStrategy instanceof PartialBufferStrategy) { ((PartialBufferStrategy)theStrategy).setBufferSize(partialBufferSize); } return theStrategy; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ protected String getMimeType() { ServletContext servContext = getServletContext(); try { return ((GeoServer) servContext.getAttribute("GeoServer")) .getMimeType(); } catch (NullPointerException e) { return "text/xml; charset=" + Charset.forName("UTF-8").displayName(); } } /** * DOCUMENT ME! * * @param response DOCUMENT ME! * @param content DOCUMENT ME! */ protected void send(HttpServletResponse response, CharSequence content) { send(response, content, getMimeType()); } /** * DOCUMENT ME! * * @param response DOCUMENT ME! * @param content DOCUMENT ME! * @param mimeType DOCUMENT ME! */ protected void send(HttpServletResponse response, CharSequence content, String mimeType) { try { response.setContentType(mimeType); response.getWriter().write(content.toString()); } catch (IOException ex) { //stream closed by client, do nothing LOGGER.fine(ex.getMessage()); } } /** * Send error produced during getService opperation. * * <p> * Some errors know how to write themselves out WfsTransactionException for * instance. It looks like this might be is handled by * getExceptionHandler().newServiceException( t, pre, null ). I still * would not mind seeing a check for ServiceConfig Exception here. * </p> * * <p> * This code says that it deals with UNCAUGHT EXCEPTIONS, so I think it * would be wise to explicitly catch ServiceExceptions. * </p> * * @param response DOCUMENT ME! * @param t DOCUMENT ME! */ protected void sendError(HttpServletResponse response, Throwable t) { if (t instanceof ServiceException) { sendError(response, (ServiceException) t); return; } LOGGER.info("Had an undefined error: " + t.getMessage()); //TODO: put the stack trace in the logger. //t.printStackTrace(); //String pre = "UNCAUGHT EXCEPTION"; ExceptionHandler exHandler = getExceptionHandler(); ServiceException se = exHandler.newServiceException(t); sendError(response, se); //GeoServer geoServer = (GeoServer) this.getServletConfig() // .getServletContext().getAttribute(GeoServer.WEB_CONTAINER_KEY); //send(response, se.getXmlResponse(geoServer.isVerboseExceptions())); } /** * Send a serviceException produced during getService opperation. * * @param response DOCUMENT ME! * @param se DOCUMENT ME! */ protected void sendError(HttpServletResponse response, ServiceException se) { String mimeType = se.getMimeType(geoServer); send(response, se.getXmlResponse(geoServer.isVerboseExceptions(), curRequest), mimeType); se.printStackTrace(); } /** * DOCUMENT ME! * * @param response DOCUMENT ME! * @param result DOCUMENT ME! */ protected void send(HttpServletResponse response, Response result) { OutputStream responseOut = null; try { responseOut = response.getOutputStream(); } catch (IOException ex) { //stream closed, do nothing. LOGGER.info("apparently client has closed stream: " + ex.getMessage()); } OutputStream out = new BufferedOutputStream(responseOut); ServletContext servContext = getServletContext(); response.setContentType(result.getContentType( (GeoServer) servContext.getAttribute("GeoServer"))); try { result.writeTo(out); out.flush(); responseOut.flush(); } catch (IOException ioe) { //user just closed the socket stream, do nothing LOGGER.fine("connection closed by user: " + ioe.getMessage()); } catch (ServiceException ex) { sendError(response, ex); } } /** * Checks if the client requests supports gzipped responses by quering it's * 'accept-encoding' header. * * @param request the request to query the HTTP header from * * @return true if 'gzip' if one of the supported content encodings of * <code>request</code>, false otherwise. */ protected boolean requestSupportsGzip(HttpServletRequest request) { boolean supportsGzip = false; String header = request.getHeader("accept-encoding"); if ((header != null) && (header.indexOf("gzip") > -1)) { supportsGzip = true; } if (LOGGER.isLoggable(Level.CONFIG)) { LOGGER.config("user-agent=" + request.getHeader("user-agent")); LOGGER.config("accept=" + request.getHeader("accept")); LOGGER.config("accept-encoding=" + request.getHeader("accept-encoding")); } return supportsGzip; } }
true
true
protected void doService(HttpServletRequest request, HttpServletResponse response, Request serviceRequest) throws ServletException { LOGGER.info("handling request: " + serviceRequest); if (!isServiceEnabled(request)) { try { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (IOException e) { // do nothing } return; } ServiceStrategy strategy = null; Response serviceResponse = null; try { strategy = createServiceStrategy(); LOGGER.fine("strategy is: " + strategy.getId()); serviceResponse = getResponseHandler(); } catch (Throwable t) { sendError(response, t); return; } Map services = context.getBeansOfType(Service.class); Service s = null; for (Iterator itr = services.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String id = (String) entry.getKey(); Service service = (Service) entry.getValue(); if (id.equalsIgnoreCase(serviceRequest.getService())) { s = service; break; } } if (s == null) { String msg = "No service found matching: " + serviceRequest.getService(); sendError(response,new ServiceException ( msg )); return; } try { // execute request LOGGER.finer("executing request"); serviceResponse.execute(serviceRequest); LOGGER.finer("execution succeed"); } catch (ServiceException serviceException) { LOGGER.warning("service exception while executing request: " + serviceRequest + "\ncause: " + serviceException.getMessage()); serviceResponse.abort(s); sendError(response, serviceException); return; } catch (Throwable t) { //we can safelly send errors here, since we have not touched response yet serviceResponse.abort(s); sendError(response, t); return; } OutputStream strategyOuput = null; //obtain the strategy output stream try { LOGGER.finest("getting strategy output"); strategyOuput = strategy.getDestination(response); LOGGER.finer("strategy output is: " + strategyOuput.getClass().getName()); String mimeType = serviceResponse.getContentType(s.getGeoServer()); LOGGER.fine("mime type is: " + mimeType); response.setContentType(mimeType); String encoding = serviceResponse.getContentEncoding(); if (encoding != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("content-encoding", encoding); } } catch (SocketException socketException) { LOGGER.fine( "it seems that the user has closed the request stream: " + socketException.getMessage()); // It seems the user has closed the request stream // Apparently this is a "cancel" and will quietly go away // // I will still give strategy and serviceResponse // a chance to clean up // serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ex) { serviceResponse.abort(s); strategy.abort(); sendError(response, ex); return; } try { // gather response serviceResponse.writeTo(strategyOuput); strategyOuput.flush(); strategy.flush(); } catch (java.net.SocketException sockEx) { // user cancel serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ioException) { // strategyOutput error serviceResponse.abort(s); strategy.abort(); sendError(response, ioException); return; } catch (ServiceException writeToFailure) { // writeTo Failure serviceResponse.abort(s); strategy.abort(); sendError(response, writeToFailure); return; } catch (Throwable help) { // This is an unexpected error(!) help.printStackTrace(); serviceResponse.abort(s); strategy.abort(); sendError(response, help); return; } // Finish Response // I have moved closing the output stream out here, it was being // done by a few of the ServiceStrategy // // By this time serviceResponse has finished successfully // and strategy is also finished // try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (SocketException sockEx) { // user cancel LOGGER.warning("Could not send completed response to user:" + sockEx); return; } catch (IOException ioException) { // This is bad, the user did not get the completed response LOGGER.warning("Could not send completed response to user:" + ioException); return; } LOGGER.info("Service handled"); }
protected void doService(HttpServletRequest request, HttpServletResponse response, Request serviceRequest) throws ServletException { LOGGER.info("handling request: " + serviceRequest); if (!isServiceEnabled(request)) { try { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (IOException e) { // do nothing } return; } ServiceStrategy strategy = null; Response serviceResponse = null; try { strategy = createServiceStrategy(); LOGGER.fine("strategy is: " + strategy.getId()); serviceResponse = getResponseHandler(); } catch (Throwable t) { sendError(response, t); return; } Map services = context.getBeansOfType(Service.class); Service s = null; for (Iterator itr = services.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String id = (String) entry.getKey(); Service service = (Service) entry.getValue(); if (id.equalsIgnoreCase(serviceRequest.getService())) { s = service; break; } } if (s == null) { String msg = "No service found matching: " + serviceRequest.getService(); sendError(response,new ServiceException ( msg )); return; } try { // execute request LOGGER.finer("executing request"); serviceResponse.execute(serviceRequest); LOGGER.finer("execution succeed"); } catch (ServiceException serviceException) { LOGGER.warning("service exception while executing request: " + serviceRequest + "\ncause: " + serviceException.getMessage()); serviceResponse.abort(s); sendError(response, serviceException); return; } catch (Throwable t) { //we can safelly send errors here, since we have not touched response yet serviceResponse.abort(s); sendError(response, t); return; } OutputStream strategyOuput = null; //obtain the strategy output stream try { LOGGER.finest("getting strategy output"); strategyOuput = strategy.getDestination(response); LOGGER.finer("strategy output is: " + strategyOuput.getClass().getName()); String mimeType = serviceResponse.getContentType(s.getGeoServer()); LOGGER.fine("mime type is: " + mimeType); response.setContentType(mimeType); String encoding = serviceResponse.getContentEncoding(); if (encoding != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("Content-Encoding", encoding); } } catch (SocketException socketException) { LOGGER.fine( "it seems that the user has closed the request stream: " + socketException.getMessage()); // It seems the user has closed the request stream // Apparently this is a "cancel" and will quietly go away // // I will still give strategy and serviceResponse // a chance to clean up // serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ex) { serviceResponse.abort(s); strategy.abort(); sendError(response, ex); return; } try { // gather response serviceResponse.writeTo(strategyOuput); strategyOuput.flush(); strategy.flush(); } catch (java.net.SocketException sockEx) { // user cancel serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ioException) { // strategyOutput error serviceResponse.abort(s); strategy.abort(); sendError(response, ioException); return; } catch (ServiceException writeToFailure) { // writeTo Failure serviceResponse.abort(s); strategy.abort(); sendError(response, writeToFailure); return; } catch (Throwable help) { // This is an unexpected error(!) help.printStackTrace(); serviceResponse.abort(s); strategy.abort(); sendError(response, help); return; } // Finish Response // I have moved closing the output stream out here, it was being // done by a few of the ServiceStrategy // // By this time serviceResponse has finished successfully // and strategy is also finished // try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (SocketException sockEx) { // user cancel LOGGER.warning("Could not send completed response to user:" + sockEx); return; } catch (IOException ioException) { // This is bad, the user did not get the completed response LOGGER.warning("Could not send completed response to user:" + ioException); return; } LOGGER.info("Service handled"); }
diff --git a/server/amee-restlet/src/main/java/com/amee/restlet/data/builder/DataCategoryResourceBuilder.java b/server/amee-restlet/src/main/java/com/amee/restlet/data/builder/DataCategoryResourceBuilder.java index 48243be2..0627d1c0 100644 --- a/server/amee-restlet/src/main/java/com/amee/restlet/data/builder/DataCategoryResourceBuilder.java +++ b/server/amee-restlet/src/main/java/com/amee/restlet/data/builder/DataCategoryResourceBuilder.java @@ -1,247 +1,247 @@ package com.amee.restlet.data.builder; import com.amee.base.utils.XMLUtils; import com.amee.domain.LocaleConstants; import com.amee.domain.ObjectType; import com.amee.domain.Pager; import com.amee.domain.data.DataCategory; import com.amee.domain.data.DataItem; import com.amee.domain.path.PathItem; import com.amee.domain.path.PathItemGroup; import com.amee.domain.sheet.Column; import com.amee.domain.sheet.Sheet; import com.amee.domain.sheet.SortOrder; import com.amee.restlet.data.DataCategoryResource; import com.amee.service.data.DataService; import com.amee.service.data.DataSheetService; import com.amee.service.definition.DefinitionService; import com.amee.service.path.PathItemService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.HashMap; import java.util.Map; /** * This file is part of AMEE. * <p/> * AMEE 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. * <p/> * AMEE is free software and 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. * <p/> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * <p/> * Created by http://www.dgen.net. * Website http://www.amee.cc */ @Service public class DataCategoryResourceBuilder { @Autowired private DataService dataService; @Autowired private DataSheetService dataSheetService; @Autowired private DefinitionService definitionService; @Autowired private PathItemService pathItemService; public JSONObject getJSONObject(DataCategoryResource resource) throws JSONException { // create JSON object JSONObject obj = new JSONObject(); obj.put("path", resource.getPathItem().getFullPath()); if (resource.isGet()) { // add DataCategory obj.put("dataCategory", resource.getDataCategory().getJSONObject(true)); // list child Data Categories and child Data Items JSONObject children = new JSONObject(); // Get PathItem. PathItem pathItem = getPathItem(resource); // add Data Categories via pathItem to children JSONArray dataCategories = new JSONArray(); for (PathItem pi : pathItem.getChildrenByType(ObjectType.DC.getName())) { dataCategories.put(pi.getJSONObject()); } children.put("dataCategories", dataCategories); // addItemValue Sheet containing Data Items Sheet sheet = dataSheetService.getSheet(resource.getDataBrowser(), pathItem.getFullPath()); if (sheet != null) { String sortBy = resource.getRequest().getResourceRef().getQueryAsForm().getFirstValue("sortBy"); if (sortBy != null) { Column c = sheet.getColumn(sortBy); if (c != null) { try { - c.setSortOrder(SortOrder.valueOf(resource.getRequest().getResourceRef().getQueryAsForm().getFirstValue("sortOrder"))); + c.setSortOrder(SortOrder.valueOf(resource.getRequest().getResourceRef().getQueryAsForm().getFirstValue("sortOrder", ""))); } catch (IllegalArgumentException e) { // swallow } sheet = Sheet.getCopy(sheet); sheet.getSortBy().getChoices().clear(); sheet.addSortBy(sortBy); sheet.sortRows(); } } Pager pager = resource.getPager(); sheet = Sheet.getCopy(sheet, pager); pager.setCurrentPage(resource.getPage()); children.put("dataItems", sheet.getJSONObject()); children.put("pager", pager.getJSONObject()); } else { children.put("dataItems", new JSONObject()); children.put("pager", new JSONObject()); } // add children obj.put("children", children); } else if (resource.isPostOrPut()) { // DataCategories if (resource.getDataCategory() != null) { obj.put("dataCategory", resource.getDataCategory().getJSONObject(true)); } else if (resource.getDataCategories() != null) { JSONArray dataCategories = new JSONArray(); obj.put("dataCategories", dataCategories); for (DataCategory dc : resource.getDataCategories()) { dataCategories.put(dc.getJSONObject(false)); } } // DataItems if (resource.getDataItem() != null) { obj.put("dataItem", resource.getDataItem().getJSONObject(true)); } else if (resource.getDataItems() != null) { JSONArray dataItems = new JSONArray(); obj.put("dataItems", dataItems); for (DataItem di : resource.getDataItems()) { dataItems.put(di.getJSONObject(false)); } } } return obj; } public Element getElement(DataCategoryResource resource, Document document) { Element element = document.createElement("DataCategoryResource"); element.appendChild(XMLUtils.getElement(document, "Path", resource.getPathItem().getFullPath())); if (resource.isGet()) { // add DataCategory element.appendChild(resource.getDataCategory().getElement(document, true)); // list child Data Categories and child Data Items Element childrenElement = document.createElement("Children"); element.appendChild(childrenElement); // Get PathItem. PathItem pathItem = getPathItem(resource); // add Data Categories Element dataCategoriesElement = document.createElement("DataCategories"); for (PathItem pi : pathItem.getChildrenByType(ObjectType.DC.getName())) { dataCategoriesElement.appendChild(pi.getElement(document)); } childrenElement.appendChild(dataCategoriesElement); // list child Data Items via sheet Sheet sheet = dataSheetService.getSheet(resource.getDataBrowser(), pathItem.getFullPath()); if (sheet != null) { Pager pager = resource.getPager(); sheet = Sheet.getCopy(sheet, pager); pager.setCurrentPage(resource.getPage()); childrenElement.appendChild(sheet.getElement(document, false)); childrenElement.appendChild(pager.getElement(document)); } } else if (resource.isPostOrPut()) { // DataCategories if (resource.getDataCategory() != null) { element.appendChild(resource.getDataCategory().getElement(document, false)); } else if (resource.getDataCategories() != null) { Element dataItemsElement = document.createElement("DataCategories"); element.appendChild(dataItemsElement); for (DataCategory dc : resource.getDataCategories()) { dataItemsElement.appendChild(dc.getElement(document, false)); } } // DataItems if (resource.getDataItem() != null) { element.appendChild(resource.getDataItem().getElement(document, false)); } else if (resource.getDataItems() != null) { Element dataItemsElement = document.createElement("DataItems"); element.appendChild(dataItemsElement); for (DataItem di : resource.getDataItems()) { dataItemsElement.appendChild(di.getElement(document, false)); } } } return element; } public Map<String, Object> getTemplateValues(DataCategoryResource resource) { DataCategory dataCategory = resource.getDataCategory(); PathItem pathItem = getPathItem(resource); Sheet sheet = dataSheetService.getSheet(resource.getDataBrowser(), pathItem.getFullPath()); Map<String, Object> values = new HashMap<String, Object>(); values.put("browser", resource.getDataBrowser()); values.put("dataCategory", dataCategory); values.put("itemDefinition", dataCategory.getItemDefinition()); values.put("user", resource.getActiveUser()); values.put("itemDefinitions", definitionService.getItemDefinitions(resource.getActiveEnvironment())); values.put("node", dataCategory); values.put("availableLocales", LocaleConstants.AVAILABLE_LOCALES.keySet()); if (sheet != null) { Pager pager = resource.getPager(); sheet = Sheet.getCopy(sheet, pager); pager.setCurrentPage(resource.getPage()); values.put("sheet", sheet); values.put("pager", pager); } values.put("pathItem", pathItem); // Ensure fullPath value comes from current pathItem and not symlink target pathItem. values.put("fullPath", "/data" + resource.getPathItem()); return values; } public org.apache.abdera.model.Element getAtomElement() { return null; } private PathItem getPathItem(DataCategoryResource resource) { // If the DC is a symlink, use the target PathItem PathItem pathItem = resource.getPathItem(); if (resource.getDataCategory().getAliasedCategory() != null) { PathItemGroup pathItemGroup = pathItemService.getPathItemGroup(resource.getActiveEnvironment()); pathItem = pathItemGroup.findByUId(resource.getDataCategory().getAliasedCategory().getUid()); } return pathItem; } }
true
true
public JSONObject getJSONObject(DataCategoryResource resource) throws JSONException { // create JSON object JSONObject obj = new JSONObject(); obj.put("path", resource.getPathItem().getFullPath()); if (resource.isGet()) { // add DataCategory obj.put("dataCategory", resource.getDataCategory().getJSONObject(true)); // list child Data Categories and child Data Items JSONObject children = new JSONObject(); // Get PathItem. PathItem pathItem = getPathItem(resource); // add Data Categories via pathItem to children JSONArray dataCategories = new JSONArray(); for (PathItem pi : pathItem.getChildrenByType(ObjectType.DC.getName())) { dataCategories.put(pi.getJSONObject()); } children.put("dataCategories", dataCategories); // addItemValue Sheet containing Data Items Sheet sheet = dataSheetService.getSheet(resource.getDataBrowser(), pathItem.getFullPath()); if (sheet != null) { String sortBy = resource.getRequest().getResourceRef().getQueryAsForm().getFirstValue("sortBy"); if (sortBy != null) { Column c = sheet.getColumn(sortBy); if (c != null) { try { c.setSortOrder(SortOrder.valueOf(resource.getRequest().getResourceRef().getQueryAsForm().getFirstValue("sortOrder"))); } catch (IllegalArgumentException e) { // swallow } sheet = Sheet.getCopy(sheet); sheet.getSortBy().getChoices().clear(); sheet.addSortBy(sortBy); sheet.sortRows(); } } Pager pager = resource.getPager(); sheet = Sheet.getCopy(sheet, pager); pager.setCurrentPage(resource.getPage()); children.put("dataItems", sheet.getJSONObject()); children.put("pager", pager.getJSONObject()); } else { children.put("dataItems", new JSONObject()); children.put("pager", new JSONObject()); } // add children obj.put("children", children); } else if (resource.isPostOrPut()) { // DataCategories if (resource.getDataCategory() != null) { obj.put("dataCategory", resource.getDataCategory().getJSONObject(true)); } else if (resource.getDataCategories() != null) { JSONArray dataCategories = new JSONArray(); obj.put("dataCategories", dataCategories); for (DataCategory dc : resource.getDataCategories()) { dataCategories.put(dc.getJSONObject(false)); } } // DataItems if (resource.getDataItem() != null) { obj.put("dataItem", resource.getDataItem().getJSONObject(true)); } else if (resource.getDataItems() != null) { JSONArray dataItems = new JSONArray(); obj.put("dataItems", dataItems); for (DataItem di : resource.getDataItems()) { dataItems.put(di.getJSONObject(false)); } } } return obj; }
public JSONObject getJSONObject(DataCategoryResource resource) throws JSONException { // create JSON object JSONObject obj = new JSONObject(); obj.put("path", resource.getPathItem().getFullPath()); if (resource.isGet()) { // add DataCategory obj.put("dataCategory", resource.getDataCategory().getJSONObject(true)); // list child Data Categories and child Data Items JSONObject children = new JSONObject(); // Get PathItem. PathItem pathItem = getPathItem(resource); // add Data Categories via pathItem to children JSONArray dataCategories = new JSONArray(); for (PathItem pi : pathItem.getChildrenByType(ObjectType.DC.getName())) { dataCategories.put(pi.getJSONObject()); } children.put("dataCategories", dataCategories); // addItemValue Sheet containing Data Items Sheet sheet = dataSheetService.getSheet(resource.getDataBrowser(), pathItem.getFullPath()); if (sheet != null) { String sortBy = resource.getRequest().getResourceRef().getQueryAsForm().getFirstValue("sortBy"); if (sortBy != null) { Column c = sheet.getColumn(sortBy); if (c != null) { try { c.setSortOrder(SortOrder.valueOf(resource.getRequest().getResourceRef().getQueryAsForm().getFirstValue("sortOrder", ""))); } catch (IllegalArgumentException e) { // swallow } sheet = Sheet.getCopy(sheet); sheet.getSortBy().getChoices().clear(); sheet.addSortBy(sortBy); sheet.sortRows(); } } Pager pager = resource.getPager(); sheet = Sheet.getCopy(sheet, pager); pager.setCurrentPage(resource.getPage()); children.put("dataItems", sheet.getJSONObject()); children.put("pager", pager.getJSONObject()); } else { children.put("dataItems", new JSONObject()); children.put("pager", new JSONObject()); } // add children obj.put("children", children); } else if (resource.isPostOrPut()) { // DataCategories if (resource.getDataCategory() != null) { obj.put("dataCategory", resource.getDataCategory().getJSONObject(true)); } else if (resource.getDataCategories() != null) { JSONArray dataCategories = new JSONArray(); obj.put("dataCategories", dataCategories); for (DataCategory dc : resource.getDataCategories()) { dataCategories.put(dc.getJSONObject(false)); } } // DataItems if (resource.getDataItem() != null) { obj.put("dataItem", resource.getDataItem().getJSONObject(true)); } else if (resource.getDataItems() != null) { JSONArray dataItems = new JSONArray(); obj.put("dataItems", dataItems); for (DataItem di : resource.getDataItems()) { dataItems.put(di.getJSONObject(false)); } } } return obj; }
diff --git a/V_semester/networks/JSpellCast/src/com/github/tumas/jspellcast/proto/IcyProtocol.java b/V_semester/networks/JSpellCast/src/com/github/tumas/jspellcast/proto/IcyProtocol.java index a7ffd93..095aef7 100644 --- a/V_semester/networks/JSpellCast/src/com/github/tumas/jspellcast/proto/IcyProtocol.java +++ b/V_semester/networks/JSpellCast/src/com/github/tumas/jspellcast/proto/IcyProtocol.java @@ -1,54 +1,54 @@ package com.github.tumas.jspellcast.proto; import java.util.HashMap; import java.util.StringTokenizer; public class IcyProtocol { public static final String HEADERLINETOKEN = "\r\n"; public static final String HEADERENDTOKEN = HEADERLINETOKEN + HEADERLINETOKEN; public static final String CLIENT2SRVMESSAGE = "GET /%s %s\r\n" + "Host: %s:%s\r\n" + "User-Agent: JSpellCast\r\n" + "Icy-MetaData: %d\r\n" + "Connection: close\r\n\r\n"; public static final String ICYSRV2SRCOK = "ICY 200 OK" + HEADERENDTOKEN; public static final String ICYSRVTOCLMSG = "ICY 200 OK" + HEADERLINETOKEN + "icy-name:%s" + HEADERLINETOKEN + "Content-Type:audio/mpeg" + HEADERLINETOKEN + "icy-br:%s" + HEADERLINETOKEN + "icy-metaint:%d" + HEADERENDTOKEN; /* Naive method definitions ... */ public static HashMap<String, String> parseHeader(String header){ HashMap<String, String> protoObject = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(header, HEADERLINETOKEN); String line; while (st.hasMoreTokens()){ line = st.nextToken(); - String[] strs = line.split(":"); + String[] strs = line.split(":", 2); if (strs.length >= 2) { protoObject.put(strs[0].toLowerCase(), strs[1]); } } return protoObject; } // TODO: rewrite this into a cryptic regExp one liner. public static String getHeaderMountPoint(String header){ String[] lines = header.split(HEADERLINETOKEN); if (lines.length <= 0) return null; String[] lineTokens = lines[0].split(" "); if (lineTokens.length < 2) return null; return lineTokens[1].substring(1); } }
true
true
public static HashMap<String, String> parseHeader(String header){ HashMap<String, String> protoObject = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(header, HEADERLINETOKEN); String line; while (st.hasMoreTokens()){ line = st.nextToken(); String[] strs = line.split(":"); if (strs.length >= 2) { protoObject.put(strs[0].toLowerCase(), strs[1]); } } return protoObject; }
public static HashMap<String, String> parseHeader(String header){ HashMap<String, String> protoObject = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(header, HEADERLINETOKEN); String line; while (st.hasMoreTokens()){ line = st.nextToken(); String[] strs = line.split(":", 2); if (strs.length >= 2) { protoObject.put(strs[0].toLowerCase(), strs[1]); } } return protoObject; }
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java index 64f4d4ef..7761881f 100644 --- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java +++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java @@ -1,1849 +1,1850 @@ package gov.nih.nci.evs.browser.bean; import java.util.*; import java.net.URI; import javax.faces.context.*; import javax.faces.event.*; import javax.faces.model.*; import javax.servlet.http.*; import org.LexGrid.concepts.*; import org.LexGrid.LexBIG.DataModel.Core.*; import org.LexGrid.LexBIG.Utility.Iterators.*; import gov.nih.nci.evs.browser.utils.*; import gov.nih.nci.evs.browser.properties.*; import gov.nih.nci.evs.browser.common.*; import gov.nih.nci.evs.searchlog.*; import org.apache.log4j.*; import org.LexGrid.LexBIG.caCore.interfaces.LexEVSDistributed; import org.lexgrid.valuesets.LexEVSValueSetDefinitionServices; import org.LexGrid.valueSets.ValueSetDefinition; import org.LexGrid.commonTypes.Source; import org.LexGrid.LexBIG.Extensions.Generic.MappingExtension.Mapping.SearchContext; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * 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 disclaimer of Article 3, * below. 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. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. 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 NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES 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. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history Initial implementation [email protected] * */ public class UserSessionBean extends Object { private static Logger _logger = Logger.getLogger(UserSessionBean.class); private static String _contains_warning_msg = "(WARNING: Only a subset of results may appear due to current limits in the terminology server (see Known Issues on the Help page).)"; private String _selectedQuickLink = null; private List _quickLinkList = null; public List<SelectItem> _ontologyList = null; public List<String> _ontologiesToSearchOn = null; public String contextPath = null; public UserSessionBean() { _ontologiesToSearchOn = new ArrayList<String>(); contextPath = getContextPath(); } public String getContextPath() { if (contextPath == null) { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); contextPath = request.getContextPath(); } return contextPath; } public void setSelectedQuickLink(String selectedQuickLink) { _selectedQuickLink = selectedQuickLink; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); request.getSession().setAttribute("selectedQuickLink", selectedQuickLink); } public String getSelectedQuickLink() { return _selectedQuickLink; } public void quickLinkChanged(ValueChangeEvent event) { if (event.getNewValue() == null) return; String newValue = (String) event.getNewValue(); // _logger.debug("quickLinkChanged; " + newValue); setSelectedQuickLink(newValue); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); String targetURL = null;// "http://nciterms.nci.nih.gov/"; if (_selectedQuickLink.compareTo("NCI Terminology Browser") == 0) { targetURL = "http://nciterms.nci.nih.gov/"; } try { response.sendRedirect(response.encodeRedirectURL(targetURL)); } catch (Exception ex) { ex.printStackTrace(); // send error message } } public List getQuickLinkList() { _quickLinkList = new ArrayList(); _quickLinkList.add(new SelectItem("Quick Links")); _quickLinkList.add(new SelectItem("NCI Terminology Browser")); _quickLinkList.add(new SelectItem("NCI MetaThesaurus")); _quickLinkList.add(new SelectItem("EVS Home")); _quickLinkList.add(new SelectItem("NCI Terminology Resources")); return _quickLinkList; } public String searchAction() { System.out.println("(*******************) SearchAction"); HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String matchText = (String) request.getParameter("matchText"); if (matchText != null) matchText = matchText.trim(); // [#19965] Error message is not displayed when Search Criteria is not // proivded if (matchText == null || matchText.length() == 0) { String message = "Please enter a search string."; request.getSession().setAttribute("message", message); // request.getSession().removeAttribute("matchText"); request.removeAttribute("matchText"); return "message"; } request.getSession().setAttribute("matchText", matchText); String matchAlgorithm = (String) request.getParameter("algorithm"); String searchTarget = (String) request.getParameter("searchTarget"); request.getSession().setAttribute("searchTarget", searchTarget); request.getSession().setAttribute("algorithm", matchAlgorithm); boolean ranking = true; String scheme = request.getParameter("scheme"); String searchaction_dictionary = request.getParameter("dictionary"); if (scheme == null) { scheme = (String) request.getAttribute("scheme"); } if (scheme == null) { scheme = (String) request.getParameter("dictionary"); } if (scheme == null) { scheme = Constants.CODING_SCHEME_NAME; } String version = (String) request.getParameter("version"); if (version == null) { version = DataUtils.getVocabularyVersionByTag(scheme, "PRODUCTION"); } request.setAttribute("version", version); _logger.debug("UserSessionBean scheme: " + scheme); _logger.debug("searchAction version: " + version); // KLO, 012610 if (searchTarget.compareTo("relationships") == 0 && matchAlgorithm.compareTo("contains") == 0) { String text = matchText.trim(); if (text.length() < NCItBrowserProperties .getMinimumSearchStringLength()) { String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING; request.getSession().setAttribute("message", msg); request.getSession().setAttribute("vocabulary", scheme); return "message"; } } request.getSession().setAttribute("ranking", Boolean.toString(ranking)); String source = (String) request.getParameter("source"); if (source == null) { source = "ALL"; } if (NCItBrowserProperties._debugOn) { try { _logger.debug(Utils.SEPARATOR); _logger.debug("* criteria: " + matchText); // _logger.debug("* matchType: " + matchtype); _logger.debug("* source: " + source); _logger.debug("* ranking: " + ranking); // _logger.debug("* sortOption: " + sortOption); } catch (Exception e) { } } Vector schemes = new Vector(); schemes.add(scheme); //String version = null; Vector versions = new Vector(); versions.add(version); String max_str = null; int maxToReturn = -1;// 1000; try { max_str = NCItBrowserProperties.getInstance().getProperty( NCItBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { } Utils.StopWatch stopWatch = new Utils.StopWatch(); Vector<org.LexGrid.concepts.Entity> v = null; boolean excludeDesignation = true; boolean designationOnly = false; // check if this search has been performance previously through // IteratorBeanManager IteratorBeanManager iteratorBeanManager = (IteratorBeanManager) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap() .get("iteratorBeanManager"); if (iteratorBeanManager == null) { iteratorBeanManager = new IteratorBeanManager(); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap() .put("iteratorBeanManager", iteratorBeanManager); } IteratorBean iteratorBean = null; ResolvedConceptReferencesIterator iterator = null; String key = iteratorBeanManager.createIteratorKey(schemes, matchText, searchTarget, matchAlgorithm, maxToReturn); if (searchTarget.compareTo("names") == 0) { if (iteratorBeanManager.containsIteratorBean(key)) { iteratorBean = iteratorBeanManager.getIteratorBean(key); iterator = iteratorBean.getIterator(); } else { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils() .searchByName(schemes, versions, matchText, source, matchAlgorithm, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); System.out.println("(**************** iterator = wrapper.getIterator()"); if (iterator != null) { iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBeanManager.addIteratorBean(iteratorBean); } else { System.out.println("(**************** iterator == null???"); } } } } else if (searchTarget.compareTo("properties") == 0) { if (iteratorBeanManager.containsIteratorBean(key)) { iteratorBean = iteratorBeanManager.getIteratorBean(key); iterator = iteratorBean.getIterator(); } else { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByProperties(schemes, versions, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); if (iterator != null) { iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBeanManager.addIteratorBean(iteratorBean); } } } } else if (searchTarget.compareTo("relationships") == 0) { System.out.println("Relationship search *************************************************"); designationOnly = true; if (iteratorBeanManager.containsIteratorBean(key)) { iteratorBean = iteratorBeanManager.getIteratorBean(key); iterator = iteratorBean.getIterator(); } else { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByAssociations(schemes, versions, matchText, source, matchAlgorithm, designationOnly, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); if (iterator != null) { try { int numberOfMatches = iterator.numberRemaining(); System.out.println("Relationship search numberOfMatches: " + numberOfMatches); } catch (Exception ex) { } iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBeanManager.addIteratorBean(iteratorBean); } } } } request.getSession().setAttribute("vocabulary", scheme); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); request.setAttribute("key", key); System.out.println("(*************) setAttribute key: " + key); if (iterator == null) { System.out.println("(*******************) SearchAction iterator == null???"); } if (iterator != null) { // request.getSession().setAttribute("key", key); //request.setAttribute("key", key); //System.out.println("(*************) setAttribute key: " + key); boolean isMapping = DataUtils.isMapping(scheme, version); if (isMapping) { System.out.println("(*************) calling getRestrictedMappingDataIterator -- search by " + searchTarget); iterator = DataUtils.getRestrictedMappingDataIterator(scheme, version, null, iterator, SearchContext.BOTH); if (iterator == null) { String msg = "No match."; request.getSession().setAttribute("message", msg); request.getSession().setAttribute("dictionary", scheme); return "message"; } int numberRemaining = 0; try { numberRemaining = iterator.numberRemaining(); System.out.println("getRestrictedMappingDataIterator returns " + numberRemaining); if (numberRemaining == 0) { String msg = "No match."; request.getSession().setAttribute("message", msg); request.getSession().setAttribute("dictionary", scheme); return "message"; } } catch (Exception ex) { ex.printStackTrace(); } iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBeanManager.addIteratorBean(iteratorBean); MappingIteratorBean mappingIteratorBean = new MappingIteratorBean( iterator, numberRemaining, // number remaining 0, // istart 50, // iend, numberRemaining, // size, 0, // pageNumber, 1); // numberPages mappingIteratorBean.initialize( iterator, numberRemaining, // number remaining 0, // istart 50, // iend, numberRemaining, // size, 0, // pageNumber, 1); // numberPages request.getSession().setAttribute("mapping_search_results", mappingIteratorBean); System.out.println("(*************) returning mapping_search_results"); return "mapping_search_results"; } int size = iteratorBean.getSize(); if (size > 1) { request.getSession().setAttribute("search_results", v); String match_size = Integer.toString(size); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); request.getSession().setAttribute("dictionary", scheme); _logger .debug("UserSessionBean request.getSession().setAttribute dictionary: " + scheme); return "search_results"; } else if (size == 1) { request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", scheme);// Constants.CODING_SCHEME_NAME); int pageNumber = 1; List list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); Entity c = null; if (ref == null) { String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); request.getSession().setAttribute("dictionary", scheme); return "message"; } else { if (ref.getConceptCode() == null) { String message = "Code has not been assigned to the concept matches with '" + matchText + "'"; _logger.warn("WARNING: " + message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("dictionary", scheme); return "message"; } else { request.getSession().setAttribute("code", ref.getConceptCode()); } c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(scheme, null, null, ref .getConceptCode()); if (c == null) { String message = "Unable to find the concept with a code '" + ref.getConceptCode() + "'"; _logger.warn("WARNING: " + message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("dictionary", scheme); return "message"; } } else { request.getSession().setAttribute("code", c.getEntityCode()); } } request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("new_search", Boolean.TRUE); /* //KLO, 021511 isMapping = DataUtils.isMapping(scheme, version); if (isMapping) { System.out.println("(*************) creating mappingIteratorBean"); MappingIteratorBean mappingIteratorBean = new MappingIteratorBean( iterator, numberRemaining, // number remaining 0, // istart 50, // iend, numberRemaining, // size, 0, // pageNumber, 1); // numberPages request.getSession().setAttribute("mapping_search_results", mappingIteratorBean); System.out.println("(*************) returning mapping_search_results"); return "mapping_search_results"; } */ return "concept_details"; } } String message = "No match found."; int minimumSearchStringLength = NCItBrowserProperties.getMinimumSearchStringLength(); if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) { message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS; } else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0 && matchText.length() < minimumSearchStringLength) { message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY; } request.getSession().setAttribute("message", message); request.getSession().setAttribute("dictionary", scheme); return "message"; } private String _selectedResultsPerPage = null; private List _resultsPerPageList = null; public static List getResultsPerPageValues() { List resultsPerPageList = new ArrayList(); resultsPerPageList.add("10"); resultsPerPageList.add("25"); resultsPerPageList.add("50"); resultsPerPageList.add("75"); resultsPerPageList.add("100"); resultsPerPageList.add("250"); resultsPerPageList.add("500"); return resultsPerPageList; } public List getResultsPerPageList() { _resultsPerPageList = new ArrayList(); _resultsPerPageList.add(new SelectItem("10")); _resultsPerPageList.add(new SelectItem("25")); _resultsPerPageList.add(new SelectItem("50")); _resultsPerPageList.add(new SelectItem("75")); _resultsPerPageList.add(new SelectItem("100")); _resultsPerPageList.add(new SelectItem("250")); _resultsPerPageList.add(new SelectItem("500")); _selectedResultsPerPage = ((SelectItem) _resultsPerPageList.get(2)).getLabel(); // default to // 50 return _resultsPerPageList; } public void setSelectedResultsPerPage(String selectedResultsPerPage) { if (selectedResultsPerPage == null) { System.out.println("(*) selectedResultsPerPage == null ??? "); return; } _selectedResultsPerPage = selectedResultsPerPage; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); request.getSession().setAttribute("selectedResultsPerPage", selectedResultsPerPage); System.out.println("(*) request.getSession().setAttribute selectedResultsPerPage " + selectedResultsPerPage); } public String getSelectedResultsPerPage() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String s = (String) request.getSession() .getAttribute("selectedResultsPerPage"); if (s != null) { _selectedResultsPerPage = s; } else { _selectedResultsPerPage = "50"; request.getSession().setAttribute("selectedResultsPerPage", "50"); } return _selectedResultsPerPage; } public void resultsPerPageChanged(ValueChangeEvent event) { if (event.getNewValue() == null) { System.out.println("(*) UserSessionBean event.getNewValue() == null??? "); return; } String newValue = (String) event.getNewValue(); System.out.println("(*) UserSessionBean resultsPerPageChanged newValue: " + newValue); setSelectedResultsPerPage(newValue); } public String linkAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); return ""; } private String _selectedAlgorithm = null; private List _algorithmList = null; public List getAlgorithmList() { _algorithmList = new ArrayList(); _algorithmList.add(new SelectItem("exactMatch", "exactMatch")); _algorithmList.add(new SelectItem("startsWith", "Begins With")); _algorithmList.add(new SelectItem("contains", "Contains")); _selectedAlgorithm = ((SelectItem) _algorithmList.get(0)).getLabel(); return _algorithmList; } public void algorithmChanged(ValueChangeEvent event) { if (event.getNewValue() == null) return; String newValue = (String) event.getNewValue(); setSelectedAlgorithm(newValue); } public void setSelectedAlgorithm(String selectedAlgorithm) { _selectedAlgorithm = selectedAlgorithm; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); request.getSession().setAttribute("algorithm", selectedAlgorithm); } public String getSelectedAlgorithm() { return _selectedAlgorithm; } public String contactUs() throws Exception { String msg = "Your message was successfully sent."; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); try { String subject = request.getParameter("subject"); String message = request.getParameter("message"); String from = request.getParameter("emailaddress"); String recipients[] = MailUtils.getRecipients(); MailUtils.postMail(from, recipients, subject, message); } catch (UserInputException e) { msg = e.getMessage(); request.setAttribute("errorMsg", Utils.toHtml(msg)); request.setAttribute("errorType", "user"); return "error"; } catch (Exception e) { msg = "System Error: Your message was not sent.\n"; msg += " (If possible, please contact NCI systems team.)\n"; msg += "\n"; msg += e.getMessage(); request.setAttribute("errorMsg", Utils.toHtml(msg)); request.setAttribute("errorType", "system"); e.printStackTrace(); return "error"; } request.getSession().setAttribute("message", Utils.toHtml(msg)); return "message"; } // ////////////////////////////////////////////////////////////////////////////////////////// // ontologies public List getOntologiesToSearchOn() { if (_ontologyList == null) { _ontologyList = DataUtils.getOntologyList(); SelectItem item = (SelectItem) _ontologyList.get(0); _ontologiesToSearchOn.add(item.getLabel()); } else if (_ontologiesToSearchOn.size() == 0) { SelectItem item = (SelectItem) _ontologyList.get(0); _ontologiesToSearchOn.add(item.getLabel()); } return _ontologiesToSearchOn; } public List getOntologyList() { if (_ontologyList == null) { _ontologyList = DataUtils.getOntologyList(); } return _ontologyList; } public void setOntologiesToSearchOn(List<String> newValue) { _ontologiesToSearchOn = new ArrayList<String>(); for (int i = 0; i < newValue.size(); i++) { Object obj = newValue.get(i); _ontologiesToSearchOn.add((String) obj); } } public void ontologiesToSearchOnChanged(ValueChangeEvent event) { if (event.getNewValue() == null) { return; } List newValue = (List) event.getNewValue(); setOntologiesToSearchOn(newValue); } public List<SelectItem> _ontologySelectionList = null; public String _ontologyToSearchOn = null; public List getOntologySelectionList() { if (_ontologySelectionList != null) return _ontologySelectionList; List ontologies = getOntologyList(); _ontologySelectionList = new ArrayList<SelectItem>(); String label = "Switch to another vocabulary (select one)"; _ontologySelectionList.add(new SelectItem(label, label)); for (int i = 0; i < ontologies.size(); i++) { SelectItem item = (SelectItem) _ontologyList.get(i); _ontologySelectionList.add(item); } return _ontologySelectionList; } public void ontologySelectionChanged(ValueChangeEvent event) { if (event.getNewValue() == null) { // _logger.warn("ontologySelectionChanged; event.getNewValue() == null "); return; } String newValue = (String) event.getNewValue(); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); String targetURL = null;// "http://nciterms.nci.nih.gov/"; targetURL = "http://nciterms.nci.nih.gov/"; try { response.sendRedirect(response.encodeRedirectURL(targetURL)); } catch (Exception ex) { ex.printStackTrace(); } } public String getOntologyToSearchOn() { if (_ontologySelectionList == null) { _ontologySelectionList = getOntologySelectionList(); SelectItem item = (SelectItem) _ontologyList.get(1); _ontologyToSearchOn = item.getLabel(); } return _ontologyToSearchOn; } public void setOntologyToSearchOn(String newValue) { _ontologyToSearchOn = newValue; } // ////////////////////////////////////////////////////////////////////////////////////// private String[] getSelectedVocabularies(String ontology_list_str) { Vector v = DataUtils.parseData(ontology_list_str); String[] ontology_list = new String[v.size()]; for (int i = 0; i < v.size(); i++) { String s = (String) v.elementAt(i); ontology_list[i] = s; } return ontology_list; } public String acceptLicenseAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String dictionary = (String) request.getParameter("dictionary"); String code = (String) request.getParameter("code"); if (dictionary != null && code != null) { LicenseBean licenseBean = (LicenseBean) request.getSession().getAttribute("licenseBean"); if (licenseBean == null) { licenseBean = new LicenseBean(); } licenseBean.addLicenseAgreement(dictionary); request.getSession().setAttribute("licenseBean", licenseBean); Entity c = DataUtils.getConceptByCode(dictionary, null, null, code); request.getSession().setAttribute("code", code); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); return "concept_details"; } else { String message = "Unidentifiable vocabulary name, or code"; request.getSession().setAttribute("warning", message); return "message"; } } public String multipleSearchAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String scheme = (String) request.getParameter("scheme"); String version = (String) request.getParameter("version"); String navigation_type = request.getParameter("nav_type"); if (navigation_type == null || navigation_type.equals("null")) { navigation_type = "terminologies"; } // Called from license.jsp LicenseBean licenseBean = (LicenseBean) request.getSession().getAttribute("licenseBean"); if (scheme != null && version != null) { if (licenseBean == null) { licenseBean = new LicenseBean(); } licenseBean.addLicenseAgreement(scheme); request.getSession().setAttribute("licenseBean", licenseBean); } String matchText = (String) request.getParameter("matchText"); if (matchText != null) { matchText = matchText.trim(); request.getSession().setAttribute("matchText", matchText); } else { matchText = (String) request.getSession().getAttribute("matchText"); } String multiple_search_error = (String) request.getSession().getAttribute( "multiple_search_no_match_error"); request.getSession().removeAttribute("multiple_search_no_match_error"); String matchAlgorithm = (String) request.getParameter("algorithm"); request.getSession().setAttribute("algorithm", matchAlgorithm); String searchTarget = (String) request.getParameter("searchTarget"); request.getSession().setAttribute("searchTarget", searchTarget); String initial_search = (String) request.getParameter("initial_search"); String[] ontology_list = null; //if (navigation_type == null || navigation_type.compareTo("terminologies") == 0) { ontology_list = request.getParameterValues("ontology_list"); //} List list = new ArrayList<String>(); String ontologiesToSearchOnStr = null; String ontology_list_str = null; List<String> ontologiesToSearchOn = null; int knt = 0; // process mappings if (initial_search != null) { // from home page if (multiple_search_error != null) { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = (String) request.getSession().getAttribute( "ontologiesToSearchOn"); if (ontologiesToSearchOnStr != null) { Vector ontologies_to_search_on = DataUtils.parseData(ontologiesToSearchOnStr); ontology_list = new String[ontologies_to_search_on.size()]; knt = ontologies_to_search_on.size(); for (int k = 0; k < ontologies_to_search_on.size(); k++) { String s = (String) ontologies_to_search_on.elementAt(k); ontology_list[k] = s; ontologiesToSearchOn.add(s); } } } if (ontology_list == null || ontology_list.length == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().removeAttribute("ontologiesToSearchOn"); // String defaultOntologiesToSearchOnStr = // ontologiesToSearchOnStr; request.getSession().setAttribute( "defaultOntologiesToSearchOnStr", "|"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } else { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = "|"; for (int i = 0; i < ontology_list.length; ++i) { list.add(ontology_list[i]); ontologiesToSearchOn.add(ontology_list[i]); ontologiesToSearchOnStr = ontologiesToSearchOnStr + ontology_list[i] + "|"; } if (ontology_list_str == null) { ontology_list_str = ""; for (int i = 0; i < ontology_list.length; ++i) { ontology_list_str = ontology_list_str + ontology_list[i]; if (i < ontology_list.length - 1) { ontology_list_str = ontology_list_str + "|"; } } } request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); } } else { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = (String) request.getSession().getAttribute( "ontologiesToSearchOn"); if (ontologiesToSearchOnStr != null) { Vector ontologies_to_search_on = DataUtils.parseData(ontologiesToSearchOnStr); ontology_list = new String[ontologies_to_search_on.size()]; knt = ontologies_to_search_on.size(); for (int k = 0; k < ontologies_to_search_on.size(); k++) { String s = (String) ontologies_to_search_on.elementAt(k); ontology_list[k] = s; ontologiesToSearchOn.add(s); } } } String hide_ontology_list = "false"; // [#19965] Error message is not displayed when Search Criteria is not // proivided if (matchText == null || matchText.length() == 0) { String message = Constants.ERROR_NO_SEARCH_STRING_ENTERED; if (initial_search == null) { hide_ontology_list = "true"; } request.getSession().setAttribute("hide_ontology_list", hide_ontology_list); request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } // KLO, 012610 else if (searchTarget.compareTo("relationships") == 0 && matchAlgorithm.compareTo("contains") == 0) { String text = matchText.trim(); if (text.length() < NCItBrowserProperties .getMinimumSearchStringLength()) { String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING; request.getSession().setAttribute("warning", msg); request.getSession().setAttribute("message", msg); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } } boolean ranking = true; String source = (String) request.getParameter("source"); if (source == null) { source = "ALL"; } if (NCItBrowserProperties._debugOn) { try { _logger.debug(Utils.SEPARATOR); _logger.debug("* criteria: " + matchText); _logger.debug("* source: " + source); _logger.debug("* ranking: " + ranking); _logger.debug("* ontology_list: "); for (int i = 0; i < ontology_list.length; ++i) { _logger.debug(" " + i + ") " + ontology_list[i]); } } catch (Exception e) { } } if (ontology_list == null) { ontology_list_str = (String) request.getParameter("ontology_list_str"); // from // multiple_search_results // (hidden // variable) if (ontology_list_str != null) { ontology_list = getSelectedVocabularies(ontology_list_str); } } else { knt = ontology_list.length; if (knt == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("hide_ontology_list", "true"); request.getSession().removeAttribute("ontologiesToSearchOn"); // String defaultOntologiesToSearchOnStr = // ontologiesToSearchOnStr; request.getSession().setAttribute( "defaultOntologiesToSearchOnStr", "|"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } } Vector schemes = new Vector(); Vector versions = new Vector(); ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = "|"; for (int i = 0; i < ontology_list.length; ++i) { list.add(ontology_list[i]); ontologiesToSearchOn.add(ontology_list[i]); ontologiesToSearchOnStr = ontologiesToSearchOnStr + ontology_list[i] + "|"; } if (ontology_list_str == null) { ontology_list_str = ""; for (int i = 0; i < ontology_list.length; ++i) { ontology_list_str = ontology_list_str + ontology_list[i]; if (i < ontology_list.length - 1) { ontology_list_str = ontology_list_str + "|"; } } } scheme = null; version = null; String t = ""; if (ontologiesToSearchOn.size() == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().removeAttribute("ontologiesToSearchOn"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } else { request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); // [#25270] Set "all but NCIm selected" as the default for the TB // home page. String defaultOntologiesToSearchOnStr = ontologiesToSearchOnStr; request.getSession().setAttribute("defaultOntologiesToSearchOnStr", defaultOntologiesToSearchOnStr); for (int k = 0; k < ontologiesToSearchOn.size(); k++) { String key = (String) list.get(k); if (key != null) { scheme = DataUtils.key2CodingSchemeName(key); version = DataUtils.key2CodingSchemeVersion(key); if (scheme != null) { schemes.add(scheme); // to be modified (handling of versions) versions.add(version); t = t + scheme + " (" + version + ")" + "\n"; boolean isLicensed = LicenseBean.isLicensed(scheme, version); if (licenseBean == null) { licenseBean = new LicenseBean(); request.getSession().setAttribute("licenseBean", licenseBean); } boolean accepted = licenseBean.licenseAgreementAccepted(scheme); if (isLicensed && !accepted) { request.getSession().setAttribute("matchText", matchText); request.setAttribute("searchTarget", searchTarget); request.setAttribute("algorithm", matchAlgorithm); request.setAttribute("ontology_list_str", ontology_list_str); request.setAttribute("scheme", scheme); request.setAttribute("version", version); return "license"; } } else { _logger.warn("Unable to identify " + key); } } } } String max_str = null; int maxToReturn = -1;// 1000; try { max_str = NCItBrowserProperties .getProperty(NCItBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { // Do nothing } boolean designationOnly = false; boolean excludeDesignation = true; ResolvedConceptReferencesIterator iterator = null; if (searchTarget.compareTo("names") == 0) { long ms = System.currentTimeMillis(); long delay = 0; _logger.debug("Calling SearchUtils().searchByName " + matchText); ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByName(schemes, versions, matchText, source, matchAlgorithm, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } delay = System.currentTimeMillis() - ms; _logger.debug("searchByName delay (millisec.): " + delay); } else if (searchTarget.compareTo("properties") == 0) { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByProperties(schemes, versions, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } else if (searchTarget.compareTo("relationships") == 0) { designationOnly = true; ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByAssociations(schemes, versions, matchText, source, matchAlgorithm, designationOnly, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } request.getSession().setAttribute("vocabulary", scheme); request.getSession().setAttribute("searchTarget", searchTarget); request.getSession().setAttribute("algorithm", matchAlgorithm); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); if (iterator != null) { IteratorBean iteratorBean = (IteratorBean) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("iteratorBean"); if (iteratorBean == null) { iteratorBean = new IteratorBean(iterator); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put("iteratorBean", iteratorBean); } else { iteratorBean.setIterator(iterator); } int size = iteratorBean.getSize(); if (size == 1) { int pageNumber = 1; list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); String coding_scheme = ref.getCodingSchemeName(); + String ref_version = ref.getCodingSchemeVersion(); if (coding_scheme.compareToIgnoreCase("NCI Metathesaurus") == 0) { String match_size = Integer.toString(size); ;// Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); // route to multiple_search_results.jsp return "search_results"; } request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", coding_scheme); - request.getSession().setAttribute("version", version); + request.getSession().setAttribute("version", ref_version); Entity c = null; if (ref == null) { String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "message"; } else { c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(coding_scheme, null, null, ref.getConceptCode()); } } request.getSession().setAttribute("code", ref.getConceptCode()); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("new_search", Boolean.TRUE); request.setAttribute("algorithm", matchAlgorithm); coding_scheme = (String) DataUtils._localName2FormalNameHashMap .get(coding_scheme); String convertJSPString = HTTPUtils.convertJSPString(matchText); request.getSession() .setAttribute("matchText", convertJSPString); request.setAttribute("dictionary", coding_scheme); - request.setAttribute("version", version); + request.setAttribute("version", ref_version); return "concept_details"; } else if (size > 0) { String match_size = Integer.toString(size); ;// Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); // route to multiple_search_results.jsp request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); _logger.debug("Start to render search_results ... "); return "search_results"; } } int minimumSearchStringLength = NCItBrowserProperties.getMinimumSearchStringLength(); if (ontologiesToSearchOn.size() == 0) { request.getSession().removeAttribute("vocabulary"); } else if (ontologiesToSearchOn.size() == 1) { String msg_scheme = (String) ontologiesToSearchOn.get(0); request.getSession().setAttribute("vocabulary", msg_scheme); } else { request.getSession().removeAttribute("vocabulary"); } String message = Constants.ERROR_NO_MATCH_FOUND; if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) { message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS; } else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0 && matchText.length() < minimumSearchStringLength) { message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY; } hide_ontology_list = "false"; /* * if (initial_search == null) { hide_ontology_list = "true"; } */ request.getSession().setAttribute("hide_ontology_list", hide_ontology_list); request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); request.getSession().setAttribute("multiple_search_no_match_error", "true"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } public String acceptLicenseAgreement() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); // update LicenseBean String dictionary = (String) request.getParameter("dictionary"); String version = (String) request.getParameter("version"); LicenseBean licenseBean = (LicenseBean) request.getSession().getAttribute("licenseBean"); if (licenseBean == null) { licenseBean = new LicenseBean(); } licenseBean.addLicenseAgreement(dictionary); request.getSession().setAttribute("licenseBean", licenseBean); request.getSession().setAttribute("dictionary", dictionary); request.getSession().setAttribute("scheme", dictionary); request.getSession().setAttribute("version", version); return "vocabulary_home"; } public String advancedSearchAction() { ResolvedConceptReferencesIteratorWrapper wrapper = null; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String scheme = (String) request.getParameter("dictionary"); String version = (String) request.getParameter("version"); System.out.println("advancedSearchAction version: " + version); SearchStatusBean bean = (SearchStatusBean) FacesContext.getCurrentInstance() .getExternalContext().getRequestMap().get("searchStatusBean"); if (bean == null) { bean = new SearchStatusBean(scheme, version); request.setAttribute("searchStatusBean", bean); } String matchType = (String) request.getParameter("adv_search_type"); bean.setSearchType(matchType); String matchAlgorithm = (String) request.getParameter("adv_search_algorithm"); bean.setAlgorithm(matchAlgorithm); String source = (String) request.getParameter("adv_search_source"); bean.setSelectedSource(source); String selectSearchOption = (String) request.getParameter("selectSearchOption"); bean.setSelectedSearchOption(selectSearchOption); String selectProperty = (String) request.getParameter("selectProperty"); bean.setSelectedProperty(selectProperty); String rel_search_association = (String) request.getParameter("rel_search_association"); bean.setSelectedAssociation(rel_search_association); String rel_search_rela = (String) request.getParameter("rel_search_rela"); bean.setSelectedRELA(rel_search_rela); FacesContext.getCurrentInstance().getExternalContext().getRequestMap() .put("searchStatusBean", bean); request.setAttribute("searchStatusBean", bean); String searchTarget = (String) request.getParameter("searchTarget"); String matchText = (String) request.getParameter("matchText"); if (matchText == null || matchText.length() == 0) { String message = "Please enter a search string."; // request.getSession().setAttribute("message", message); request.setAttribute("message", message); return "message"; } matchText = matchText.trim(); bean.setMatchText(matchText); if (NCItBrowserProperties._debugOn) { _logger.debug(Utils.SEPARATOR); _logger.debug("* criteria: " + matchText); _logger.debug("* source: " + source); } // String scheme = Constants.CODING_SCHEME_NAME; Vector schemes = new Vector(); schemes.add(scheme); String max_str = null; int maxToReturn = -1;// 1000; try { max_str = NCItBrowserProperties.getInstance().getProperty( NCItBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { } Utils.StopWatch stopWatch = new Utils.StopWatch(); Vector<org.LexGrid.concepts.Entity> v = null; boolean excludeDesignation = true; boolean designationOnly = false; // check if this search has been performance previously through // IteratorBeanManager IteratorBeanManager iteratorBeanManager = (IteratorBeanManager) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap() .get("iteratorBeanManager"); if (iteratorBeanManager == null) { iteratorBeanManager = new IteratorBeanManager(); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap() .put("iteratorBeanManager", iteratorBeanManager); } IteratorBean iteratorBean = null; ResolvedConceptReferencesIterator iterator = null; boolean ranking = true; SearchFields searchFields = null; String key = null; String searchType = (String) request.getParameter("selectSearchOption"); _logger.debug("SearchUtils.java searchType: " + searchType); if (searchType != null && searchType.compareTo("Property") == 0) { /* * _logger.debug("Advanced Search: "); _logger.debug("searchType: " * + searchType); _logger.debug("matchText: " + matchText); * _logger.debug("adv_search_algorithm: " + adv_search_algorithm); * _logger.debug("adv_search_source: " + adv_search_source); */ String property_type = (String) request.getParameter("selectPropertyType"); if (property_type != null && property_type.compareTo("ALL") == 0) { property_type = null; } String property_name = selectProperty; if (property_name != null) { property_name = property_name.trim(); // if (property_name.length() == 0) property_name = null; if (property_name.compareTo("ALL") == 0) property_name = null; } searchFields = SearchFields.setProperty(schemes, matchText, searchTarget, property_type, property_name, source, matchAlgorithm, maxToReturn); key = searchFields.getKey(); _logger.debug("advancedSearchAction " + key); if (iteratorBeanManager.containsIteratorBean(key)) { iteratorBean = iteratorBeanManager.getIteratorBean(key); iterator = iteratorBean.getIterator(); } else { String[] property_types = null; if (property_type != null) property_types = new String[] { property_type }; String[] property_names = null; if (property_name != null) property_names = new String[] { property_name }; excludeDesignation = false; wrapper = new SearchUtils().searchByProperties(scheme, version, matchText, property_types, property_names, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } if (iterator != null) { iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBean.setMatchText(matchText); iteratorBeanManager.addIteratorBean(iteratorBean); } } } else if (searchType != null && searchType.compareTo("Relationship") == 0) { if (rel_search_association != null && rel_search_association.compareTo("ALL") == 0) rel_search_association = null; if (rel_search_rela != null) { rel_search_rela = rel_search_rela.trim(); if (rel_search_rela.length() == 0) rel_search_rela = null; } /* * String rel_search_direction = (String) * request.getParameter("rel_search_direction"); * * //boolean direction = false; int search_direction = * Constants.SEARCH_BOTH_DIRECTION; if (rel_search_direction != null * && rel_search_direction.compareTo("source") == 0) { * search_direction = Constants.SEARCH_SOURCE; //direction = true; } * else if (rel_search_direction != null && * rel_search_direction.compareTo("target") == 0) { search_direction * = Constants.SEARCH_TARGET; //direction = true; } */ int search_direction = Constants.SEARCH_SOURCE; _logger.debug("AdvancedSearchAction search_direction " + search_direction); searchFields = SearchFields.setRelationship(schemes, matchText, searchTarget, rel_search_association, rel_search_rela, source, matchAlgorithm, maxToReturn); key = searchFields.getKey(); _logger.debug("AdvancedSearchAction key " + key); if (iteratorBeanManager.containsIteratorBean(key)) { iteratorBean = iteratorBeanManager.getIteratorBean(key); iterator = iteratorBean.getIterator(); } else { String[] associationsToNavigate = null; String[] association_qualifier_names = null; String[] association_qualifier_values = null; if (rel_search_association != null) { /* associationsToNavigate = new String[] { rel_search_association }; */ String assocName = OntologyBean.convertAssociationName(scheme, null, rel_search_association); //_logger.debug("Converting " + rel_search_association + " to " + assocName); associationsToNavigate = new String[] { assocName }; } else { _logger.debug("(*) associationsToNavigate == null"); } if (rel_search_rela != null) { association_qualifier_names = new String[] { "rela" }; association_qualifier_values = new String[] { rel_search_rela }; if (associationsToNavigate == null) { Vector w = OntologyBean.getAssociationNames(scheme); if (w == null || w.size() == 0) { _logger .warn("OntologyBean.getAssociationNames() returns null, or nothing???"); } else { associationsToNavigate = new String[w.size()]; for (int i = 0; i < w.size(); i++) { String nm = (String) w.elementAt(i); associationsToNavigate[i] = nm; } } } } else { _logger.warn("(*) qualifiers == null"); } wrapper = new SearchUtils().searchByAssociations(scheme, version, matchText, associationsToNavigate, association_qualifier_names, association_qualifier_values, search_direction, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } if (iterator != null) { iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBean.setMatchText(matchText); iteratorBeanManager.addIteratorBean(iteratorBean); } } } else if (searchType != null && searchType.compareTo("Name") == 0) { searchFields = SearchFields.setName(schemes, matchText, searchTarget, source, matchAlgorithm, maxToReturn); key = searchFields.getKey(); if (iteratorBeanManager.containsIteratorBean(key)) { iteratorBean = iteratorBeanManager.getIteratorBean(key); iterator = iteratorBean.getIterator(); } else { wrapper = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, ranking, maxToReturn, SearchUtils.NameSearchType.Name); if (wrapper != null) { iterator = wrapper.getIterator(); if (iterator != null) { iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBean.setMatchText(matchText); iteratorBeanManager.addIteratorBean(iteratorBean); } } } } else if (searchType != null && searchType.compareTo("Code") == 0) { searchFields = SearchFields.setCode(schemes, matchText, searchTarget, source, matchAlgorithm, maxToReturn); key = searchFields.getKey(); if (iteratorBeanManager.containsIteratorBean(key)) { iteratorBean = iteratorBeanManager.getIteratorBean(key); iterator = iteratorBean.getIterator(); } else { /* * wrapper = new SearchUtils().searchByName(scheme, version, * matchText, source, matchAlgorithm, ranking, maxToReturn, * SearchUtils.NameSearchType.Code); */ wrapper = new SearchUtils().searchByCode(scheme, version, matchText, source, matchAlgorithm, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); if (iterator != null) { iteratorBean = new IteratorBean(iterator); iteratorBean.setKey(key); iteratorBean.setMatchText(matchText); iteratorBeanManager.addIteratorBean(iteratorBean); } } } } request.setAttribute("key", key); request.getSession().setAttribute("matchText", matchText); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); if (iterator != null) { int size = iteratorBean.getSize(); _logger.debug("AdvancedSearchActon size: " + size); // Write a search log entry SearchLog.writeEntry(searchFields, size, HTTPUtils .getRefererParmDecode(request)); if (size > 1) { request.getSession().setAttribute("search_results", v); String match_size = Integer.toString(size); ;// Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.setAttribute("version", version); request.getSession().setAttribute("new_search", Boolean.TRUE); return "search_results"; } else if (size == 1) { request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", scheme); // Concept c = (Concept) v.elementAt(0); int pageNumber = 1; List list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); Entity c = null; if (ref == null) { String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); return "message"; } else { c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(scheme, null, null, ref .getConceptCode()); } } request.getSession().setAttribute("code", ref.getConceptCode()); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("version", version); request.getSession().setAttribute("new_search", Boolean.TRUE); return "concept_details"; } } String message = "No match found."; if (matchAlgorithm.compareTo("exactMatch") == 0) { message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS; } request.setAttribute("message", message); return "no_match"; } //resolveValueSetAction public String resolveValueSetAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); return "resolve_value_set"; } public String continueResolveValueSetAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); return "resolved_value_set"; } public String exportValueSetAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); return "exported_value_set"; } }
false
true
public String multipleSearchAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String scheme = (String) request.getParameter("scheme"); String version = (String) request.getParameter("version"); String navigation_type = request.getParameter("nav_type"); if (navigation_type == null || navigation_type.equals("null")) { navigation_type = "terminologies"; } // Called from license.jsp LicenseBean licenseBean = (LicenseBean) request.getSession().getAttribute("licenseBean"); if (scheme != null && version != null) { if (licenseBean == null) { licenseBean = new LicenseBean(); } licenseBean.addLicenseAgreement(scheme); request.getSession().setAttribute("licenseBean", licenseBean); } String matchText = (String) request.getParameter("matchText"); if (matchText != null) { matchText = matchText.trim(); request.getSession().setAttribute("matchText", matchText); } else { matchText = (String) request.getSession().getAttribute("matchText"); } String multiple_search_error = (String) request.getSession().getAttribute( "multiple_search_no_match_error"); request.getSession().removeAttribute("multiple_search_no_match_error"); String matchAlgorithm = (String) request.getParameter("algorithm"); request.getSession().setAttribute("algorithm", matchAlgorithm); String searchTarget = (String) request.getParameter("searchTarget"); request.getSession().setAttribute("searchTarget", searchTarget); String initial_search = (String) request.getParameter("initial_search"); String[] ontology_list = null; //if (navigation_type == null || navigation_type.compareTo("terminologies") == 0) { ontology_list = request.getParameterValues("ontology_list"); //} List list = new ArrayList<String>(); String ontologiesToSearchOnStr = null; String ontology_list_str = null; List<String> ontologiesToSearchOn = null; int knt = 0; // process mappings if (initial_search != null) { // from home page if (multiple_search_error != null) { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = (String) request.getSession().getAttribute( "ontologiesToSearchOn"); if (ontologiesToSearchOnStr != null) { Vector ontologies_to_search_on = DataUtils.parseData(ontologiesToSearchOnStr); ontology_list = new String[ontologies_to_search_on.size()]; knt = ontologies_to_search_on.size(); for (int k = 0; k < ontologies_to_search_on.size(); k++) { String s = (String) ontologies_to_search_on.elementAt(k); ontology_list[k] = s; ontologiesToSearchOn.add(s); } } } if (ontology_list == null || ontology_list.length == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().removeAttribute("ontologiesToSearchOn"); // String defaultOntologiesToSearchOnStr = // ontologiesToSearchOnStr; request.getSession().setAttribute( "defaultOntologiesToSearchOnStr", "|"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } else { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = "|"; for (int i = 0; i < ontology_list.length; ++i) { list.add(ontology_list[i]); ontologiesToSearchOn.add(ontology_list[i]); ontologiesToSearchOnStr = ontologiesToSearchOnStr + ontology_list[i] + "|"; } if (ontology_list_str == null) { ontology_list_str = ""; for (int i = 0; i < ontology_list.length; ++i) { ontology_list_str = ontology_list_str + ontology_list[i]; if (i < ontology_list.length - 1) { ontology_list_str = ontology_list_str + "|"; } } } request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); } } else { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = (String) request.getSession().getAttribute( "ontologiesToSearchOn"); if (ontologiesToSearchOnStr != null) { Vector ontologies_to_search_on = DataUtils.parseData(ontologiesToSearchOnStr); ontology_list = new String[ontologies_to_search_on.size()]; knt = ontologies_to_search_on.size(); for (int k = 0; k < ontologies_to_search_on.size(); k++) { String s = (String) ontologies_to_search_on.elementAt(k); ontology_list[k] = s; ontologiesToSearchOn.add(s); } } } String hide_ontology_list = "false"; // [#19965] Error message is not displayed when Search Criteria is not // proivided if (matchText == null || matchText.length() == 0) { String message = Constants.ERROR_NO_SEARCH_STRING_ENTERED; if (initial_search == null) { hide_ontology_list = "true"; } request.getSession().setAttribute("hide_ontology_list", hide_ontology_list); request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } // KLO, 012610 else if (searchTarget.compareTo("relationships") == 0 && matchAlgorithm.compareTo("contains") == 0) { String text = matchText.trim(); if (text.length() < NCItBrowserProperties .getMinimumSearchStringLength()) { String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING; request.getSession().setAttribute("warning", msg); request.getSession().setAttribute("message", msg); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } } boolean ranking = true; String source = (String) request.getParameter("source"); if (source == null) { source = "ALL"; } if (NCItBrowserProperties._debugOn) { try { _logger.debug(Utils.SEPARATOR); _logger.debug("* criteria: " + matchText); _logger.debug("* source: " + source); _logger.debug("* ranking: " + ranking); _logger.debug("* ontology_list: "); for (int i = 0; i < ontology_list.length; ++i) { _logger.debug(" " + i + ") " + ontology_list[i]); } } catch (Exception e) { } } if (ontology_list == null) { ontology_list_str = (String) request.getParameter("ontology_list_str"); // from // multiple_search_results // (hidden // variable) if (ontology_list_str != null) { ontology_list = getSelectedVocabularies(ontology_list_str); } } else { knt = ontology_list.length; if (knt == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("hide_ontology_list", "true"); request.getSession().removeAttribute("ontologiesToSearchOn"); // String defaultOntologiesToSearchOnStr = // ontologiesToSearchOnStr; request.getSession().setAttribute( "defaultOntologiesToSearchOnStr", "|"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } } Vector schemes = new Vector(); Vector versions = new Vector(); ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = "|"; for (int i = 0; i < ontology_list.length; ++i) { list.add(ontology_list[i]); ontologiesToSearchOn.add(ontology_list[i]); ontologiesToSearchOnStr = ontologiesToSearchOnStr + ontology_list[i] + "|"; } if (ontology_list_str == null) { ontology_list_str = ""; for (int i = 0; i < ontology_list.length; ++i) { ontology_list_str = ontology_list_str + ontology_list[i]; if (i < ontology_list.length - 1) { ontology_list_str = ontology_list_str + "|"; } } } scheme = null; version = null; String t = ""; if (ontologiesToSearchOn.size() == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().removeAttribute("ontologiesToSearchOn"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } else { request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); // [#25270] Set "all but NCIm selected" as the default for the TB // home page. String defaultOntologiesToSearchOnStr = ontologiesToSearchOnStr; request.getSession().setAttribute("defaultOntologiesToSearchOnStr", defaultOntologiesToSearchOnStr); for (int k = 0; k < ontologiesToSearchOn.size(); k++) { String key = (String) list.get(k); if (key != null) { scheme = DataUtils.key2CodingSchemeName(key); version = DataUtils.key2CodingSchemeVersion(key); if (scheme != null) { schemes.add(scheme); // to be modified (handling of versions) versions.add(version); t = t + scheme + " (" + version + ")" + "\n"; boolean isLicensed = LicenseBean.isLicensed(scheme, version); if (licenseBean == null) { licenseBean = new LicenseBean(); request.getSession().setAttribute("licenseBean", licenseBean); } boolean accepted = licenseBean.licenseAgreementAccepted(scheme); if (isLicensed && !accepted) { request.getSession().setAttribute("matchText", matchText); request.setAttribute("searchTarget", searchTarget); request.setAttribute("algorithm", matchAlgorithm); request.setAttribute("ontology_list_str", ontology_list_str); request.setAttribute("scheme", scheme); request.setAttribute("version", version); return "license"; } } else { _logger.warn("Unable to identify " + key); } } } } String max_str = null; int maxToReturn = -1;// 1000; try { max_str = NCItBrowserProperties .getProperty(NCItBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { // Do nothing } boolean designationOnly = false; boolean excludeDesignation = true; ResolvedConceptReferencesIterator iterator = null; if (searchTarget.compareTo("names") == 0) { long ms = System.currentTimeMillis(); long delay = 0; _logger.debug("Calling SearchUtils().searchByName " + matchText); ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByName(schemes, versions, matchText, source, matchAlgorithm, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } delay = System.currentTimeMillis() - ms; _logger.debug("searchByName delay (millisec.): " + delay); } else if (searchTarget.compareTo("properties") == 0) { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByProperties(schemes, versions, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } else if (searchTarget.compareTo("relationships") == 0) { designationOnly = true; ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByAssociations(schemes, versions, matchText, source, matchAlgorithm, designationOnly, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } request.getSession().setAttribute("vocabulary", scheme); request.getSession().setAttribute("searchTarget", searchTarget); request.getSession().setAttribute("algorithm", matchAlgorithm); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); if (iterator != null) { IteratorBean iteratorBean = (IteratorBean) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("iteratorBean"); if (iteratorBean == null) { iteratorBean = new IteratorBean(iterator); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put("iteratorBean", iteratorBean); } else { iteratorBean.setIterator(iterator); } int size = iteratorBean.getSize(); if (size == 1) { int pageNumber = 1; list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); String coding_scheme = ref.getCodingSchemeName(); if (coding_scheme.compareToIgnoreCase("NCI Metathesaurus") == 0) { String match_size = Integer.toString(size); ;// Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); // route to multiple_search_results.jsp return "search_results"; } request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", coding_scheme); request.getSession().setAttribute("version", version); Entity c = null; if (ref == null) { String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "message"; } else { c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(coding_scheme, null, null, ref.getConceptCode()); } } request.getSession().setAttribute("code", ref.getConceptCode()); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("new_search", Boolean.TRUE); request.setAttribute("algorithm", matchAlgorithm); coding_scheme = (String) DataUtils._localName2FormalNameHashMap .get(coding_scheme); String convertJSPString = HTTPUtils.convertJSPString(matchText); request.getSession() .setAttribute("matchText", convertJSPString); request.setAttribute("dictionary", coding_scheme); request.setAttribute("version", version); return "concept_details"; } else if (size > 0) { String match_size = Integer.toString(size); ;// Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); // route to multiple_search_results.jsp request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); _logger.debug("Start to render search_results ... "); return "search_results"; } } int minimumSearchStringLength = NCItBrowserProperties.getMinimumSearchStringLength(); if (ontologiesToSearchOn.size() == 0) { request.getSession().removeAttribute("vocabulary"); } else if (ontologiesToSearchOn.size() == 1) { String msg_scheme = (String) ontologiesToSearchOn.get(0); request.getSession().setAttribute("vocabulary", msg_scheme); } else { request.getSession().removeAttribute("vocabulary"); } String message = Constants.ERROR_NO_MATCH_FOUND; if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) { message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS; } else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0 && matchText.length() < minimumSearchStringLength) { message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY; } hide_ontology_list = "false"; /* * if (initial_search == null) { hide_ontology_list = "true"; } */ request.getSession().setAttribute("hide_ontology_list", hide_ontology_list); request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); request.getSession().setAttribute("multiple_search_no_match_error", "true"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; }
public String multipleSearchAction() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String scheme = (String) request.getParameter("scheme"); String version = (String) request.getParameter("version"); String navigation_type = request.getParameter("nav_type"); if (navigation_type == null || navigation_type.equals("null")) { navigation_type = "terminologies"; } // Called from license.jsp LicenseBean licenseBean = (LicenseBean) request.getSession().getAttribute("licenseBean"); if (scheme != null && version != null) { if (licenseBean == null) { licenseBean = new LicenseBean(); } licenseBean.addLicenseAgreement(scheme); request.getSession().setAttribute("licenseBean", licenseBean); } String matchText = (String) request.getParameter("matchText"); if (matchText != null) { matchText = matchText.trim(); request.getSession().setAttribute("matchText", matchText); } else { matchText = (String) request.getSession().getAttribute("matchText"); } String multiple_search_error = (String) request.getSession().getAttribute( "multiple_search_no_match_error"); request.getSession().removeAttribute("multiple_search_no_match_error"); String matchAlgorithm = (String) request.getParameter("algorithm"); request.getSession().setAttribute("algorithm", matchAlgorithm); String searchTarget = (String) request.getParameter("searchTarget"); request.getSession().setAttribute("searchTarget", searchTarget); String initial_search = (String) request.getParameter("initial_search"); String[] ontology_list = null; //if (navigation_type == null || navigation_type.compareTo("terminologies") == 0) { ontology_list = request.getParameterValues("ontology_list"); //} List list = new ArrayList<String>(); String ontologiesToSearchOnStr = null; String ontology_list_str = null; List<String> ontologiesToSearchOn = null; int knt = 0; // process mappings if (initial_search != null) { // from home page if (multiple_search_error != null) { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = (String) request.getSession().getAttribute( "ontologiesToSearchOn"); if (ontologiesToSearchOnStr != null) { Vector ontologies_to_search_on = DataUtils.parseData(ontologiesToSearchOnStr); ontology_list = new String[ontologies_to_search_on.size()]; knt = ontologies_to_search_on.size(); for (int k = 0; k < ontologies_to_search_on.size(); k++) { String s = (String) ontologies_to_search_on.elementAt(k); ontology_list[k] = s; ontologiesToSearchOn.add(s); } } } if (ontology_list == null || ontology_list.length == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().removeAttribute("ontologiesToSearchOn"); // String defaultOntologiesToSearchOnStr = // ontologiesToSearchOnStr; request.getSession().setAttribute( "defaultOntologiesToSearchOnStr", "|"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } else { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = "|"; for (int i = 0; i < ontology_list.length; ++i) { list.add(ontology_list[i]); ontologiesToSearchOn.add(ontology_list[i]); ontologiesToSearchOnStr = ontologiesToSearchOnStr + ontology_list[i] + "|"; } if (ontology_list_str == null) { ontology_list_str = ""; for (int i = 0; i < ontology_list.length; ++i) { ontology_list_str = ontology_list_str + ontology_list[i]; if (i < ontology_list.length - 1) { ontology_list_str = ontology_list_str + "|"; } } } request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); } } else { ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = (String) request.getSession().getAttribute( "ontologiesToSearchOn"); if (ontologiesToSearchOnStr != null) { Vector ontologies_to_search_on = DataUtils.parseData(ontologiesToSearchOnStr); ontology_list = new String[ontologies_to_search_on.size()]; knt = ontologies_to_search_on.size(); for (int k = 0; k < ontologies_to_search_on.size(); k++) { String s = (String) ontologies_to_search_on.elementAt(k); ontology_list[k] = s; ontologiesToSearchOn.add(s); } } } String hide_ontology_list = "false"; // [#19965] Error message is not displayed when Search Criteria is not // proivided if (matchText == null || matchText.length() == 0) { String message = Constants.ERROR_NO_SEARCH_STRING_ENTERED; if (initial_search == null) { hide_ontology_list = "true"; } request.getSession().setAttribute("hide_ontology_list", hide_ontology_list); request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } // KLO, 012610 else if (searchTarget.compareTo("relationships") == 0 && matchAlgorithm.compareTo("contains") == 0) { String text = matchText.trim(); if (text.length() < NCItBrowserProperties .getMinimumSearchStringLength()) { String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING; request.getSession().setAttribute("warning", msg); request.getSession().setAttribute("message", msg); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } } boolean ranking = true; String source = (String) request.getParameter("source"); if (source == null) { source = "ALL"; } if (NCItBrowserProperties._debugOn) { try { _logger.debug(Utils.SEPARATOR); _logger.debug("* criteria: " + matchText); _logger.debug("* source: " + source); _logger.debug("* ranking: " + ranking); _logger.debug("* ontology_list: "); for (int i = 0; i < ontology_list.length; ++i) { _logger.debug(" " + i + ") " + ontology_list[i]); } } catch (Exception e) { } } if (ontology_list == null) { ontology_list_str = (String) request.getParameter("ontology_list_str"); // from // multiple_search_results // (hidden // variable) if (ontology_list_str != null) { ontology_list = getSelectedVocabularies(ontology_list_str); } } else { knt = ontology_list.length; if (knt == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("hide_ontology_list", "true"); request.getSession().removeAttribute("ontologiesToSearchOn"); // String defaultOntologiesToSearchOnStr = // ontologiesToSearchOnStr; request.getSession().setAttribute( "defaultOntologiesToSearchOnStr", "|"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } } Vector schemes = new Vector(); Vector versions = new Vector(); ontologiesToSearchOn = new ArrayList<String>(); ontologiesToSearchOnStr = "|"; for (int i = 0; i < ontology_list.length; ++i) { list.add(ontology_list[i]); ontologiesToSearchOn.add(ontology_list[i]); ontologiesToSearchOnStr = ontologiesToSearchOnStr + ontology_list[i] + "|"; } if (ontology_list_str == null) { ontology_list_str = ""; for (int i = 0; i < ontology_list.length; ++i) { ontology_list_str = ontology_list_str + ontology_list[i]; if (i < ontology_list.length - 1) { ontology_list_str = ontology_list_str + "|"; } } } scheme = null; version = null; String t = ""; if (ontologiesToSearchOn.size() == 0) { String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary."; request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().removeAttribute("ontologiesToSearchOn"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; } else { request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); // [#25270] Set "all but NCIm selected" as the default for the TB // home page. String defaultOntologiesToSearchOnStr = ontologiesToSearchOnStr; request.getSession().setAttribute("defaultOntologiesToSearchOnStr", defaultOntologiesToSearchOnStr); for (int k = 0; k < ontologiesToSearchOn.size(); k++) { String key = (String) list.get(k); if (key != null) { scheme = DataUtils.key2CodingSchemeName(key); version = DataUtils.key2CodingSchemeVersion(key); if (scheme != null) { schemes.add(scheme); // to be modified (handling of versions) versions.add(version); t = t + scheme + " (" + version + ")" + "\n"; boolean isLicensed = LicenseBean.isLicensed(scheme, version); if (licenseBean == null) { licenseBean = new LicenseBean(); request.getSession().setAttribute("licenseBean", licenseBean); } boolean accepted = licenseBean.licenseAgreementAccepted(scheme); if (isLicensed && !accepted) { request.getSession().setAttribute("matchText", matchText); request.setAttribute("searchTarget", searchTarget); request.setAttribute("algorithm", matchAlgorithm); request.setAttribute("ontology_list_str", ontology_list_str); request.setAttribute("scheme", scheme); request.setAttribute("version", version); return "license"; } } else { _logger.warn("Unable to identify " + key); } } } } String max_str = null; int maxToReturn = -1;// 1000; try { max_str = NCItBrowserProperties .getProperty(NCItBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { // Do nothing } boolean designationOnly = false; boolean excludeDesignation = true; ResolvedConceptReferencesIterator iterator = null; if (searchTarget.compareTo("names") == 0) { long ms = System.currentTimeMillis(); long delay = 0; _logger.debug("Calling SearchUtils().searchByName " + matchText); ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByName(schemes, versions, matchText, source, matchAlgorithm, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } delay = System.currentTimeMillis() - ms; _logger.debug("searchByName delay (millisec.): " + delay); } else if (searchTarget.compareTo("properties") == 0) { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByProperties(schemes, versions, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } else if (searchTarget.compareTo("relationships") == 0) { designationOnly = true; ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils().searchByAssociations(schemes, versions, matchText, source, matchAlgorithm, designationOnly, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } request.getSession().setAttribute("vocabulary", scheme); request.getSession().setAttribute("searchTarget", searchTarget); request.getSession().setAttribute("algorithm", matchAlgorithm); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); if (iterator != null) { IteratorBean iteratorBean = (IteratorBean) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("iteratorBean"); if (iteratorBean == null) { iteratorBean = new IteratorBean(iterator); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put("iteratorBean", iteratorBean); } else { iteratorBean.setIterator(iterator); } int size = iteratorBean.getSize(); if (size == 1) { int pageNumber = 1; list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); String coding_scheme = ref.getCodingSchemeName(); String ref_version = ref.getCodingSchemeVersion(); if (coding_scheme.compareToIgnoreCase("NCI Metathesaurus") == 0) { String match_size = Integer.toString(size); ;// Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); // route to multiple_search_results.jsp return "search_results"; } request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", coding_scheme); request.getSession().setAttribute("version", ref_version); Entity c = null; if (ref == null) { String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "message"; } else { c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(coding_scheme, null, null, ref.getConceptCode()); } } request.getSession().setAttribute("code", ref.getConceptCode()); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("new_search", Boolean.TRUE); request.setAttribute("algorithm", matchAlgorithm); coding_scheme = (String) DataUtils._localName2FormalNameHashMap .get(coding_scheme); String convertJSPString = HTTPUtils.convertJSPString(matchText); request.getSession() .setAttribute("matchText", convertJSPString); request.setAttribute("dictionary", coding_scheme); request.setAttribute("version", ref_version); return "concept_details"; } else if (size > 0) { String match_size = Integer.toString(size); ;// Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); // route to multiple_search_results.jsp request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); _logger.debug("Start to render search_results ... "); return "search_results"; } } int minimumSearchStringLength = NCItBrowserProperties.getMinimumSearchStringLength(); if (ontologiesToSearchOn.size() == 0) { request.getSession().removeAttribute("vocabulary"); } else if (ontologiesToSearchOn.size() == 1) { String msg_scheme = (String) ontologiesToSearchOn.get(0); request.getSession().setAttribute("vocabulary", msg_scheme); } else { request.getSession().removeAttribute("vocabulary"); } String message = Constants.ERROR_NO_MATCH_FOUND; if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) { message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS; } else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0 && matchText.length() < minimumSearchStringLength) { message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY; } hide_ontology_list = "false"; /* * if (initial_search == null) { hide_ontology_list = "true"; } */ request.getSession().setAttribute("hide_ontology_list", hide_ontology_list); request.getSession().setAttribute("warning", message); request.getSession().setAttribute("message", message); request.getSession().setAttribute("ontologiesToSearchOn", ontologiesToSearchOnStr); request.getSession().setAttribute("multiple_search_no_match_error", "true"); request.getSession().setAttribute("matchText", HTTPUtils.convertJSPString(matchText)); return "multiple_search"; }
diff --git a/proxy/src/main/java/org/jboss/forge/proxy/ClassLoaderAdapterCallback.java b/proxy/src/main/java/org/jboss/forge/proxy/ClassLoaderAdapterCallback.java index 5a2619363..baa9406b6 100644 --- a/proxy/src/main/java/org/jboss/forge/proxy/ClassLoaderAdapterCallback.java +++ b/proxy/src/main/java/org/jboss/forge/proxy/ClassLoaderAdapterCallback.java @@ -1,447 +1,463 @@ package org.jboss.forge.proxy; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import javassist.util.proxy.MethodFilter; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyFactory; import javassist.util.proxy.ProxyObject; import org.jboss.forge.container.exception.ContainerException; import org.jboss.forge.container.util.ClassLoaders; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> */ public class ClassLoaderAdapterCallback implements MethodHandler { private static final ClassLoader JAVASSIST_LOADER = ProxyObject.class.getClassLoader(); private final Object delegate; private final ClassLoader callingLoader; private final ClassLoader delegateLoader; private final Object unwrappedDelegate; private final Class<?> unwrappedDelegateType; private final ClassLoader unwrappedDelegateLoader; public ClassLoaderAdapterCallback(ClassLoader callingLoader, ClassLoader delegateLoader, Object delegate) { this.callingLoader = callingLoader; this.delegateLoader = delegateLoader; this.delegate = delegate; unwrappedDelegate = Proxies.unwrap(delegate); unwrappedDelegateType = Proxies.unwrapProxyTypes(unwrappedDelegate.getClass(), callingLoader, delegateLoader, unwrappedDelegate.getClass().getClassLoader()); unwrappedDelegateLoader = unwrappedDelegateType.getClassLoader(); } @Override public Object invoke(final Object obj, final Method thisMethod, final Method proceed, final Object[] args) throws Throwable { return ClassLoaders.executeIn(delegateLoader, new Callable<Object>() { @Override public Object call() throws Exception { try { try { if (thisMethod.getDeclaringClass().equals(callingLoader.loadClass(ForgeProxy.class.getName()))) { return delegate; } } catch (Exception e) { } Method delegateMethod = getDelegateMethod(thisMethod); List<Object> parameterValues = convertParameterValues(args, delegateMethod); AccessibleObject.setAccessible(new AccessibleObject[] { delegateMethod }, true); Object result = delegateMethod.invoke(delegate, parameterValues.toArray()); return enhanceResult(thisMethod, result); } catch (Throwable e) { throw new ContainerException( "Could not invoke proxy method [" + delegate.getClass().getName() + "." + thisMethod.getName() + "()] in ClassLoader [" + delegateLoader + "]", e); } } private Method getDelegateMethod(final Method proxy) throws ClassNotFoundException, NoSuchMethodException { Method delegateMethod = null; try { List<Class<?>> parameterTypes = convertParameterTypes(proxy); delegateMethod = delegate.getClass().getMethod(proxy.getName(), parameterTypes.toArray(new Class<?>[parameterTypes.size()])); } catch (ClassNotFoundException e) { method: for (Method m : delegate.getClass().getMethods()) { String methodName = proxy.getName(); String delegateMethodName = m.getName(); if (methodName.equals(delegateMethodName)) { Class<?>[] methodParameterTypes = proxy.getParameterTypes(); Class<?>[] delegateParameterTypes = m.getParameterTypes(); if (methodParameterTypes.length == delegateParameterTypes.length) { for (int i = 0; i < methodParameterTypes.length; i++) { Class<?> methodType = methodParameterTypes[i]; Class<?> delegateType = delegateParameterTypes[i]; if (!methodType.getName().equals(delegateType.getName())) { continue method; } } delegateMethod = m; break; } } } if (delegateMethod == null) throw e; } return delegateMethod; } }); } private Object enhanceResult(final Method method, Object result) { if (result != null) { Object unwrappedResult = Proxies.unwrap(result); Class<?> unwrappedResultType = unwrappedResult.getClass(); ClassLoader resultInstanceLoader = delegateLoader; if (!ClassLoaders.containsClass(delegateLoader, unwrappedResultType)) { resultInstanceLoader = Proxies.unwrapProxyTypes(unwrappedResultType, callingLoader, delegateLoader, unwrappedResultType.getClassLoader()).getClassLoader(); } Class<?> returnType = method.getReturnType(); if (returnTypeNeedsEnhancement(returnType, result, unwrappedResultType)) { Class<?>[] resultHierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(result.getClass(), callingLoader, delegateLoader, resultInstanceLoader)); Class<?>[] returnTypeHierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(returnType, callingLoader, delegateLoader, resultInstanceLoader)); if (!Modifier.isFinal(returnType.getModifiers())) { if (Object.class.equals(returnType) && !Object.class.equals(result)) { result = enhance(callingLoader, resultInstanceLoader, method, result, resultHierarchy); } else { if (returnTypeHierarchy.length == 0) { returnTypeHierarchy = new Class[] { returnType }; } result = enhance(callingLoader, resultInstanceLoader, method, result, mergeHierarchies(returnTypeHierarchy, resultHierarchy)); } } else { result = enhance(callingLoader, resultInstanceLoader, method, returnTypeHierarchy); } } } return result; } @SuppressWarnings("unchecked") private Class<?>[] mergeHierarchies(Class<?>[] left, Class<?>[] right) { for (Class<?> type : right) { boolean found = false; for (Class<?> existing : left) { if (type.equals(existing)) { found = true; break; } } if (!found && type.isInterface()) left = Arrays.append(left, type); } return left; } private boolean returnTypeNeedsEnhancement(Class<?> methodReturnType, Object returnValue, Class<?> unwrappedReturnValueType) { if (unwrappedReturnValueType.getName().contains("java.lang") || unwrappedReturnValueType.isPrimitive()) { return false; } else if (!Object.class.equals(methodReturnType) && (methodReturnType.getName().startsWith("java.lang") || methodReturnType.isPrimitive())) { return false; } if (unwrappedReturnValueType.getClassLoader() != null && !unwrappedReturnValueType.getClassLoader().equals(callingLoader)) { if (ClassLoaders.containsClass(callingLoader, unwrappedReturnValueType) && ClassLoaders.containsClass(callingLoader, methodReturnType)) { return false; } } return true; } private List<Object> convertParameterValues(final Object[] args, Method delegateMethod) { List<Object> parameterValues = new ArrayList<Object>(); for (int i = 0; i < delegateMethod.getParameterTypes().length; i++) { final Class<?> delegateParameterType = delegateMethod.getParameterTypes()[i]; final Object parameterValue = args[i]; if (parameterValue == null) parameterValues.add(null); else { Object unwrappedValue = Proxies.unwrap(parameterValue); Class<?> unwrappedValueType = Proxies.unwrapProxyTypes(unwrappedValue.getClass(), delegateMethod .getDeclaringClass().getClassLoader(), callingLoader, delegateLoader, unwrappedValue.getClass() .getClassLoader()); ClassLoader valueDelegateLoader = delegateLoader; ClassLoader methodLoader = delegateMethod.getDeclaringClass().getClassLoader(); if (methodLoader != null && ClassLoaders.containsClass(methodLoader, unwrappedValueType)) { valueDelegateLoader = methodLoader; } ClassLoader valueCallingLoader = callingLoader; if (!ClassLoaders.containsClass(callingLoader, unwrappedValueType)) { valueCallingLoader = unwrappedValueType.getClassLoader(); } // If it is a class, use the delegateLoader loaded version if (parameterValue instanceof Class<?>) { Class<?> paramClassValue = (Class<?>) parameterValue; Class<?> loadedClass; try { loadedClass = delegateLoader.loadClass(paramClassValue.getName()); } catch (ClassNotFoundException e) { // Oh oh, there is no class with this type in the target. // Trying with delegate ClassLoader; try { loadedClass = unwrappedDelegateLoader.loadClass(paramClassValue.getName()); } catch (ClassNotFoundException cnfe) { // No way, here is the original class and god bless you :) loadedClass = paramClassValue; } } parameterValues.add(loadedClass); } else if (delegateParameterType.isPrimitive() || parameterValue == null) { parameterValues.add(parameterValue); } else { final Class<?> parameterType = parameterValue.getClass(); if (!delegateParameterType.isAssignableFrom(parameterType)) { Class<?>[] compatibleClassHierarchy = ProxyTypeInspector.getCompatibleClassHierarchy( valueDelegateLoader, unwrappedValueType); if (compatibleClassHierarchy.length == 0) compatibleClassHierarchy = new Class[] { delegateParameterType }; Object delegateParameterValue = enhance(valueDelegateLoader, valueCallingLoader, parameterValue, compatibleClassHierarchy); parameterValues.add(delegateParameterValue); } else { parameterValues.add(Proxies.unwrap(parameterValue)); } } } } return parameterValues; } private List<Class<?>> convertParameterTypes(final Method method) throws ClassNotFoundException { List<Class<?>> parameterTypes = new ArrayList<Class<?>>(); for (int i = 0; i < method.getParameterTypes().length; i++) { Class<?> parameterType = method.getParameterTypes()[i]; if (parameterType.isPrimitive()) { parameterTypes.add(parameterType); } else { Class<?> delegateParameterType = delegateLoader.loadClass(parameterType.getName()); parameterTypes.add(delegateParameterType); } } return parameterTypes; } public static <T> T enhance(final ClassLoader callingLoader, final ClassLoader delegateLoader, final Object delegate, final Class<?>... types) { return enhance(callingLoader, delegateLoader, null, delegate, types); } @SuppressWarnings("unchecked") private static <T> T enhance(final ClassLoader callingLoader, final ClassLoader delegateLoader, final Method sourceMethod, final Object delegate, final Class<?>... types) { // TODO consider removing option to set type hierarchy here. Instead it might just be // best to use type inspection of the given callingLoader ClassLoader to figure out the proper type. final Class<?> delegateType = delegate.getClass(); return ClassLoaders.executeIn(JAVASSIST_LOADER, new Callable<T>() { @Override public T call() throws Exception { Class<?>[] hierarchy = null; if (types == null || types.length == 0) { hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(delegateType, callingLoader, delegateLoader)); if (hierarchy == null || hierarchy.length == 0) throw new IllegalArgumentException("Must specify at least one non-final type to enhance for Object: " + delegate + " of type " + delegate.getClass()); } else hierarchy = Arrays.copy(types, new Class<?>[types.length]); MethodFilter filter = new MethodFilter() { @Override public boolean isHandled(Method method) { if (!method.getDeclaringClass().getName().contains("java.lang") || ("toString".equals(method.getName()) && method.getParameterTypes().length == 0)) return true; return false; } }; Object enhancedResult = null; ProxyFactory f = new ProxyFactory(); f.setUseCache(true); Class<?> first = hierarchy[0]; if (!first.isInterface()) { f.setSuperclass(Proxies.unwrapProxyTypes(first, callingLoader, delegateLoader)); hierarchy = Arrays.shiftLeft(hierarchy, new Class<?>[hierarchy.length - 1]); } int index = Arrays.indexOf(hierarchy, ProxyObject.class); if (index >= 0) { hierarchy = Arrays.removeElementAtIndex(hierarchy, index); } if (!Proxies.isProxyType(first) && !Arrays.contains(hierarchy, ForgeProxy.class)) hierarchy = Arrays.append(hierarchy, ForgeProxy.class); if (hierarchy.length > 0) f.setInterfaces(hierarchy); f.setFilter(filter); - Class<?> c = f.createClass(); + Class<?> c = null; + try + { + c = f.createClass(); + } + catch (Exception e) + { + try + { + // FIXME Why is this failing to proxy the type + c = f.createClass(); + } + catch (Exception e1) + { + throw e; + } + } try { enhancedResult = c.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } try { ((ProxyObject) enhancedResult) .setHandler(new ClassLoaderAdapterCallback(callingLoader, delegateLoader, delegate)); } catch (ClassCastException e) { Class<?>[] interfaces = enhancedResult.getClass().getInterfaces(); for (Class<?> javassistType : interfaces) { if (ProxyObject.class.getName().equals(javassistType.getName())) { String callbackClassName = ClassLoaderAdapterCallback.class.getName(); ClassLoader javassistLoader = javassistType.getClassLoader(); Constructor<?> callbackConstructor = javassistLoader.loadClass(callbackClassName) .getConstructors()[0]; Class<?> typeArgument = javassistLoader.loadClass(MethodHandler.class.getName()); Method setHandlerMethod = javassistType.getMethod("setHandler", typeArgument); setHandlerMethod.invoke(enhancedResult, callbackConstructor.newInstance(callingLoader, delegateLoader, delegate)); } } } return (T) enhancedResult; } }); } }
true
true
private static <T> T enhance(final ClassLoader callingLoader, final ClassLoader delegateLoader, final Method sourceMethod, final Object delegate, final Class<?>... types) { // TODO consider removing option to set type hierarchy here. Instead it might just be // best to use type inspection of the given callingLoader ClassLoader to figure out the proper type. final Class<?> delegateType = delegate.getClass(); return ClassLoaders.executeIn(JAVASSIST_LOADER, new Callable<T>() { @Override public T call() throws Exception { Class<?>[] hierarchy = null; if (types == null || types.length == 0) { hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(delegateType, callingLoader, delegateLoader)); if (hierarchy == null || hierarchy.length == 0) throw new IllegalArgumentException("Must specify at least one non-final type to enhance for Object: " + delegate + " of type " + delegate.getClass()); } else hierarchy = Arrays.copy(types, new Class<?>[types.length]); MethodFilter filter = new MethodFilter() { @Override public boolean isHandled(Method method) { if (!method.getDeclaringClass().getName().contains("java.lang") || ("toString".equals(method.getName()) && method.getParameterTypes().length == 0)) return true; return false; } }; Object enhancedResult = null; ProxyFactory f = new ProxyFactory(); f.setUseCache(true); Class<?> first = hierarchy[0]; if (!first.isInterface()) { f.setSuperclass(Proxies.unwrapProxyTypes(first, callingLoader, delegateLoader)); hierarchy = Arrays.shiftLeft(hierarchy, new Class<?>[hierarchy.length - 1]); } int index = Arrays.indexOf(hierarchy, ProxyObject.class); if (index >= 0) { hierarchy = Arrays.removeElementAtIndex(hierarchy, index); } if (!Proxies.isProxyType(first) && !Arrays.contains(hierarchy, ForgeProxy.class)) hierarchy = Arrays.append(hierarchy, ForgeProxy.class); if (hierarchy.length > 0) f.setInterfaces(hierarchy); f.setFilter(filter); Class<?> c = f.createClass(); try { enhancedResult = c.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } try { ((ProxyObject) enhancedResult) .setHandler(new ClassLoaderAdapterCallback(callingLoader, delegateLoader, delegate)); } catch (ClassCastException e) { Class<?>[] interfaces = enhancedResult.getClass().getInterfaces(); for (Class<?> javassistType : interfaces) { if (ProxyObject.class.getName().equals(javassistType.getName())) { String callbackClassName = ClassLoaderAdapterCallback.class.getName(); ClassLoader javassistLoader = javassistType.getClassLoader(); Constructor<?> callbackConstructor = javassistLoader.loadClass(callbackClassName) .getConstructors()[0]; Class<?> typeArgument = javassistLoader.loadClass(MethodHandler.class.getName()); Method setHandlerMethod = javassistType.getMethod("setHandler", typeArgument); setHandlerMethod.invoke(enhancedResult, callbackConstructor.newInstance(callingLoader, delegateLoader, delegate)); } } } return (T) enhancedResult; } }); }
private static <T> T enhance(final ClassLoader callingLoader, final ClassLoader delegateLoader, final Method sourceMethod, final Object delegate, final Class<?>... types) { // TODO consider removing option to set type hierarchy here. Instead it might just be // best to use type inspection of the given callingLoader ClassLoader to figure out the proper type. final Class<?> delegateType = delegate.getClass(); return ClassLoaders.executeIn(JAVASSIST_LOADER, new Callable<T>() { @Override public T call() throws Exception { Class<?>[] hierarchy = null; if (types == null || types.length == 0) { hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(delegateType, callingLoader, delegateLoader)); if (hierarchy == null || hierarchy.length == 0) throw new IllegalArgumentException("Must specify at least one non-final type to enhance for Object: " + delegate + " of type " + delegate.getClass()); } else hierarchy = Arrays.copy(types, new Class<?>[types.length]); MethodFilter filter = new MethodFilter() { @Override public boolean isHandled(Method method) { if (!method.getDeclaringClass().getName().contains("java.lang") || ("toString".equals(method.getName()) && method.getParameterTypes().length == 0)) return true; return false; } }; Object enhancedResult = null; ProxyFactory f = new ProxyFactory(); f.setUseCache(true); Class<?> first = hierarchy[0]; if (!first.isInterface()) { f.setSuperclass(Proxies.unwrapProxyTypes(first, callingLoader, delegateLoader)); hierarchy = Arrays.shiftLeft(hierarchy, new Class<?>[hierarchy.length - 1]); } int index = Arrays.indexOf(hierarchy, ProxyObject.class); if (index >= 0) { hierarchy = Arrays.removeElementAtIndex(hierarchy, index); } if (!Proxies.isProxyType(first) && !Arrays.contains(hierarchy, ForgeProxy.class)) hierarchy = Arrays.append(hierarchy, ForgeProxy.class); if (hierarchy.length > 0) f.setInterfaces(hierarchy); f.setFilter(filter); Class<?> c = null; try { c = f.createClass(); } catch (Exception e) { try { // FIXME Why is this failing to proxy the type c = f.createClass(); } catch (Exception e1) { throw e; } } try { enhancedResult = c.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } try { ((ProxyObject) enhancedResult) .setHandler(new ClassLoaderAdapterCallback(callingLoader, delegateLoader, delegate)); } catch (ClassCastException e) { Class<?>[] interfaces = enhancedResult.getClass().getInterfaces(); for (Class<?> javassistType : interfaces) { if (ProxyObject.class.getName().equals(javassistType.getName())) { String callbackClassName = ClassLoaderAdapterCallback.class.getName(); ClassLoader javassistLoader = javassistType.getClassLoader(); Constructor<?> callbackConstructor = javassistLoader.loadClass(callbackClassName) .getConstructors()[0]; Class<?> typeArgument = javassistLoader.loadClass(MethodHandler.class.getName()); Method setHandlerMethod = javassistType.getMethod("setHandler", typeArgument); setHandlerMethod.invoke(enhancedResult, callbackConstructor.newInstance(callingLoader, delegateLoader, delegate)); } } } return (T) enhancedResult; } }); }
diff --git a/trunk/src/webcamstudio/media/renderer/Capturer.java b/trunk/src/webcamstudio/media/renderer/Capturer.java index 0f6a3f4..8be5da7 100644 --- a/trunk/src/webcamstudio/media/renderer/Capturer.java +++ b/trunk/src/webcamstudio/media/renderer/Capturer.java @@ -1,169 +1,171 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package webcamstudio.media.renderer; import java.awt.image.BufferedImage; import java.io.DataInputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.logging.Level; import java.util.logging.Logger; import webcamstudio.mixers.Frame; import webcamstudio.streams.Stream; import webcamstudio.util.Tools; /** * * @author patrick */ public class Capturer { private int vport = 0; private int aport = 0; private boolean stopMe = false; private Stream stream; private int audioBufferSize = 0; private int videoBufferSize = 0; private ServerSocket videoServer = null; private ServerSocket audioServer = null; private Frame frame = null; private BufferedImage lastImage = null; public Capturer(Stream s) { stream = s; audioBufferSize = (44100 * 2 * 2) / stream.getRate(); videoBufferSize = stream.getCaptureWidth() * stream.getCaptureHeight() * 4; frame = new Frame(stream.getID(), null, null); if (stream.hasAudio()) { try { audioServer = new ServerSocket(0); aport = audioServer.getLocalPort(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } if (stream.hasVideo()) { try { videoServer = new ServerSocket(0); vport = videoServer.getLocalPort(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Port used is Video:" + vport + "/Audio:" + aport); System.out.println("Size: " + stream.getCaptureWidth() + "X" + stream.getCaptureHeight()); Thread vCapture = new Thread(new Runnable() { @Override public void run() { Socket connection = null; try { connection = videoServer.accept(); System.out.println(stream.getName() + " video accepted..."); DataInputStream din = new DataInputStream(connection.getInputStream()); long mark = 0; // long count = 0; while (!stopMe) { try { // count++; mark = System.currentTimeMillis(); + videoBufferSize = stream.getCaptureWidth() * stream.getCaptureHeight() * 4; byte[] vbuffer = new byte[videoBufferSize]; int[] rgb = new int[videoBufferSize / 4]; BufferedImage image = new BufferedImage(stream.getCaptureWidth(), stream.getCaptureHeight(), BufferedImage.TYPE_INT_ARGB); din.readFully(vbuffer); IntBuffer intData = ByteBuffer.wrap(vbuffer).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); intData.get(rgb); //Special Effects... - image.setRGB(0, 0, stream.getWidth(), stream.getHeight(), rgb, 0, stream.getWidth()); + image.setRGB(0, 0, stream.getCaptureWidth(), stream.getCaptureHeight(), rgb, 0, stream.getCaptureWidth()); lastImage = image; Tools.wait(1000/stream.getRate(), mark); // if (count == stream.getRate()){ // System.out.println("Video Frame " + System.currentTimeMillis()); // count=0; // } } catch (IOException ioe) { stopMe = true; //ioe.printStackTrace(); } } din.close(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } }); vCapture.setPriority(Thread.MIN_PRIORITY); if (stream.hasVideo()) { vCapture.start(); } Thread aCapture = new Thread(new Runnable() { @Override public void run() { try { Socket connection = audioServer.accept(); System.out.println(stream.getName() + " audio accepted..."); DataInputStream din = new DataInputStream(connection.getInputStream()); long mark = 0; while (!stopMe) { try { mark=System.currentTimeMillis(); + audioBufferSize = (44100 * 2 * 2) / stream.getRate(); byte[] abuffer = new byte[audioBufferSize]; din.readFully(abuffer); frame = new Frame(stream.getID(), lastImage, abuffer); frame.setOutputFormat(stream.getX(), stream.getY(), stream.getWidth(), stream.getHeight(), stream.getOpacity(), stream.getVolume()); frame.setZOrder(stream.getZOrder()); Tools.wait(1000/stream.getRate(), mark); } catch (IOException ioe) { stopMe = true; //ioe.printStackTrace(); } } din.close(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } }); aCapture.setPriority(Thread.MIN_PRIORITY); if (stream.hasAudio()) { aCapture.start(); } } public void abort() { try { if (videoServer != null) { videoServer.close(); videoServer=null; } if (audioServer != null) { audioServer.close(); audioServer=null; } } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } public int getVideoPort() { return vport; } public int getAudioPort() { return aport; } public Frame getFrame() { return frame; } }
false
true
public Capturer(Stream s) { stream = s; audioBufferSize = (44100 * 2 * 2) / stream.getRate(); videoBufferSize = stream.getCaptureWidth() * stream.getCaptureHeight() * 4; frame = new Frame(stream.getID(), null, null); if (stream.hasAudio()) { try { audioServer = new ServerSocket(0); aport = audioServer.getLocalPort(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } if (stream.hasVideo()) { try { videoServer = new ServerSocket(0); vport = videoServer.getLocalPort(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Port used is Video:" + vport + "/Audio:" + aport); System.out.println("Size: " + stream.getCaptureWidth() + "X" + stream.getCaptureHeight()); Thread vCapture = new Thread(new Runnable() { @Override public void run() { Socket connection = null; try { connection = videoServer.accept(); System.out.println(stream.getName() + " video accepted..."); DataInputStream din = new DataInputStream(connection.getInputStream()); long mark = 0; // long count = 0; while (!stopMe) { try { // count++; mark = System.currentTimeMillis(); byte[] vbuffer = new byte[videoBufferSize]; int[] rgb = new int[videoBufferSize / 4]; BufferedImage image = new BufferedImage(stream.getCaptureWidth(), stream.getCaptureHeight(), BufferedImage.TYPE_INT_ARGB); din.readFully(vbuffer); IntBuffer intData = ByteBuffer.wrap(vbuffer).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); intData.get(rgb); //Special Effects... image.setRGB(0, 0, stream.getWidth(), stream.getHeight(), rgb, 0, stream.getWidth()); lastImage = image; Tools.wait(1000/stream.getRate(), mark); // if (count == stream.getRate()){ // System.out.println("Video Frame " + System.currentTimeMillis()); // count=0; // } } catch (IOException ioe) { stopMe = true; //ioe.printStackTrace(); } } din.close(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } }); vCapture.setPriority(Thread.MIN_PRIORITY); if (stream.hasVideo()) { vCapture.start(); } Thread aCapture = new Thread(new Runnable() { @Override public void run() { try { Socket connection = audioServer.accept(); System.out.println(stream.getName() + " audio accepted..."); DataInputStream din = new DataInputStream(connection.getInputStream()); long mark = 0; while (!stopMe) { try { mark=System.currentTimeMillis(); byte[] abuffer = new byte[audioBufferSize]; din.readFully(abuffer); frame = new Frame(stream.getID(), lastImage, abuffer); frame.setOutputFormat(stream.getX(), stream.getY(), stream.getWidth(), stream.getHeight(), stream.getOpacity(), stream.getVolume()); frame.setZOrder(stream.getZOrder()); Tools.wait(1000/stream.getRate(), mark); } catch (IOException ioe) { stopMe = true; //ioe.printStackTrace(); } } din.close(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } }); aCapture.setPriority(Thread.MIN_PRIORITY); if (stream.hasAudio()) { aCapture.start(); } }
public Capturer(Stream s) { stream = s; audioBufferSize = (44100 * 2 * 2) / stream.getRate(); videoBufferSize = stream.getCaptureWidth() * stream.getCaptureHeight() * 4; frame = new Frame(stream.getID(), null, null); if (stream.hasAudio()) { try { audioServer = new ServerSocket(0); aport = audioServer.getLocalPort(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } if (stream.hasVideo()) { try { videoServer = new ServerSocket(0); vport = videoServer.getLocalPort(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Port used is Video:" + vport + "/Audio:" + aport); System.out.println("Size: " + stream.getCaptureWidth() + "X" + stream.getCaptureHeight()); Thread vCapture = new Thread(new Runnable() { @Override public void run() { Socket connection = null; try { connection = videoServer.accept(); System.out.println(stream.getName() + " video accepted..."); DataInputStream din = new DataInputStream(connection.getInputStream()); long mark = 0; // long count = 0; while (!stopMe) { try { // count++; mark = System.currentTimeMillis(); videoBufferSize = stream.getCaptureWidth() * stream.getCaptureHeight() * 4; byte[] vbuffer = new byte[videoBufferSize]; int[] rgb = new int[videoBufferSize / 4]; BufferedImage image = new BufferedImage(stream.getCaptureWidth(), stream.getCaptureHeight(), BufferedImage.TYPE_INT_ARGB); din.readFully(vbuffer); IntBuffer intData = ByteBuffer.wrap(vbuffer).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); intData.get(rgb); //Special Effects... image.setRGB(0, 0, stream.getCaptureWidth(), stream.getCaptureHeight(), rgb, 0, stream.getCaptureWidth()); lastImage = image; Tools.wait(1000/stream.getRate(), mark); // if (count == stream.getRate()){ // System.out.println("Video Frame " + System.currentTimeMillis()); // count=0; // } } catch (IOException ioe) { stopMe = true; //ioe.printStackTrace(); } } din.close(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } }); vCapture.setPriority(Thread.MIN_PRIORITY); if (stream.hasVideo()) { vCapture.start(); } Thread aCapture = new Thread(new Runnable() { @Override public void run() { try { Socket connection = audioServer.accept(); System.out.println(stream.getName() + " audio accepted..."); DataInputStream din = new DataInputStream(connection.getInputStream()); long mark = 0; while (!stopMe) { try { mark=System.currentTimeMillis(); audioBufferSize = (44100 * 2 * 2) / stream.getRate(); byte[] abuffer = new byte[audioBufferSize]; din.readFully(abuffer); frame = new Frame(stream.getID(), lastImage, abuffer); frame.setOutputFormat(stream.getX(), stream.getY(), stream.getWidth(), stream.getHeight(), stream.getOpacity(), stream.getVolume()); frame.setZOrder(stream.getZOrder()); Tools.wait(1000/stream.getRate(), mark); } catch (IOException ioe) { stopMe = true; //ioe.printStackTrace(); } } din.close(); } catch (IOException ex) { Logger.getLogger(Capturer.class.getName()).log(Level.SEVERE, null, ex); } } }); aCapture.setPriority(Thread.MIN_PRIORITY); if (stream.hasAudio()) { aCapture.start(); } }
diff --git a/JavaSource/org/unitime/timetable/solver/TimetableDatabaseLoader.java b/JavaSource/org/unitime/timetable/solver/TimetableDatabaseLoader.java index 8bdad4c1..69e40ad2 100644 --- a/JavaSource/org/unitime/timetable/solver/TimetableDatabaseLoader.java +++ b/JavaSource/org/unitime/timetable/solver/TimetableDatabaseLoader.java @@ -1,3197 +1,3197 @@ /* * UniTime 3.2 (University Timetabling Application) * Copyright (C) 2008 - 2010, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * 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 org.unitime.timetable.solver; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; import net.sf.cpsolver.coursett.TimetableLoader; import net.sf.cpsolver.coursett.constraint.ClassLimitConstraint; import net.sf.cpsolver.coursett.constraint.DepartmentSpreadConstraint; import net.sf.cpsolver.coursett.constraint.DiscouragedRoomConstraint; import net.sf.cpsolver.coursett.constraint.GroupConstraint; import net.sf.cpsolver.coursett.constraint.InstructorConstraint; import net.sf.cpsolver.coursett.constraint.JenrlConstraint; import net.sf.cpsolver.coursett.constraint.MinimizeNumberOfUsedGroupsOfTime; import net.sf.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint; import net.sf.cpsolver.coursett.constraint.RoomConstraint; import net.sf.cpsolver.coursett.constraint.SpreadConstraint; import net.sf.cpsolver.coursett.model.Configuration; import net.sf.cpsolver.coursett.model.InitialSectioning; import net.sf.cpsolver.coursett.model.Lecture; import net.sf.cpsolver.coursett.model.Placement; import net.sf.cpsolver.coursett.model.RoomLocation; import net.sf.cpsolver.coursett.model.Student; import net.sf.cpsolver.coursett.model.TimeLocation; import net.sf.cpsolver.coursett.model.TimetableModel; import net.sf.cpsolver.coursett.preference.MinMaxPreferenceCombination; import net.sf.cpsolver.coursett.preference.PreferenceCombination; import net.sf.cpsolver.coursett.preference.SumPreferenceCombination; import net.sf.cpsolver.ifs.model.Constraint; import net.sf.cpsolver.ifs.util.DataProperties; import net.sf.cpsolver.ifs.util.Progress; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.FlushMode; import org.hibernate.Hibernate; import org.hibernate.LazyInitializationException; import org.hibernate.Query; import org.hibernate.Transaction; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.interfaces.RoomAvailabilityInterface; import org.unitime.timetable.interfaces.RoomAvailabilityInterface.TimeBlock; import org.unitime.timetable.model.AcademicClassification; import org.unitime.timetable.model.Assignment; import org.unitime.timetable.model.Building; import org.unitime.timetable.model.BuildingPref; import org.unitime.timetable.model.ClassInstructor; import org.unitime.timetable.model.Class_; import org.unitime.timetable.model.CourseOffering; import org.unitime.timetable.model.CourseReservation; import org.unitime.timetable.model.CurriculumReservation; import org.unitime.timetable.model.DatePattern; import org.unitime.timetable.model.Department; import org.unitime.timetable.model.DepartmentalInstructor; import org.unitime.timetable.model.DistributionObject; import org.unitime.timetable.model.DistributionPref; import org.unitime.timetable.model.ExactTimeMins; import org.unitime.timetable.model.InstrOfferingConfig; import org.unitime.timetable.model.InstructionalOffering; import org.unitime.timetable.model.Location; import org.unitime.timetable.model.PosMajor; import org.unitime.timetable.model.PreferenceLevel; import org.unitime.timetable.model.Reservation; import org.unitime.timetable.model.Room; import org.unitime.timetable.model.RoomFeature; import org.unitime.timetable.model.RoomFeaturePref; import org.unitime.timetable.model.RoomGroupPref; import org.unitime.timetable.model.RoomPref; import org.unitime.timetable.model.RoomSharingModel; import org.unitime.timetable.model.SchedulingSubpart; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.Solution; import org.unitime.timetable.model.SolverGroup; import org.unitime.timetable.model.TimePattern; import org.unitime.timetable.model.TimePatternModel; import org.unitime.timetable.model.TimePref; import org.unitime.timetable.model.comparators.ClassComparator; import org.unitime.timetable.model.dao.AssignmentDAO; import org.unitime.timetable.model.dao.LocationDAO; import org.unitime.timetable.model.dao.SessionDAO; import org.unitime.timetable.model.dao.SolutionDAO; import org.unitime.timetable.model.dao.SolverGroupDAO; import org.unitime.timetable.model.dao.TimetableManagerDAO; import org.unitime.timetable.solver.curricula.LastLikeStudentCourseDemands; import org.unitime.timetable.solver.curricula.StudentCourseDemands; import org.unitime.timetable.solver.curricula.StudentCourseDemands.WeightedCourseOffering; import org.unitime.timetable.solver.curricula.StudentCourseDemands.WeightedStudentId; import org.unitime.timetable.solver.remote.core.RemoteSolverServer; import org.unitime.timetable.util.Constants; import org.unitime.timetable.util.DateUtils; import org.unitime.timetable.util.RoomAvailability; /** * @author Tomas Muller */ public class TimetableDatabaseLoader extends TimetableLoader { private static Log sLog = LogFactory.getLog(TimetableDatabaseLoader.class); private Session iSession; private Long iSessionId; private Long[] iSolverGroupId; private String iSolverGroupIds; private String iDepartmentIds = null; private SolverGroup[] iSolverGroup; private Long[] iSolutionId; private Hashtable<Long, RoomConstraint> iRooms = new Hashtable<Long, RoomConstraint>(); private Hashtable<Object, InstructorConstraint> iInstructors = new Hashtable<Object, InstructorConstraint>(); private Hashtable<Long, Lecture> iLectures = new Hashtable<Long, Lecture>(); private Hashtable<Long, SchedulingSubpart> iSubparts = new Hashtable<Long, SchedulingSubpart>(); private Hashtable<Long, Student> iStudents = new Hashtable<Long, Student>(); private Hashtable<Long, String> iDeptNames = new Hashtable<Long, String>(); private Hashtable<Integer, List<TimePattern>> iPatterns = new Hashtable<Integer, List<TimePattern>>(); private Hashtable<Long, Class_> iClasses = new Hashtable<Long, Class_>(); private Set<DatePattern> iAllUsedDatePatterns = new HashSet<DatePattern>(); private Set<Class_> iAllClasses = null; private Hashtable<InstructionalOffering, List<Configuration>> iAltConfigurations = new Hashtable<InstructionalOffering, List<Configuration>>(); private Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> iOfferings = new Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig,Set<SchedulingSubpart>>>(); private Hashtable<CourseOffering, Set<Student>> iCourse2students = new Hashtable<CourseOffering, Set<Student>>(); private boolean iDeptBalancing = true; private boolean iSubjectBalancing = false; private boolean iMppAssignment = true; private boolean iInteractiveMode = false; private boolean iSpread = true; private boolean iAutoSameStudents = true; private boolean iLoadCommittedAssignments = false; private double iFewerSeatsDisouraged = 0.01; private double iFewerSeatsStronglyDisouraged = 0.02; private double iNormalizedPrefDecreaseFactor = TimePatternModel.sDefaultDecreaseFactor; private double iAlterTimePatternWeight = 0.0; private TimePatternModel iAlterTimePatternModel = (TimePatternModel)TimePattern.getDefaultRequiredTimeTable().getModel(); private boolean iWeakenTimePreferences = false; private Progress iProgress = null; private boolean iLoadStudentEnrlsFromSolution = false; private boolean iFixMinPerWeek = false; private boolean iAssignSingleton = true; private boolean iIgnoreRoomSharing = false; private String iAutoSameStudentsConstraint = "SAME_STUDENTS"; private String iInstructorFormat = null; private boolean iRoomAvailabilityTimeStampIsSet = false; private CommittedStudentConflictsMode iCommittedStudentConflictsMode = CommittedStudentConflictsMode.Load; private StudentCourseDemands iStudentCourseDemands = null; public static enum CommittedStudentConflictsMode { Ignore, Load, Compute}; public TimetableDatabaseLoader(TimetableModel model) { super(model); Progress.sTraceEnabled=false; iProgress = Progress.getInstance(model); iSessionId = model.getProperties().getPropertyLong("General.SessionId",(Long)null); iSolverGroupId = model.getProperties().getPropertyLongArry("General.SolverGroupId",null); iSolutionId = model.getProperties().getPropertyLongArry("General.SolutionId",null); iIgnoreRoomSharing = model.getProperties().getPropertyBoolean("General.IgnoreRoomSharing",iIgnoreRoomSharing); iSolverGroupIds = ""; if (iSolverGroupId!=null) { for (int i=0;i<iSolverGroupId.length;i++) { if (i>0) iSolverGroupIds+=","; iSolverGroupIds+=iSolverGroupId[i].toString(); } } iDeptBalancing = getModel().getProperties().getPropertyBoolean("General.DeptBalancing",iDeptBalancing); iSubjectBalancing = getModel().getProperties().getPropertyBoolean("General.SubjectBalancing",iSubjectBalancing); iSpread = getModel().getProperties().getPropertyBoolean("General.Spread",iSpread); iAutoSameStudents = getModel().getProperties().getPropertyBoolean("General.AutoSameStudents",iAutoSameStudents); iMppAssignment = getModel().getProperties().getPropertyBoolean("General.MPP",iMppAssignment); iInteractiveMode = getModel().getProperties().getPropertyBoolean("General.InteractiveMode", iInteractiveMode); iAssignSingleton = getModel().getProperties().getPropertyBoolean("General.AssignSingleton", iAssignSingleton); iFewerSeatsDisouraged = getModel().getProperties().getPropertyDouble("Global.FewerSeatsDisouraged", iFewerSeatsDisouraged); iFewerSeatsStronglyDisouraged = getModel().getProperties().getPropertyDouble("Global.FewerSeatsStronglyDisouraged", iFewerSeatsStronglyDisouraged); iNormalizedPrefDecreaseFactor = getModel().getProperties().getPropertyDouble("General.NormalizedPrefDecreaseFactor", iNormalizedPrefDecreaseFactor); iLoadStudentEnrlsFromSolution = getModel().getProperties().getPropertyBoolean("Global.LoadStudentEnrlsFromSolution", iLoadStudentEnrlsFromSolution); iFixMinPerWeek = getModel().getProperties().getPropertyBoolean("Global.FixMinPerWeek", iFixMinPerWeek); iAlterTimePatternWeight = getModel().getProperties().getPropertyDouble("TimePreferences.Weight", iAlterTimePatternWeight); iAlterTimePatternModel.setPreferences(getModel().getProperties().getProperty("TimePreferences.Pref", null)); iWeakenTimePreferences = getModel().getProperties().getPropertyBoolean("TimePreferences.Weaken", iWeakenTimePreferences); iAutoSameStudentsConstraint = getModel().getProperties().getProperty("General.AutoSameStudentsConstraint",iAutoSameStudentsConstraint); iInstructorFormat = getModel().getProperties().getProperty("General.InstructorFormat", DepartmentalInstructor.sNameFormatLastFist); try { String studentCourseDemandsClassName = getModel().getProperties().getProperty("Curriculum.StudentCourseDemadsClass", LastLikeStudentCourseDemands.class.getName()); if (studentCourseDemandsClassName.indexOf(' ') >= 0) studentCourseDemandsClassName = studentCourseDemandsClassName.replace(" ", ""); if (studentCourseDemandsClassName.indexOf('.') < 0) studentCourseDemandsClassName = "org.unitime.timetable.solver.curricula." + studentCourseDemandsClassName; Class studentCourseDemandsClass = Class.forName(studentCourseDemandsClassName); iStudentCourseDemands = (StudentCourseDemands)studentCourseDemandsClass.getConstructor(DataProperties.class).newInstance(getModel().getProperties()); } catch (Exception e) { iProgress.message(msglevel("badStudentCourseDemands", Progress.MSGLEVEL_WARN), "Failed to load custom student course demands class, using last-like course demands instead.",e); iStudentCourseDemands = new LastLikeStudentCourseDemands(getModel().getProperties()); } getModel().getProperties().setProperty("General.SaveStudentEnrollments", iStudentCourseDemands.isMakingUpStudents() ? "false" : "true"); iCommittedStudentConflictsMode = CommittedStudentConflictsMode.valueOf(getModel().getProperties().getProperty("General.CommittedStudentConflicts", iCommittedStudentConflictsMode.name())); iLoadCommittedAssignments = getModel().getProperties().getPropertyBoolean("General.LoadCommittedAssignments", iLoadCommittedAssignments); if (iCommittedStudentConflictsMode == CommittedStudentConflictsMode.Load && iStudentCourseDemands.isMakingUpStudents()) { iCommittedStudentConflictsMode = CommittedStudentConflictsMode.Compute; getModel().getProperties().setProperty("General.CommittedStudentConflicts", iCommittedStudentConflictsMode.name()); } if (iLoadStudentEnrlsFromSolution && iStudentCourseDemands.isMakingUpStudents()) { iLoadStudentEnrlsFromSolution = false; getModel().getProperties().setProperty("Global.LoadStudentEnrlsFromSolution", "false"); } } public int msglevel(String type, int defaultLevel) { String level = ApplicationProperties.getProperty("unitime.solver.log.level." + type); if (level == null) return defaultLevel; if ("warn".equalsIgnoreCase(level)) return Progress.MSGLEVEL_WARN; if ("error".equalsIgnoreCase(level)) return Progress.MSGLEVEL_ERROR; if ("fatal".equalsIgnoreCase(level)) return Progress.MSGLEVEL_FATAL; if ("info".equalsIgnoreCase(level)) return Progress.MSGLEVEL_INFO; if ("debug".equalsIgnoreCase(level)) return Progress.MSGLEVEL_DEBUG; if ("trace".equalsIgnoreCase(level)) return Progress.MSGLEVEL_TRACE; return defaultLevel; } private String getClassLabel(Class_ clazz) { return "<A href='classDetail.do?cid="+clazz.getUniqueId()+"'>"+clazz.getClassLabel()+"</A>"; } private String getClassLabel(Lecture lecture) { return "<A href='classDetail.do?cid="+lecture.getClassId()+"'>"+lecture.getName()+"</A>"; } private String getOfferingLabel(InstructionalOffering offering) { return "<A href='instructionalOfferingDetail.do?io="+offering.getUniqueId()+"'>"+offering.getCourseName()+"</A>"; } private String getOfferingLabel(CourseOffering offering) { return "<A href='instructionalOfferingDetail.do?io="+offering.getInstructionalOffering().getUniqueId()+"'>"+offering.getCourseName()+"</A>"; } private String getSubpartLabel(SchedulingSubpart subpart) { String suffix = subpart.getSchedulingSubpartSuffix(); return "<A href='schedulingSubpartDetail.do?ssuid="+subpart.getUniqueId()+"'>"+subpart.getCourseName()+" "+subpart.getItypeDesc().trim()+(suffix==null || suffix.length()==0?"":" ("+suffix+")")+"</A>"; } private Hashtable iRoomPreferences = null; private PreferenceLevel getRoomPreference(Long deptId, Long locationId) { if (iRoomPreferences == null) { iRoomPreferences = new Hashtable(); for (int i=0;i<iSolverGroup.length;i++) { for (Iterator j=iSolverGroup[i].getDepartments().iterator();j.hasNext();) { Department department = (Department)j.next(); Hashtable roomPreferencesThisDept = new Hashtable(); iRoomPreferences.put(department.getUniqueId(),roomPreferencesThisDept); for (Iterator k=department.getPreferences(RoomPref.class).iterator();k.hasNext();) { RoomPref pref = (RoomPref)k.next(); roomPreferencesThisDept.put(pref.getRoom().getUniqueId(),pref.getPrefLevel()); } } } } Hashtable roomPreferencesThisDept = (Hashtable)iRoomPreferences.get(deptId); if (roomPreferencesThisDept==null) return null; return (PreferenceLevel)roomPreferencesThisDept.get(locationId); } public static List<RoomLocation> computeRoomLocations(Class_ clazz) { return computeRoomLocations(clazz, false, 0.01, 0.02); } public static List<RoomLocation> computeRoomLocations(Class_ clazz, boolean interactiveMode, double fewerSeatsDisouraged, double fewerSeatsStronglyDisouraged) { int minClassLimit = clazz.getExpectedCapacity().intValue(); int maxClassLimit = clazz.getMaxExpectedCapacity().intValue(); if (maxClassLimit<minClassLimit) maxClassLimit = minClassLimit; float room2limitRatio = clazz.getRoomRatio().floatValue(); int roomCapacity = (int)Math.ceil(minClassLimit<=0?room2limitRatio:room2limitRatio*minClassLimit); int discouragedCapacity = (int)Math.round((1.0-fewerSeatsStronglyDisouraged) * roomCapacity); int stronglyDiscouragedCapacity = (int)Math.round((1.0-fewerSeatsStronglyDisouraged) * roomCapacity); List<RoomLocation> roomLocations = new ArrayList<RoomLocation>(); boolean reqRoom = false; boolean reqBldg = false; boolean reqGroup = false; Set allRooms = clazz.getAvailableRooms(); Set groupPrefs = clazz.effectivePreferences(RoomGroupPref.class); Set roomPrefs = clazz.effectivePreferences(RoomPref.class); Set bldgPrefs = clazz.effectivePreferences(BuildingPref.class); Set featurePrefs = clazz.effectivePreferences(RoomFeaturePref.class); for (Iterator i1=allRooms.iterator();i1.hasNext();) { Location room = (Location)i1.next(); boolean add = true; PreferenceCombination pref = new SumPreferenceCombination(); // --- group preference ---------- PreferenceCombination groupPref = PreferenceCombination.getDefault(); for (Iterator i2=groupPrefs.iterator();i2.hasNext();) { RoomGroupPref p = (RoomGroupPref)i2.next(); if (p.getRoomGroup().getRooms().contains(room)) groupPref.addPreferenceProlog(p.getPrefLevel().getPrefProlog()); } if (groupPref.getPreferenceProlog().equals(PreferenceLevel.sProhibited)) { if (interactiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (reqGroup && !groupPref.getPreferenceProlog().equals(PreferenceLevel.sRequired)) { if (interactiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (!reqGroup && (groupPref.getPreferenceProlog().equals(PreferenceLevel.sRequired))) { reqGroup=true; if (interactiveMode) { for (RoomLocation r: roomLocations) { r.setPreference(r.getPreference()+100); } } else roomLocations.clear(); } if (!groupPref.getPreferenceProlog().equals(PreferenceLevel.sProhibited) && !groupPref.getPreferenceProlog().equals(PreferenceLevel.sRequired)) pref.addPreferenceProlog(groupPref.getPreferenceProlog()); // --- room preference ------------ String roomPref = null; PreferenceLevel roomPreference = null; for (Iterator k=clazz.getManagingDept().getPreferences(RoomPref.class).iterator();k.hasNext();) { RoomPref x = (RoomPref)k.next(); if (room.equals(x.getRoom())) roomPreference = x.getPrefLevel(); } if (roomPreference!=null) { roomPref = roomPreference.getPrefProlog(); if (PreferenceLevel.sProhibited.equals(roomPref)) { add=false; } if (PreferenceLevel.sStronglyDiscouraged.equals(roomPref)) { roomPref = PreferenceLevel.sProhibited; } } for (Iterator i2=roomPrefs.iterator();i2.hasNext();) { RoomPref p = (RoomPref)i2.next(); if (room.equals(p.getRoom())) { roomPref = p.getPrefLevel().getPrefProlog(); break; } } if (roomPref!=null && roomPref.equals(PreferenceLevel.sProhibited)) { if (interactiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (reqRoom && (roomPref==null || !roomPref.equals(PreferenceLevel.sRequired))) { if (interactiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (!reqRoom && (roomPref!=null && roomPref.equals(PreferenceLevel.sRequired))) { reqRoom=true; if (interactiveMode) { for (RoomLocation r: roomLocations) { r.setPreference(r.getPreference()+100); } } else roomLocations.clear(); } if (roomPref!=null && !roomPref.equals(PreferenceLevel.sProhibited) && !roomPref.equals(PreferenceLevel.sRequired)) pref.addPreferenceProlog(roomPref); // --- building preference ------------ Building bldg = (room instanceof Room ? ((Room)room).getBuilding() : null); String bldgPref = null; for (Iterator i2=bldgPrefs.iterator();i2.hasNext();) { BuildingPref p = (BuildingPref)i2.next(); if (bldg!=null && bldg.equals(p.getBuilding())) { bldgPref = p.getPrefLevel().getPrefProlog(); break; } } if (bldgPref!=null && bldgPref.equals(PreferenceLevel.sProhibited)) { if (interactiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (reqBldg && (bldgPref==null || !bldgPref.equals(PreferenceLevel.sRequired))) { if (interactiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (!reqBldg && (bldgPref!=null && bldgPref.equals(PreferenceLevel.sRequired))) { reqBldg = true; if (interactiveMode) { for (RoomLocation r: roomLocations) { r.setPreference(r.getPreference()+100); } } else roomLocations.clear(); } if (bldgPref!=null && !bldgPref.equals(PreferenceLevel.sProhibited) && !bldgPref.equals(PreferenceLevel.sRequired)) pref.addPreferenceProlog(bldgPref); // --- room features preference -------- boolean acceptableFeatures = true; PreferenceCombination featurePref = new MinMaxPreferenceCombination(); for (Iterator i2=featurePrefs.iterator();i2.hasNext();) { RoomFeaturePref roomFeaturePref = (RoomFeaturePref)i2.next(); RoomFeature feature = roomFeaturePref.getRoomFeature(); String p = roomFeaturePref.getPrefLevel().getPrefProlog(); boolean hasFeature = feature.getRooms().contains(room); if (p.equals(PreferenceLevel.sProhibited) && hasFeature) { acceptableFeatures=false; } if (p.equals(PreferenceLevel.sRequired) && !hasFeature) { acceptableFeatures=false; } if (p!=null && hasFeature && !p.equals(PreferenceLevel.sProhibited) && !p.equals(PreferenceLevel.sRequired)) featurePref.addPreferenceProlog(p); } pref.addPreferenceInt(featurePref.getPreferenceInt()); if (!acceptableFeatures) { if (interactiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } // --- room size ----------------- if (room.getCapacity().intValue()<stronglyDiscouragedCapacity) { if (interactiveMode) pref.addPreferenceInt(1000); else add=false; } else if (room.getCapacity().intValue()<discouragedCapacity) { pref.addPreferenceProlog(PreferenceLevel.sStronglyDiscouraged); } else if (room.getCapacity().intValue()<roomCapacity) { pref.addPreferenceProlog(PreferenceLevel.sDiscouraged); } int prefInt = pref.getPreferenceInt(); if (!add) continue; roomLocations.add( new RoomLocation( room.getUniqueId(), room.getLabel(), (bldg==null?null:bldg.getUniqueId()), prefInt, room.getCapacity().intValue(), room.getCoordinateX(), room.getCoordinateY(), (room.isIgnoreTooFar()==null?false:room.isIgnoreTooFar().booleanValue()), null)); } return roomLocations; } private Lecture loadClass(Class_ clazz, org.hibernate.Session hibSession) { List<TimeLocation> timeLocations = new ArrayList<TimeLocation>(); List<RoomLocation> roomLocations = new ArrayList<RoomLocation>(); iProgress.message(msglevel("loadingClass", Progress.MSGLEVEL_DEBUG), "loading class "+getClassLabel(clazz)); Department dept = clazz.getControllingDept(); iDeptNames.put(dept.getUniqueId(),dept.getShortLabel()); iProgress.trace("department: "+dept.getName()+" (id:"+dept.getUniqueId()+")"); int minClassLimit = clazz.getExpectedCapacity().intValue(); int maxClassLimit = clazz.getMaxExpectedCapacity().intValue(); if (maxClassLimit<minClassLimit) maxClassLimit = minClassLimit; float room2limitRatio = clazz.getRoomRatio().floatValue(); int roomCapacity = (int)Math.ceil(minClassLimit<=0?room2limitRatio:room2limitRatio*minClassLimit); iProgress.trace("class limit: ["+minClassLimit+","+maxClassLimit+"]"); iProgress.trace("room2limitRatio: "+room2limitRatio); iProgress.trace("room capacity: "+roomCapacity); int discouragedCapacity = (int)Math.round((1.0-iFewerSeatsDisouraged) * roomCapacity); iProgress.trace("discouraged capacity: "+discouragedCapacity); int stronglyDiscouragedCapacity = (int)Math.round((1.0-iFewerSeatsStronglyDisouraged) * roomCapacity); iProgress.trace("strongly discouraged capacity: "+stronglyDiscouragedCapacity); Set timePrefs = clazz.effectivePreferences(TimePref.class); if (timePrefs.isEmpty()) { if (clazz.getSchedulingSubpart().getMinutesPerWk().intValue()!=0) iProgress.message(msglevel("noTimePattern", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(clazz)+" has no time pattern selected (class not loaded). <i>If not changed, this class will be treated as Arrange "+Math.round(clazz.getSchedulingSubpart().getMinutesPerWk().intValue()/50.0)+" Hours.</i>"); return null; } Set patterns = new HashSet(); DatePattern datePattern = clazz.effectiveDatePattern(); if (datePattern==null) { iProgress.message(msglevel("noDatePattern", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(clazz)+" has no date pattern selected (class not loaded)."); return null; } iAllUsedDatePatterns.add(datePattern); int nrRooms = (clazz.getNbrRooms()==null?1:clazz.getNbrRooms().intValue()); Set groupPrefs = clazz.effectivePreferences(RoomGroupPref.class); Set roomPrefs = clazz.effectivePreferences(RoomPref.class); Set bldgPrefs = clazz.effectivePreferences(BuildingPref.class); Set featurePrefs = clazz.effectivePreferences(RoomFeaturePref.class); if (nrRooms>0) { boolean reqRoom = false; boolean reqBldg = false; boolean reqGroup = false; Set allRooms = clazz.getAvailableRooms(); for (Iterator i1=allRooms.iterator();i1.hasNext();) { Location room = (Location)i1.next(); iProgress.trace("checking room "+room.getLabel()+" ..."); boolean add=true; PreferenceCombination pref = new SumPreferenceCombination(); // --- group preference ---------- PreferenceCombination groupPref = PreferenceCombination.getDefault(); for (Iterator i2=groupPrefs.iterator();i2.hasNext();) { RoomGroupPref p = (RoomGroupPref)i2.next(); if (p.getRoomGroup().getRooms().contains(room)) groupPref.addPreferenceProlog(p.getPrefLevel().getPrefProlog()); } if (groupPref.getPreferenceProlog().equals(PreferenceLevel.sProhibited)) { iProgress.trace("group is prohibited :-("); if (iInteractiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (reqGroup && !groupPref.getPreferenceProlog().equals(PreferenceLevel.sRequired)) { iProgress.trace("building is not required :-("); if (iInteractiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (!reqGroup && (groupPref.getPreferenceProlog().equals(PreferenceLevel.sRequired))) { iProgress.trace("group is required, removing all previous rooms (they are not required)"); reqGroup=true; if (iInteractiveMode) { for (RoomLocation r: roomLocations) { r.setPreference(r.getPreference()+100); } } else roomLocations.clear(); } if (!groupPref.getPreferenceProlog().equals(PreferenceLevel.sProhibited) && !groupPref.getPreferenceProlog().equals(PreferenceLevel.sRequired)) pref.addPreferenceProlog(groupPref.getPreferenceProlog()); // --- room preference ------------ String roomPref = null; PreferenceLevel roomPreference = getRoomPreference(clazz.getManagingDept().getUniqueId(),room.getUniqueId()); if (roomPreference!=null) { roomPref = roomPreference.getPrefProlog(); if (!iInteractiveMode && PreferenceLevel.sProhibited.equals(roomPref)) { iProgress.trace("room is prohibited (on room level) :-("); add=false; } if (PreferenceLevel.sStronglyDiscouraged.equals(roomPref)) { roomPref = PreferenceLevel.sProhibited; } } for (Iterator i2=roomPrefs.iterator();i2.hasNext();) { RoomPref p = (RoomPref)i2.next(); if (room.equals(p.getRoom())) { roomPref = p.getPrefLevel().getPrefProlog(); iProgress.trace("room preference is "+p.getPrefLevel().getPrefName()); break; } } if (roomPref!=null && roomPref.equals(PreferenceLevel.sProhibited)) { iProgress.trace("room is prohibited :-("); if (iInteractiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (reqRoom && (roomPref==null || !roomPref.equals(PreferenceLevel.sRequired))) { iProgress.trace("room is not required :-("); if (iInteractiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (!reqRoom && (roomPref!=null && roomPref.equals(PreferenceLevel.sRequired))) { iProgress.trace("room is required, removing all previous rooms (they are not required)"); reqRoom=true; if (iInteractiveMode) { for (RoomLocation r: roomLocations) { r.setPreference(r.getPreference()+100); } } else roomLocations.clear(); } if (roomPref!=null && !roomPref.equals(PreferenceLevel.sProhibited) && !roomPref.equals(PreferenceLevel.sRequired)) pref.addPreferenceProlog(roomPref); // --- building preference ------------ Building bldg = (room instanceof Room ? ((Room)room).getBuilding() : null); String bldgPref = null; for (Iterator i2=bldgPrefs.iterator();i2.hasNext();) { BuildingPref p = (BuildingPref)i2.next(); if (bldg!=null && bldg.equals(p.getBuilding())) { bldgPref = p.getPrefLevel().getPrefProlog(); iProgress.trace("building preference is "+p.getPrefLevel().getPrefName()); break; } } if (bldgPref!=null && bldgPref.equals(PreferenceLevel.sProhibited)) { iProgress.trace("building is prohibited :-("); if (iInteractiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (reqBldg && (bldgPref==null || !bldgPref.equals(PreferenceLevel.sRequired))) { iProgress.trace("building is not required :-("); if (iInteractiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } if (!reqBldg && (bldgPref!=null && bldgPref.equals(PreferenceLevel.sRequired))) { iProgress.trace("building is required, removing all previous rooms (they are not required)"); reqBldg = true; if (iInteractiveMode) { for (RoomLocation r: roomLocations) { r.setPreference(r.getPreference()+100); } } else roomLocations.clear(); } if (bldgPref!=null && !bldgPref.equals(PreferenceLevel.sProhibited) && !bldgPref.equals(PreferenceLevel.sRequired)) pref.addPreferenceProlog(bldgPref); // --- room features preference -------- boolean acceptableFeatures = true; PreferenceCombination featurePref = new MinMaxPreferenceCombination(); for (Iterator i2=featurePrefs.iterator();i2.hasNext();) { RoomFeaturePref roomFeaturePref = (RoomFeaturePref)i2.next(); RoomFeature feature = roomFeaturePref.getRoomFeature(); String p = roomFeaturePref.getPrefLevel().getPrefProlog(); boolean hasFeature = feature.getRooms().contains(room); if (p.equals(PreferenceLevel.sProhibited) && hasFeature) { iProgress.trace("present feature "+feature.getLabel()+" is prohibited :-("); acceptableFeatures=false; } if (p.equals(PreferenceLevel.sRequired) && !hasFeature) { iProgress.trace("not present feature "+feature.getLabel()+" is required :-("); acceptableFeatures=false; } if (p!=null && hasFeature && !p.equals(PreferenceLevel.sProhibited) && !p.equals(PreferenceLevel.sRequired)) featurePref.addPreferenceProlog(p); } pref.addPreferenceInt(featurePref.getPreferenceInt()); if (!acceptableFeatures) { if (iInteractiveMode) pref.addPreferenceProlog(PreferenceLevel.sProhibited); else add=false; } // --- room size ----------------- if (room.getCapacity().intValue()<stronglyDiscouragedCapacity) { iProgress.trace("too small :-("); if (iInteractiveMode) pref.addPreferenceInt(1000); else add=false; } else if (room.getCapacity().intValue()<discouragedCapacity) { iProgress.trace("room of strongly discouraged size"); pref.addPreferenceProlog(PreferenceLevel.sStronglyDiscouraged); } else if (room.getCapacity().intValue()<roomCapacity) { iProgress.trace("room of discouraged size"); pref.addPreferenceProlog(PreferenceLevel.sDiscouraged); } int prefInt = pref.getPreferenceInt(); iProgress.trace("room preference is "+prefInt); if (!add) continue; roomLocations.add( new RoomLocation( room.getUniqueId(), room.getLabel(), (bldg==null?null:bldg.getUniqueId()), prefInt, room.getCapacity().intValue(), room.getCoordinateX(), room.getCoordinateY(), (room.isIgnoreTooFar()==null?false:room.isIgnoreTooFar().booleanValue()), getRoomConstraint(clazz.getManagingDept(),room,hibSession))); } if (roomLocations.isEmpty() || roomLocations.size()<(clazz.getNbrRooms()==null?1:clazz.getNbrRooms().intValue())) { iProgress.message(msglevel("noRoom", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(clazz)+" has no available room"+(clazz.getNbrRooms()!=null && clazz.getNbrRooms().intValue()>1?"s":"")+" (class not loaded)."); return null; } } else { if (!groupPrefs.isEmpty() || !roomPrefs.isEmpty() || !bldgPrefs.isEmpty() || !featurePrefs.isEmpty()) iProgress.message(msglevel("zeroRoomsButPref", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(clazz)+" requires no room (number of rooms is set to zero), but it contains some room preferences."); } int minPerWeek = clazz.getSchedulingSubpart().getMinutesPerWk().intValue(); boolean onlyReq = false; for (Iterator i1=timePrefs.iterator();i1.hasNext();) { TimePref timePref = (TimePref)i1.next(); TimePatternModel pattern = timePref.getTimePatternModel(); if (pattern.isExactTime() || pattern.countPreferences(PreferenceLevel.sRequired)>0) onlyReq = true; } if (onlyReq) { iProgress.trace("time pattern has requred times"); } for (Iterator i1=timePrefs.iterator();i1.hasNext();) { TimePref timePref = (TimePref)i1.next(); TimePatternModel pattern = timePref.getTimePatternModel(); if (pattern.isExactTime()) { int length = ExactTimeMins.getNrSlotsPerMtg(pattern.getExactDays(),clazz.getSchedulingSubpart().getMinutesPerWk().intValue()); int breakTime = ExactTimeMins.getBreakTime(pattern.getExactDays(),clazz.getSchedulingSubpart().getMinutesPerWk().intValue()); TimeLocation loc = new TimeLocation(pattern.getExactDays(),pattern.getExactStartSlot(),length,PreferenceLevel.sIntLevelNeutral,0,datePattern.getUniqueId(),datePattern.getName(),datePattern.getPatternBitSet(),breakTime); loc.setTimePatternId(pattern.getTimePattern().getUniqueId()); timeLocations.add(loc); continue; } patterns.add(pattern.getTimePattern()); if (iWeakenTimePreferences) { pattern.weakenHardPreferences(); onlyReq = false; } if (clazz.getSchedulingSubpart().getMinutesPerWk().intValue()!=pattern.getMinPerMtg()*pattern.getNrMeetings()) { iProgress.message(msglevel("noTimePattern", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(clazz)+" has "+clazz.getSchedulingSubpart().getMinutesPerWk()+" minutes per week, but "+pattern.getName()+" time pattern selected."); minPerWeek = pattern.getMinPerMtg()*pattern.getNrMeetings(); if (iFixMinPerWeek) clazz.getSchedulingSubpart().setMinutesPerWk(new Integer(minPerWeek)); } for (int time=0;time<pattern.getNrTimes(); time++) { for (int day=0;day<pattern.getNrDays(); day++) { String pref = pattern.getPreference(day,time); iProgress.trace("checking time "+pattern.getDayHeader(day)+" "+pattern.getTimeHeaderShort(time)+" ("+pref+")"); if (!iInteractiveMode && pref.equals(PreferenceLevel.sProhibited)) { iProgress.trace("time is prohibited :-("); continue; } if (!iInteractiveMode && onlyReq && !pref.equals(PreferenceLevel.sRequired)) { iProgress.trace("time is not required :-("); continue; } TimeLocation loc = new TimeLocation( pattern.getDayCode(day), pattern.getStartSlot(time), pattern.getSlotsPerMtg(), PreferenceLevel.prolog2int(pattern.getPreference(day, time)), pattern.getNormalizedPreference(day,time,iNormalizedPrefDecreaseFactor), datePattern.getUniqueId(), datePattern.getName(), datePattern.getPatternBitSet(), pattern.getBreakTime()); loc.setTimePatternId(pattern.getTimePattern().getUniqueId()); if (iAlterTimePatternWeight!=0.0) { String altPref = iAlterTimePatternModel.getCombinedPreference(loc.getDayCode(), loc.getStartSlot(), loc.getLength(), TimePatternModel.sMixAlgMinMax); if (!altPref.equals(PreferenceLevel.sNeutral)) { loc.setNormalizedPreference(loc.getNormalizedPreference()+iAlterTimePatternWeight*PreferenceLevel.prolog2int(altPref)); } } if (iInteractiveMode && onlyReq && !pref.equals(PreferenceLevel.sRequired)) { loc.setPreference(PreferenceLevel.sIntLevelProhibited); loc.setNormalizedPreference(PreferenceLevel.sIntLevelProhibited); } timeLocations.add(loc); } } } if (iInteractiveMode) { List<TimePattern> allPatterns = iPatterns.get(new Integer(minPerWeek)); if (allPatterns==null) { allPatterns = TimePattern.findByMinPerWeek(iSession,false,false,false,minPerWeek,clazz.getManagingDept()); iPatterns.put(new Integer(minPerWeek),allPatterns); } for (TimePattern pattern: allPatterns) { if (patterns.contains(pattern)) continue; TimePatternModel model = pattern.getTimePatternModel(); iProgress.trace("adding prohibited pattern "+model.getName()); for (int time=0;time<model.getNrTimes(); time++) { for (int day=0;day<model.getNrDays(); day++) { TimeLocation loc = new TimeLocation( model.getDayCode(day), model.getStartSlot(time), model.getSlotsPerMtg(), PreferenceLevel.prolog2int(model.getPreference(day, time)), model.getNormalizedPreference(day,time,iNormalizedPrefDecreaseFactor), datePattern.getUniqueId(), datePattern.getName(), datePattern.getPatternBitSet(), model.getBreakTime()); loc.setTimePatternId(model.getTimePattern().getUniqueId()); loc.setPreference(1000); loc.setNormalizedPreference(1000.0); timeLocations.add(loc); } } } } if (timeLocations.isEmpty()) { iProgress.message(msglevel("noTime", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(clazz)+" has no available time (class not loaded)."); return null; } List<DepartmentalInstructor> instructors = clazz.getLeadInstructors(); String className = clazz.getClassLabel(); Lecture lecture = new Lecture( clazz.getUniqueId(), clazz.getManagingDept().getSolverGroup().getUniqueId(), clazz.getSchedulingSubpart().getUniqueId(), className, timeLocations, roomLocations, nrRooms, null, minClassLimit, maxClassLimit, room2limitRatio); lecture.setNote(clazz.getNotes()); if (clazz.getManagingDept()!=null) lecture.setScheduler(clazz.getManagingDept().getUniqueId()); lecture.setDepartment(dept.getUniqueId()); for (DepartmentalInstructor instructor: instructors) { getInstructorConstraint(instructor,hibSession).addVariable(lecture); } long estNrValues = lecture.nrTimeLocations(); for (int i=0;i<lecture.getNrRooms();i++) { estNrValues *= (lecture.nrRoomLocations()-i)/(lecture.getNrRooms()-i); } if (estNrValues>1000000) { iProgress.message(msglevel("hugeDomain", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(lecture)+" has too many possible placements ("+estNrValues+"). " + "The class was not loaded in order to prevent out of memory exception. " + "Please restrict the number of available rooms and/or times for this class."); for (DepartmentalInstructor instructor: instructors) { getInstructorConstraint(instructor,hibSession).removeVariable(lecture); } return null; } else if (estNrValues>10000) { iProgress.message(msglevel("bigDomain", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(lecture)+" has quite a lot of possible placements ("+estNrValues+"). " + "Solver may run too slow. " + "If possible, please restrict the number of available rooms and/or times for this class."); } if (lecture.values().isEmpty()) { if (!iInteractiveMode) { iProgress.message(msglevel("noPlacement", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(lecture)+" has no available placement (class not loaded)."); for (DepartmentalInstructor instructor: instructors) { getInstructorConstraint(instructor,hibSession).removeVariable(lecture); } return null; } else iProgress.message(msglevel("noPlacement", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(lecture)+" has no available placement."); } iLectures.put(clazz.getUniqueId(),lecture); getModel().addVariable(lecture); for (RoomLocation r: roomLocations) { r.getRoomConstraint().addVariable(lecture); } return lecture; } private void assignCommited() { if (!getModel().hasConstantVariables()) return; iProgress.setPhase("Assigning committed classes ...", getModel().constantVariables().size()); for (Lecture lecture: getModel().constantVariables()) { iProgress.incProgress(); if (lecture.getAssignment()!=null) continue; Placement placement = (Placement)lecture.getInitialAssignment(); Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(placement); if (conflictConstraints.isEmpty()) { lecture.assign(0,placement); } else { String warn = "Unable to assign committed class "+getClassLabel(lecture)+" &larr; "+placement.getLongName(); warn+="<br>&nbsp;&nbsp;Reason:"; for (Constraint<Lecture, Placement> c: conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement v: vals) { warn+="<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(v.variable())+" = "+v.getLongName(); } warn+="<br>&nbsp;&nbsp;&nbsp;&nbsp; in constraint "+c; iProgress.message(msglevel("cannotAssignCommitted", Progress.MSGLEVEL_WARN), warn); } } } } private void purgeInvalidValues() { iProgress.setPhase("Purging invalid placements ...", getModel().variables().size()); HashSet alreadyEmpty = new HashSet(); for (Lecture lecture: getModel().variables()) { if (lecture.values().isEmpty()) alreadyEmpty.add(lecture); } for (Lecture lecture: new ArrayList<Lecture>(getModel().variables())) { List<Placement> oldValues = new ArrayList<Placement>(lecture.values()); lecture.purgeInvalidValues(iInteractiveMode); if (lecture.values().isEmpty()) { if (!alreadyEmpty.contains(lecture)) { String warn = "Class "+getClassLabel(lecture)+" has no available placement (after enforcing consistency between the problem and committed solutions"+(iInteractiveMode?"":", class not loaded")+")."; for (Placement p: oldValues) { warn += "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+p.getNotValidReason(); } iProgress.message(msglevel("noPlacementAfterCommit", Progress.MSGLEVEL_WARN), warn); } if (!iInteractiveMode) { getModel().removeVariable(lecture); for (Constraint c: new ArrayList<Constraint>(lecture.constraints())) { c.removeVariable(lecture); if (c.variables().isEmpty()) getModel().removeConstraint(c); } for (Iterator i=lecture.students().iterator();i.hasNext();) { Student s = (Student)i.next(); s.getLectures().remove(lecture); } } } iProgress.incProgress(); } } private void loadAssignment(Assignment assignment) { Lecture lecture = (Lecture)iLectures.get(assignment.getClazz().getUniqueId()); int dayCode = assignment.getDays().intValue(); int startSlot = assignment.getStartSlot().intValue(); Long patternId = assignment.getTimePattern().getUniqueId(); DatePattern datePattern = assignment.getDatePattern(); Set<Location> rooms = assignment.getRooms(); if (lecture==null) return; Placement initialPlacement = null; for (Iterator i2=lecture.values().iterator();i2.hasNext();) { Placement placement = (Placement)i2.next(); if (placement.getTimeLocation().getDayCode()!=dayCode) continue; if (placement.getTimeLocation().getStartSlot()!=startSlot) continue; if (!placement.getTimeLocation().getTimePatternId().equals(patternId)) continue; if (datePattern != null && !placement.getTimeLocation().getDatePatternId().equals(datePattern.getUniqueId())) continue; boolean sameRooms = true; for (Iterator i=rooms.iterator();sameRooms && i.hasNext();) { Location r = (Location)i.next(); if (!placement.hasRoomLocation(r.getUniqueId())) sameRooms = false; } if (!sameRooms) continue; initialPlacement = placement; break; } if (initialPlacement==null) { TimeLocation timeLocation = null; for (TimeLocation t: lecture.timeLocations()) { if (t.getDayCode()!=dayCode) continue; if (t.getStartSlot()!=startSlot) continue; if (!t.getTimePatternId().equals(patternId)) continue; if (datePattern != null && !t.getDatePatternId().equals(datePattern.getUniqueId())) continue; timeLocation = t; break; } List<RoomLocation> roomLocations = new ArrayList<RoomLocation>(); for (Location room: rooms) { for (RoomLocation r: lecture.roomLocations()) { if (r.getId().equals(room.getUniqueId())) roomLocations.add(r); } } if (timeLocation!=null && roomLocations.size()==lecture.getNrRooms()) { initialPlacement = new Placement(lecture,timeLocation,roomLocations); } } if (initialPlacement==null) { StringBuffer sb = new StringBuffer(assignment.getTimeLocation().getLongName()+" "); for (Iterator<Location> i=rooms.iterator();i.hasNext();) { sb.append(i.next().getLabel()); if (i.hasNext()) sb.append(", "); } if (!assignment.getInstructors().isEmpty()) { sb.append(" "); for (Iterator i=assignment.getInstructors().iterator();i.hasNext();) { sb.append(((DepartmentalInstructor)i.next()).getName(iInstructorFormat)); if (i.hasNext()) sb.append(", "); } } iProgress.message(msglevel("placementNotValid", Progress.MSGLEVEL_WARN), "Unable to assign "+getClassLabel(lecture)+" &larr; "+sb+" (placement not valid)"); return; } if (!initialPlacement.isValid()) { String reason = ""; for (InstructorConstraint ic: lecture.getInstructorConstraints()) { if (!ic.isAvailable(lecture, initialPlacement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;instructor "+ic.getName()+" not available"; } if (lecture.getNrRooms()>0) { if (initialPlacement.isMultiRoom()) { for (RoomLocation roomLocation: initialPlacement.getRoomLocations()) { if (!roomLocation.getRoomConstraint().isAvailable(lecture,initialPlacement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+roomLocation.getName()+" not available"; } } else { if (!initialPlacement.getRoomLocation().getRoomConstraint().isAvailable(lecture,initialPlacement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+initialPlacement.getRoomLocation().getName()+" not available"; } } Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(initialPlacement); if (!conflictConstraints.isEmpty()) { for (Constraint<Lecture, Placement> c: conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement p: vals) { Lecture l = p.variable(); if (l.isCommitted()) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;conflict with committed assignment "+getClassLabel(l)+" = "+p.getLongName()+" (in constraint "+c+")"; if (p.equals(initialPlacement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;constraint "+c; } } } iProgress.message(msglevel("cannotAssign", Progress.MSGLEVEL_WARN), "Unable to assign "+getClassLabel(lecture)+" &larr; "+initialPlacement.getLongName()+(reason.length()==0?".":":"+reason)); } else { if (iMppAssignment) lecture.setInitialAssignment(initialPlacement); Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(initialPlacement); if (conflictConstraints.isEmpty()) { lecture.assign(0,initialPlacement); } else { String warn = "Unable to assign "+getClassLabel(lecture)+" &larr; "+initialPlacement.getLongName(); warn += "<br>&nbsp;&nbsp;Reason:"; for (Constraint<Lecture, Placement> c: conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement v: vals) { warn += "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(v.variable())+" = "+v.getLongName(); } warn += "<br>&nbsp;&nbsp;&nbsp;&nbsp; in constraint "+c; iProgress.message(msglevel("cannotAssign", Progress.MSGLEVEL_WARN), warn); } } } } private RoomConstraint getRoomConstraint(Department dept, Location location, org.hibernate.Session hibSession) { RoomConstraint rc = (RoomConstraint)iRooms.get(location.getUniqueId()); if (rc==null) { PreferenceLevel roomPreference = getRoomPreference(dept.getUniqueId(), location.getUniqueId()); boolean discouraged = (!iInteractiveMode && roomPreference!=null && ( roomPreference.getPrefProlog().equals(PreferenceLevel.sProhibited) || roomPreference.getPrefProlog().equals(PreferenceLevel.sStronglyDiscouraged) || roomPreference.getPrefProlog().equals(PreferenceLevel.sDiscouraged))); RoomSharingModel sharingModel = location.getRoomSharingModel(); if (sharingModel!=null && iIgnoreRoomSharing) { for (int d=0;d<sharingModel.getNrDays();d++) for (int t=0;t<sharingModel.getNrTimes();t++) if (!String.valueOf(RoomSharingModel.sNotAvailablePref).equals(sharingModel.getPreference(d, t))) sharingModel.setPreference(d, t, String.valueOf(RoomSharingModel.sFreeForAllPref)); } if (sharingModel!=null && sharingModel.allAvailable(null)) sharingModel=null; Long buildingId = null; if (location instanceof Room) { buildingId = ((Room)location).getBuilding().getUniqueId(); } rc = (discouraged? new DiscouragedRoomConstraint( getModel().getProperties(), location.getUniqueId(), location.getLabel(), buildingId, location.getCapacity().intValue(), sharingModel, location.getCoordinateX(), location.getCoordinateY(), (location.isIgnoreTooFar()==null?false:location.isIgnoreTooFar().booleanValue()), (location.isIgnoreRoomCheck()==null?true:!location.isIgnoreRoomCheck().booleanValue()) ) : new RoomConstraint( location.getUniqueId(), location.getLabel(), buildingId, location.getCapacity().intValue(), sharingModel, location.getCoordinateX(), location.getCoordinateY(), (location.isIgnoreTooFar()==null?false:location.isIgnoreTooFar().booleanValue()), (location.isIgnoreRoomCheck()==null?true:!location.isIgnoreRoomCheck().booleanValue()) ) ); rc.setType(location instanceof Room ? ((Room)location).getRoomType().getUniqueId() : null); //loadRoomAvailability(location, rc, hibSession); getModel().addConstraint(rc); iRooms.put(location.getUniqueId(),rc); } return rc; } private InstructorConstraint getInstructorConstraint(DepartmentalInstructor instructor, org.hibernate.Session hibSession) { if (instructor.getExternalUniqueId()!=null && instructor.getExternalUniqueId().length()>0) { InstructorConstraint ic = (InstructorConstraint)iInstructors.get(instructor.getExternalUniqueId()); if (ic!=null) return ic; } InstructorConstraint ic = (InstructorConstraint)iInstructors.get(instructor.getUniqueId()); if (ic==null) { boolean ignDist = (instructor.isIgnoreToFar()!=null && instructor.isIgnoreToFar().booleanValue()); ic = new InstructorConstraint(instructor.getUniqueId(),instructor.getExternalUniqueId(),instructor.getName(iInstructorFormat),ignDist); ic.setType(instructor.getPositionType()==null?new Long(Long.MAX_VALUE):new Long(instructor.getPositionType().getSortOrder())); //loadInstructorAvailability(instructor, ic, hibSession); getModel().addConstraint(ic); iInstructors.put(instructor.getUniqueId(),ic); if (instructor.getExternalUniqueId()!=null && instructor.getExternalUniqueId().length()>0) iInstructors.put(instructor.getExternalUniqueId(),ic); } return ic; } private void loadInstructorAvailabilities(org.hibernate.Session hibSession, String puids) { Query q = hibSession.createQuery("select distinct i.externalUniqueId, a from DepartmentalInstructor i inner join i.assignments as a " + "where i.externalUniqueId in ("+puids+") and a.solution.owner.session.uniqueId=:sessionId and a.solution.commited=true and a.solution.owner.uniqueId not in ("+iSolverGroupIds+")"); q.setLong("sessionId",iSessionId.longValue()); for (Iterator i=q.iterate();i.hasNext();) { Object[] x = (Object[])i.next(); String puid = (String)x[0]; Assignment a = (Assignment)x[1]; InstructorConstraint ic = (InstructorConstraint)iInstructors.get(puid); Placement p = a.getPlacement(); ic.setNotAvailable(p); if (!iLectures.containsKey(a.getClassId())) { iLectures.put(a.getClassId(), p.variable()); getModel().addVariable(p.variable()); } } } private void loadInstructorAvailabilities(org.hibernate.Session hibSession) { iProgress.setPhase("Loading instructor availabilities ...", 1); StringBuffer puids = new StringBuffer(); int idx = 0; for (Enumeration e=iInstructors.elements();e.hasMoreElements();) { InstructorConstraint ic = (InstructorConstraint)e.nextElement(); if (ic.getPuid()==null) continue; if (puids.length()>0) puids.append(","); puids.append("'"+ic.getPuid()+"'"); idx++; if (idx==100) { loadInstructorAvailabilities(hibSession, puids.toString()); puids = new StringBuffer(); idx = 0; } } if (puids.length()>0) loadInstructorAvailabilities(hibSession, puids.toString()); iProgress.incProgress(); } private void loadRoomAvailabilities(org.hibernate.Session hibSession, String roomids) { Query q = hibSession.createQuery("select distinct r.uniqueId, a from Location r inner join r.assignments as a "+ "where r.uniqueId in ("+roomids+") and a.solution.owner.session.uniqueId=:sessionId and a.solution.commited=true and a.solution.owner.uniqueId not in ("+iSolverGroupIds+")"); q.setLong("sessionId",iSessionId.longValue()); for (Iterator i=q.iterate();i.hasNext();) { Object[] x = (Object[])i.next(); Long roomId = (Long)x[0]; Assignment a = (Assignment)x[1]; Placement p = a.getPlacement(); RoomConstraint rc = (RoomConstraint)iRooms.get(roomId); rc.setNotAvailable(p); if (!iLectures.containsKey(a.getClassId())) { iLectures.put(a.getClassId(), p.variable()); getModel().addVariable(p.variable()); } } } private void loadRoomAvailabilities(org.hibernate.Session hibSession) { iProgress.setPhase("Loading room availabilities ...", 1); StringBuffer roomids = new StringBuffer(); int idx = 0; for (Enumeration e=iRooms.elements();e.hasMoreElements();) { RoomConstraint rc = (RoomConstraint)e.nextElement(); if (roomids.length()>0) roomids.append(","); roomids.append(rc.getResourceId()); idx++; if (idx==100) { loadRoomAvailabilities(hibSession, roomids.toString()); roomids = new StringBuffer(); idx = 0; } } if (roomids.length()>0) loadRoomAvailabilities(hibSession, roomids.toString()); iProgress.incProgress(); } private Constraint createGroupConstraint(DistributionPref pref) { Constraint gc = null; if ("SAME_INSTR".equals(pref.getDistributionType().getReference()) && PreferenceLevel.sRequired.equals(pref.getPrefLevel().getPrefProlog())) { gc = new InstructorConstraint(new Long(-(int)pref.getUniqueId().longValue()),null, pref.getDistributionType().getLabel(),false); } else if ("SPREAD".equals(pref.getDistributionType().getReference())) { gc = new SpreadConstraint(getModel().getProperties(), "spread"); } else if ("MIN_ROOM_USE".equals(pref.getDistributionType().getReference())) { if (!iInteractiveMode) gc = new MinimizeNumberOfUsedRoomsConstraint(getModel().getProperties()); else iProgress.message(msglevel("constraintNotUsed", Progress.MSGLEVEL_INFO), "Minimize number of used rooms constraint not loaded due to the interactive mode of the solver."); } else if ("MIN_GRUSE(10x1h)".equals(pref.getDistributionType().getReference())) { if (!iInteractiveMode) gc = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(),"10x1h",MinimizeNumberOfUsedGroupsOfTime.sGroups10of1h); else iProgress.message(msglevel("constraintNotUsed", Progress.MSGLEVEL_INFO), "Minimize number of used groups of time constraint not loaded due to the interactive mode of the solver."); } else if ("MIN_GRUSE(5x2h)".equals(pref.getDistributionType().getReference())) { if (!iInteractiveMode) gc = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(),"5x2h",MinimizeNumberOfUsedGroupsOfTime.sGroups5of2h); else iProgress.message(msglevel("constraintNotUsed", Progress.MSGLEVEL_INFO), "Minimize number of used groups of time constraint not loaded due to the interactive mode of the solver."); } else if ("MIN_GRUSE(3x3h)".equals(pref.getDistributionType().getReference())) { if (!iInteractiveMode) gc = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(),"3x3h",MinimizeNumberOfUsedGroupsOfTime.sGroups3of3h); else iProgress.message(msglevel("constraintNotUsed", Progress.MSGLEVEL_INFO), "Minimize number of used groups of time constraint not loaded due to the interactive mode of the solver."); } else if ("MIN_GRUSE(2x5h)".equals(pref.getDistributionType().getReference())) { if (!iInteractiveMode) gc = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(),"2x5h",MinimizeNumberOfUsedGroupsOfTime.sGroups2of5h); else iProgress.message(msglevel("constraintNotUsed", Progress.MSGLEVEL_INFO), "Minimize number of used groups of time constraint not loaded due to the interactive mode of the solver."); } else { GroupConstraint.ConstraintType type = GroupConstraint.ConstraintType.get(pref.getDistributionType().getReference()); if (type == null) { iProgress.error("Distribution constraint " + pref.getDistributionType().getReference() + " is not implemented."); return null; } gc = new GroupConstraint(pref.getUniqueId(), type, pref.getPrefLevel().getPrefProlog()); } return gc; } private void errorAddGroupConstraintNotFound(DistributionPref pref, Class_ clazz) { if (pref.getOwner()!=null && pref.getOwner() instanceof DepartmentalInstructor) iProgress.message(msglevel("notLoadedInInstrPref", Progress.MSGLEVEL_INFO), "Lecture "+getClassLabel(clazz)+" not found/loaded, but used in distribution preference "+pref.getDistributionType().getLabel()+pref.getGroupingSufix()); else iProgress.message(msglevel("notLoadedInDistPref", Progress.MSGLEVEL_WARN), "Lecture "+getClassLabel(clazz)+" not found/loaded, but used in distribution preference "+pref.getDistributionType().getLabel()+pref.getGroupingSufix()); } private Lecture getLecture(Class_ clazz) { Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture!=null) return lecture; if (iAllClasses.contains(clazz)) return null; try { Assignment assignment = clazz.getCommittedAssignment(); if (assignment!=null) { Placement placement = assignment.getPlacement(); lecture = (Lecture)placement.variable(); getModel().addVariable(lecture); iLectures.put(clazz.getUniqueId(), lecture); } } catch (LazyInitializationException e) { Assignment assignment = (new AssignmentDAO()).get(clazz.getCommittedAssignment().getUniqueId()); if (assignment!=null) { Placement placement = assignment.getPlacement(); lecture = (Lecture)placement.variable(); getModel().addVariable(lecture); iLectures.put(clazz.getUniqueId(), lecture); } } return lecture; } private void addGroupConstraint(Constraint<Lecture, Placement> gc) { if (gc.variables().isEmpty()) return; boolean allVariablesAreCommitted = true; for (Lecture lecture: gc.variables()) { if (!lecture.isCommitted()) { allVariablesAreCommitted = false; break; } } if (allVariablesAreCommitted) { iProgress.debug("Not created constraint "+gc.getName()+" between "+gc.variables()+" (all variables are committed)"); for (Lecture lecture: new ArrayList<Lecture>(gc.variables())) { gc.removeVariable(lecture); } return; } getModel().addConstraint(gc); iProgress.trace("Added constraint "+gc.getName()+" between "+gc.variables()); } private void loadGroupConstraint(DistributionPref pref) { int groupingType = (pref.getGrouping()==null?DistributionPref.sGroupingNone:pref.getGrouping().intValue()); if (groupingType==DistributionPref.sGroupingProgressive) { int maxSize = 0; for (Iterator i=pref.getOrderedSetOfDistributionObjects().iterator();i.hasNext();) { DistributionObject distributionObject = (DistributionObject)i.next(); if (distributionObject.getPrefGroup() instanceof Class_) maxSize = Math.max(maxSize, 1); else if (distributionObject.getPrefGroup() instanceof SchedulingSubpart) maxSize = Math.max(maxSize, ((SchedulingSubpart)distributionObject.getPrefGroup()).getClasses().size()); } Constraint gc[] = new Constraint[maxSize]; Set gcClasses[] = new Set[maxSize]; for (int i=0;i<gc.length;i++) { gc[i]=createGroupConstraint(pref); if (gc[i]==null) return; gcClasses[i]=new HashSet(); } List<Lecture> allLectureOfCorrectOrder = new ArrayList<Lecture>(); for (Iterator i=pref.getOrderedSetOfDistributionObjects().iterator();i.hasNext();) { DistributionObject distributionObject = (DistributionObject)i.next(); if (distributionObject.getPrefGroup() instanceof Class_) { Class_ clazz = (Class_)distributionObject.getPrefGroup(); Lecture lecture = (Lecture)getLecture(clazz); if (lecture!=null) allLectureOfCorrectOrder.add(lecture); } else if (distributionObject.getPrefGroup() instanceof SchedulingSubpart) { SchedulingSubpart subpart = (SchedulingSubpart)distributionObject.getPrefGroup(); List<Class_> classes = new ArrayList<Class_>(subpart.getClasses()); Collections.sort(classes,new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (Class_ clazz: classes) { Lecture lecture = getLecture(clazz); if (lecture!=null) allLectureOfCorrectOrder.add(lecture); } } } List<DistributionObject> distributionObjects = new ArrayList<DistributionObject>(pref.getDistributionObjects()); Collections.sort(distributionObjects, new ChildrenFirstDistributionObjectComparator()); for (DistributionObject distributionObject: distributionObjects) { if (distributionObject.getPrefGroup() instanceof Class_) { Class_ clazz = (Class_)distributionObject.getPrefGroup(); Lecture lecture = (Lecture)getLecture(clazz); if (lecture==null) { errorAddGroupConstraintNotFound(pref, clazz); continue; } for (int j=0;j<gc.length;j++) { gc[j].addVariable(lecture); gcClasses[j].add(clazz); } } else if (distributionObject.getPrefGroup() instanceof SchedulingSubpart) { SchedulingSubpart subpart = (SchedulingSubpart)distributionObject.getPrefGroup(); List<Class_> classes = new ArrayList<Class_>(subpart.getClasses()); Collections.sort(classes,new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (int j=0;j<gc.length;j++) { Class_ clazz = null; for (Iterator k=gcClasses[j].iterator();k.hasNext() && clazz==null;) { clazz = getParentClass((Class_)k.next(),subpart); } if (clazz==null) clazz = (Class_)classes.get(j%classes.size()); Lecture lecture = getLecture(clazz); if (lecture==null) { errorAddGroupConstraintNotFound(pref, clazz); continue; } gc[j].addVariable(lecture); gcClasses[j].add(clazz); } } else { iProgress.message(msglevel("badDistributionObj", Progress.MSGLEVEL_WARN), "Distribution preference "+pref.getDistributionType().getLabel()+pref.getGroupingSufix()+" refers to unsupported object "+distributionObject.getPrefGroup()); } } for (int i=0;i<gc.length;i++) { Comparator cmp = new ObjectsByGivenOrderComparator(allLectureOfCorrectOrder); if (!gc[i].variables().isEmpty()) { Collections.sort(gc[i].variables(), cmp); addGroupConstraint(gc[i]); } } } else if (groupingType==DistributionPref.sGroupingPairWise) { List<Lecture> lectures = new ArrayList<Lecture>(); for (Iterator i=pref.getOrderedSetOfDistributionObjects().iterator();i.hasNext();) { DistributionObject distributionObject = (DistributionObject)i.next(); if (distributionObject.getPrefGroup() instanceof Class_) { Class_ clazz = (Class_)distributionObject.getPrefGroup(); Lecture lecture = getLecture(clazz); if (lecture==null) { errorAddGroupConstraintNotFound(pref, clazz); continue; } lectures.add(lecture); } else if (distributionObject.getPrefGroup() instanceof SchedulingSubpart) { SchedulingSubpart subpart = (SchedulingSubpart)distributionObject.getPrefGroup(); List<Class_> classes = new ArrayList<Class_>(subpart.getClasses()); Collections.sort(classes,new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (Class_ clazz: classes) { Lecture lecture = getLecture(clazz); if (lecture==null) { errorAddGroupConstraintNotFound(pref, clazz); continue; } lectures.add(lecture); } } else { iProgress.message(msglevel("badDistributionObj", Progress.MSGLEVEL_WARN), "Distribution preference "+pref.getDistributionType().getLabel()+pref.getGroupingSufix()+" refers to unsupported object "+distributionObject.getPrefGroup()); } } if (lectures.size()<2) { iProgress.message(msglevel("distrPrefIncomplete", Progress.MSGLEVEL_WARN), "Distribution preference "+pref.getDistributionType().getLabel()+pref.getGroupingSufix()+" refers to less than two classes"); } else { for (int idx1=0;idx1<lectures.size()-1;idx1++) { Lecture l1 = lectures.get(idx1); for (int idx2=idx1+1;idx2<lectures.size();idx2++) { Lecture l2 = lectures.get(idx2); Constraint gc = createGroupConstraint(pref); if (gc==null) return; gc.addVariable(l1); gc.addVariable(l2); addGroupConstraint(gc); } } } } else { Constraint gc = createGroupConstraint(pref); if (gc==null) return; for (Iterator i=pref.getOrderedSetOfDistributionObjects().iterator();i.hasNext();) { DistributionObject distributionObject = (DistributionObject)i.next(); if (distributionObject.getPrefGroup() instanceof Class_) { Class_ clazz = (Class_)distributionObject.getPrefGroup(); Lecture lecture = getLecture(clazz); if (lecture==null) { errorAddGroupConstraintNotFound(pref, clazz); continue; } gc.addVariable(lecture); if (groupingType>=DistributionPref.sGroupingByTwo && gc.variables().size()==groupingType) { addGroupConstraint(gc); gc=createGroupConstraint(pref); if (gc==null) return; } } else if (distributionObject.getPrefGroup() instanceof SchedulingSubpart) { SchedulingSubpart subpart = (SchedulingSubpart)distributionObject.getPrefGroup(); List<Class_> classes = new ArrayList<Class_>(subpart.getClasses()); Collections.sort(classes,new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (Class_ clazz: classes) { Lecture lecture = getLecture(clazz); if (lecture==null) { errorAddGroupConstraintNotFound(pref, clazz); continue; } gc.addVariable(lecture); if (groupingType>=DistributionPref.sGroupingByTwo && gc.variables().size()==groupingType) { addGroupConstraint(gc); gc=createGroupConstraint(pref); if (gc==null) return; } } } else { iProgress.message(msglevel("badDistributionObj", Progress.MSGLEVEL_WARN), "Distribution preference "+pref.getDistributionType().getLabel()+pref.getGroupingSufix()+" refers to unsupported object "+distributionObject.getPrefGroup()); } } addGroupConstraint(gc); } } private void loadInstructorGroupConstraint(DepartmentalInstructor instructor, DistributionPref pref) { Constraint gc = createGroupConstraint(pref); if (gc==null) return; boolean allExternallyManaged = true; for (Iterator i=instructor.getClasses().iterator();i.hasNext();) { ClassInstructor classInstructor = (ClassInstructor)i.next(); Class_ clazz = (Class_)classInstructor.getClassInstructing(); if (!clazz.getManagingDept().isExternalManager().booleanValue()) { allExternallyManaged = false; break; } } if (allExternallyManaged) return; for (Iterator i=instructor.getClasses().iterator();i.hasNext();) { ClassInstructor classInstructor = (ClassInstructor)i.next(); if (!classInstructor.isLead()) continue; Class_ clazz = (Class_)classInstructor.getClassInstructing(); Lecture lecture = getLecture(clazz); if (lecture==null) { errorAddGroupConstraintNotFound(pref, clazz); continue; } gc.addVariable(lecture); } addGroupConstraint(gc); } private void loadInstructorGroupConstraints(DepartmentalInstructor instructor) { Set prefs = instructor.getPreferences(DistributionPref.class); if (prefs==null || prefs.isEmpty()) return; for (Iterator i=prefs.iterator();i.hasNext();) { DistributionPref pref = (DistributionPref)i.next(); loadInstructorGroupConstraint(instructor, pref); } } private void loadInstructorGroupConstraints(Department department, org.hibernate.Session hibSession) { List instructors = hibSession.createQuery( "select distinct di from DepartmentalInstructor di inner join di.department d where d.uniqueId=:deptId" ).setLong("deptId",department.getUniqueId().longValue()).list(); if (instructors==null || instructors.isEmpty()) return; iProgress.setPhase("Loading instructor distr. constraints for "+department.getShortLabel()+" ...", instructors.size()); for (Iterator i=instructors.iterator();i.hasNext();) { DepartmentalInstructor instructor = (DepartmentalInstructor)i.next(); loadInstructorGroupConstraints(instructor); iProgress.incProgress(); } } private static Class_ getParentClass(Class_ clazz, SchedulingSubpart parentSubpart) { if (clazz==null) return null; if (parentSubpart.getClasses().contains(clazz)) return clazz; return getParentClass(clazz.getParentClass(), parentSubpart); } public static class ChildrenFirstDistributionObjectComparator implements Comparator<DistributionObject> { public int compare(DistributionObject d1, DistributionObject d2) { if (d1.getPrefGroup() instanceof Class_) { if (d2.getPrefGroup() instanceof Class_) return d1.compareTo(d2); else return 1; //classes last } else if (d2.getPrefGroup() instanceof Class_) return -1; if (!(d1.getPrefGroup() instanceof SchedulingSubpart) || !(d2.getPrefGroup() instanceof SchedulingSubpart)) return d1.compareTo(d2); //should not happen SchedulingSubpart s1 = (SchedulingSubpart)d1.getPrefGroup(); SchedulingSubpart s2 = (SchedulingSubpart)d2.getPrefGroup(); if (s1.getClasses().size()<=1) { if (s2.getClasses().size()<=1) return d1.compareTo(d2); else return 1; //singleton last } else if (s2.getClasses().size()<=1) return -1; if (getParentClass((Class_)s1.getClasses().iterator().next(),s2)!=null) return -1; //c1 is child, c2 is parent if (getParentClass((Class_)s2.getClasses().iterator().next(),s1)!=null) return 1; //c2 is child, c1 is parent return d1.compareTo(d2); } } private String getClassLimitConstraitName(SchedulingSubpart subpart) { if (subpart==null) return "class-limit"; String name = subpart.getCourseName()+" "+subpart.getItypeDesc().trim(); String sufix = subpart.getSchedulingSubpartSuffix(); if (sufix!=null && sufix.length()>0) name += " ("+sufix+")"; return name; } private String getClassLimitConstraitName(Lecture lecture) { return getClassLimitConstraitName((SchedulingSubpart)iSubparts.get(lecture.getSchedulingSubpartId())); } private void createChildrenClassLimitConstraits(Lecture parentLecture) { if (!parentLecture.hasAnyChildren()) return; for (Long subpartId: parentLecture.getChildrenSubpartIds()) { List<Lecture> children = parentLecture.getChildren(subpartId); ClassLimitConstraint clc = new ClassLimitConstraint(parentLecture, getClassLimitConstraitName(parentLecture)); boolean isMakingSense = false; for (Lecture lecture: children) { createChildrenClassLimitConstraits(lecture); if (!lecture.isCommitted() && lecture.minClassLimit() != lecture.maxClassLimit()) isMakingSense=true; } if (!isMakingSense) continue; for (Lecture lecture: children) { if (!lecture.isCommitted()) clc.addVariable(lecture); else clc.setClassLimitDelta(clc.getClassLimitDelta() - iClasses.get(lecture.getClassId()).getClassLimit()); } if (clc.variables().isEmpty()) continue; for (Class_ clazz: iSubparts.get(subpartId).getClasses()) { if (iLectures.get(clazz.getUniqueId()) == null) clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit()); } iProgress.trace("Added constraint "+clc.getName()+" between "+clc.variables()); getModel().addConstraint(clc); } } public void load() { org.hibernate.Session hibSession = null; Transaction tx = null; try { TimetableManagerDAO dao = new TimetableManagerDAO(); hibSession = dao.getSession(); tx = hibSession.beginTransaction(); load(hibSession); tx.commit(); } catch (Exception e) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load input data, reason:"+e.getMessage(),e); tx.rollback(); } finally { // here we need to close the session since this code may run in a separate thread if (hibSession!=null && hibSession.isOpen()) hibSession.close(); } } private boolean postSameStudentConstraint(Class_ clazz, String type) { boolean posted = false; if (!clazz.getChildClasses().isEmpty()) { for (Iterator i=clazz.getChildClasses().iterator();i.hasNext();) { Class_ c = (Class_)i.next(); if (postSameStudentConstraint(c, type)) posted = true; } } if (posted) return true; Lecture lecture = getLecture(clazz); if (lecture==null) return false; List<Lecture> variables = new ArrayList<Lecture>(); variables.add(lecture); Class_ parent = clazz; while ((parent=parent.getParentClass())!=null) { Lecture parentLecture = getLecture(parent); if (parentLecture!=null) variables.add(parentLecture); } for (Iterator i=clazz.getSchedulingSubpart().getInstrOfferingConfig().getSchedulingSubparts().iterator();i.hasNext();) { SchedulingSubpart subpart = (SchedulingSubpart)i.next(); if (subpart.getParentSubpart()!=null || subpart.getClasses().size()!=1) continue; Class_ singleClazz = (Class_)subpart.getClasses().iterator().next(); Lecture singleLecture = getLecture(singleClazz); if (singleLecture!=null && !variables.contains(singleLecture)) variables.add(singleLecture); } if (variables.size()==1) return false; GroupConstraint gc = new GroupConstraint(null, GroupConstraint.ConstraintType.get(type), PreferenceLevel.sRequired); for (Lecture var: variables) gc.addVariable(var); addGroupConstraint(gc); return true; } private void propagateCommittedAssignment(HashSet students, Assignment assignment) { Class_ clazz = assignment.getClazz(); Lecture parentLecture = null; Class_ c = clazz; while ((parentLecture==null || parentLecture.isCommitted()) && c.getParentClass()!=null) { c = c.getParentClass(); parentLecture = (Lecture)iLectures.get(c.getUniqueId()); } if (parentLecture!=null && !parentLecture.isCommitted()) { for (Lecture lecture: parentLecture.sameSubpartLectures()) { if (!lecture.equals(parentLecture) && !lecture.isCommitted()) { //iProgress.debug("[A] Students "+students+" cannot enroll "+lecture.getName()+" due to the enrollment of "+clazz.getClassLabel()); for (Iterator i=students.iterator();i.hasNext();) { Student student = (Student)i.next(); student.addCanNotEnroll(lecture); } } } } if (!clazz.getSchedulingSubpart().getChildSubparts().isEmpty()) { for (Iterator i=clazz.getSchedulingSubpart().getChildSubparts().iterator();i.hasNext();) { SchedulingSubpart subpart = (SchedulingSubpart)i.next(); for (Iterator j=subpart.getClasses().iterator();j.hasNext();) { Class_ child = (Class_)j.next(); if (!clazz.equals(child.getParentClass())) propagateCommittedAssignment(students, clazz, child); } } } } private void propagateCommittedAssignment(HashSet students, Class_ parent, Class_ clazz) { Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture!=null && !lecture.isCommitted()) { //iProgress.debug("[B] Students "+students+" cannot enroll "+lecture.getName()+" due to the enrollment of "+parent.getClassLabel()); for (Iterator i=students.iterator();i.hasNext();) { Student student = (Student)i.next(); student.addCanNotEnroll(lecture); } } else { for (Iterator i=clazz.getChildClasses().iterator();i.hasNext();) { Class_ child = (Class_)i.next(); propagateCommittedAssignment(students, parent, child); } } } private void loadCommittedStudentConflicts(org.hibernate.Session hibSession, Set<Long> offeringsToAvoid) { //Load all committed assignment - student relations that may be relevant List<Object[]> assignmentEnrollments = (List<Object[]>)hibSession.createQuery( "select distinct a, e.studentId, io.uniqueId from "+ "Solution s inner join s.assignments a inner join s.studentEnrollments e inner join a.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering io "+ "where "+ "s.commited=true and s.owner.session.uniqueId=:sessionId and s.owner not in ("+iSolverGroupIds+") and "+ "a.clazz=e.clazz").setLong("sessionId", iSessionId.longValue()).list(); // Filter out relevant relations (relations that are for loaded students) Hashtable<Assignment, Set<Student>> assignments = new Hashtable<Assignment, Set<Student>>(); for (Object[] result: assignmentEnrollments) { Assignment assignment = (Assignment)result[0]; Long studentId = (Long)result[1]; Long offeringId = (Long)result[2]; if (offeringsToAvoid.contains(offeringId)) continue; Student student = (Student)iStudents.get(studentId); if (student!=null) { Set<Student> students = assignments.get(assignment); if (students==null) { students = new HashSet<Student>(); assignments.put(assignment, students); } students.add(student); } } // Ensure no assignment-class relation is got from the cache for (Iterator i1=assignmentEnrollments.iterator(); i1.hasNext();) { Object[] result = (Object[])i1.next(); Assignment assignment = (Assignment)result[0]; if (!assignments.containsKey(assignment)) hibSession.evict(assignment); } for (Enumeration e1=assignments.keys(); e1.hasMoreElements();) { Assignment assignment = (Assignment)e1.nextElement(); Hibernate.initialize(assignment.getClazz()); } for (Enumeration e1=assignments.keys(); e1.hasMoreElements();) { Assignment assignment = (Assignment)e1.nextElement(); Hibernate.initialize(assignment.getClazz().getChildClasses()); Hibernate.initialize(assignment.getClazz().getSchedulingSubpart()); } for (Enumeration e1=assignments.keys(); e1.hasMoreElements();) { Assignment assignment = (Assignment)e1.nextElement(); Hibernate.initialize(assignment.getClazz().getSchedulingSubpart().getChildSubparts()); Hibernate.initialize(assignment.getClazz().getSchedulingSubpart().getClasses()); } // Make up the appropriate committed placements and propagate those through the course structure iProgress.setPhase("Loading student conflicts with commited solutions ...", assignments.size()); for (Iterator i1=assignments.entrySet().iterator(); i1.hasNext();) { Map.Entry entry = (Map.Entry)i1.next(); Assignment assignment = (Assignment)entry.getKey(); HashSet students = (HashSet)entry.getValue(); Placement committedPlacement = assignment.getPlacement(); for (Iterator i2=students.iterator();i2.hasNext();) { Student student = (Student)i2.next(); student.addCommitedPlacement(committedPlacement); } if (!iLectures.containsKey(assignment.getClassId())) { iLectures.put(assignment.getClassId(), committedPlacement.variable()); getModel().addVariable(committedPlacement.variable()); } propagateCommittedAssignment(students, assignment); iProgress.incProgress(); } } private boolean somehowEnroll(Student student, CourseOffering course, float weight) { if (course.getInstructionalOffering().isNotOffered()) return false; boolean hasSomethingCommitted = false; config: for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) { for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { for (Class_ clazz: subpart.getClasses()) { if (clazz.getCommittedAssignment() != null) { hasSomethingCommitted = true; break config; } } } } if (!hasSomethingCommitted) return false; if (!iOfferings.containsKey(course.getInstructionalOffering())) iOfferings.put(course.getInstructionalOffering(), loadOffering(course.getInstructionalOffering(), true)); student.addOffering(course.getInstructionalOffering().getUniqueId(), weight); Set<Student> students = iCourse2students.get(course); if (students==null) { students = new HashSet<Student>(); iCourse2students.put(course,students); } students.add(student); return true; } private void makeupCommittedStudentConflicts(Set<Long> offeringsToAvoid) { iProgress.setPhase("Creating student conflicts with commited solutions ...", iStudents.size()); for (Student student: iStudents.values()) { Set<WeightedCourseOffering> courses = iStudentCourseDemands.getCourses(student.getId()); iProgress.incProgress(); if (courses == null) continue; for (WeightedCourseOffering course: courses) { if (offeringsToAvoid.contains(course.getCourseOffering().getInstructionalOffering().getUniqueId())) continue; if (!somehowEnroll(student, course.getCourseOffering(), course.getWeight())) offeringsToAvoid.add(course.getCourseOffering().getInstructionalOffering().getUniqueId()); } } } private void propagateReservedClasses(Class_ clazz, Set<Long> reservedClasses) { reservedClasses.add(clazz.getUniqueId()); for (Class_ child: clazz.getChildClasses()) propagateReservedClasses(child, reservedClasses); } private boolean canAttend(Set<Lecture> cannotAttendLectures, Collection<Lecture> lectures) { for (Iterator e=lectures.iterator();e.hasNext();) { Lecture lecture = (Lecture)e.next(); if (cannotAttendLectures.contains(lecture)) continue; boolean canAttend = true; if (lecture.hasAnyChildren()) { for (Long subpartId: lecture.getChildrenSubpartIds()) { if (!canAttend(cannotAttendLectures, lecture.getChildren(subpartId))) { canAttend = false; break; } } } if (canAttend) return true; } return false; } private boolean canAttendConfigurations(Set<Lecture> cannotAttendLectures, List<Configuration> configurations) { for (Configuration cfg: configurations) { boolean canAttend = true; for (Long subpartId: cfg.getTopSubpartIds()) { if (!canAttend(cannotAttendLectures, cfg.getTopLectures(subpartId))) { canAttend = false; break; } } if (canAttend) return true; } return false; } private void checkReservation(CourseOffering course, Set<Lecture> cannotAttendLectures, List<Configuration> configurations) { if (canAttendConfigurations(cannotAttendLectures, configurations)) return; iProgress.message(msglevel("badCourseReservation", Progress.MSGLEVEL_WARN), "Inconsistent course reservations for course "+getOfferingLabel(course)); } private Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> loadOffering(InstructionalOffering offering, boolean assignCommitted) { // solver group ids for fast check HashSet<Long> solverGroupIds = new HashSet<Long>(); for (Long solverGroupId: iSolverGroupId) solverGroupIds.add(solverGroupId); Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> cfg2topSubparts = new Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>(); // alternative configurations List<Configuration> altCfgs = new ArrayList<Configuration>(); iAltConfigurations.put(offering, altCfgs); for (InstrOfferingConfig config: offering.getInstrOfferingConfigs()) { // create a configuration, set alternative configurations Configuration cfg = new Configuration(offering.getUniqueId(), config.getUniqueId(), config.getLimit().intValue()); Set<SchedulingSubpart> topSubparts = new HashSet<SchedulingSubpart>(); for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null) { if (solverGroupIds.contains(clazz.getManagingDept().getSolverGroup().getUniqueId())) continue; // only classes of other problems if (clazz.getCommittedAssignment() == null) continue; // only committed classes if (iLectures.containsKey(clazz.getUniqueId())) continue; // already loaded Placement committedPlacement = clazz.getCommittedAssignment().getPlacement(); lecture = committedPlacement.variable(); iLectures.put(clazz.getUniqueId(), lecture); iClasses.put(lecture.getClassId(), clazz); iSubparts.put(subpart.getUniqueId(), subpart); getModel().addVariable(lecture); if (assignCommitted) { Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(committedPlacement); if (conflictConstraints.isEmpty()) { lecture.assign(0,committedPlacement); } else { String warn = "Unable to assign committed class "+getClassLabel(lecture)+" &larr; "+committedPlacement.getLongName(); warn+="<br>&nbsp;&nbsp;Reason:"; for (Constraint<Lecture, Placement> c: conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement v: vals) { warn+="<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(v.variable())+" = "+v.getLongName(); } warn+="<br>&nbsp;&nbsp;&nbsp;&nbsp; in constraint "+c; iProgress.message(msglevel("cannotAssignCommitted", Progress.MSGLEVEL_WARN), warn); } } } } } } for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { List<Lecture> sameSubpart = new ArrayList<Lecture>(); for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null) continue; // set parent lecture Class_ parentClazz = clazz.getParentClass(); if (parentClazz!=null) { Lecture parentLecture = null; Class_ c = clazz; while (parentLecture == null && c.getParentClass() != null) { c = c.getParentClass(); parentLecture = iLectures.get(c.getUniqueId()); } if (parentLecture != null) lecture.setParent(parentLecture); } // set same subpart lectures sameSubpart.add(lecture); lecture.setSameSubpartLectures(sameSubpart); if (lecture.getParent() == null) { // set configuration lecture.setConfiguration(cfg); // top subparts topSubparts.add(subpart); } } } if (!cfg.getTopLectures().isEmpty()) { // skip empty configurations altCfgs.add(cfg); cfg.setAltConfigurations(altCfgs); cfg2topSubparts.put(config, topSubparts); } } return cfg2topSubparts; } private void load(org.hibernate.Session hibSession) throws Exception { iProgress.setStatus("Loading input data ..."); SolverGroupDAO dao = new SolverGroupDAO(); hibSession = dao.getSession(); hibSession.setFlushMode(FlushMode.COMMIT); iSolverGroup = null; iSession = null; if (iSolverGroup==null) { iSolverGroup = new SolverGroup[iSolverGroupId.length]; for (int i=0;i<iSolverGroupId.length;i++) { iSolverGroup[i] = dao.get(iSolverGroupId[i], hibSession); if (iSolverGroup[i]==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solver group "+iSolverGroupId[i]+"."); return; } iProgress.debug("solver group["+(i+1)+"]: "+iSolverGroup[i].getName()); } } if (iSolverGroup==null || iSolverGroup.length==0) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No solver group loaded."); return; } iDepartmentIds = ""; for (int j=0;j<iSolverGroup.length;j++) { for (Iterator i=iSolverGroup[j].getDepartments().iterator();i.hasNext();) { Department d = (Department)i.next(); if (iDepartmentIds.length()>0) iDepartmentIds += ","; iDepartmentIds += d.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.DepartmentIds",iDepartmentIds); Hashtable<Long, Solution> solutions = null; if (iSolutionId!=null && iSolutionId.length>0) { solutions = new Hashtable<Long, Solution>(); String note=""; for (int i=0;i<iSolutionId.length;i++) { Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession); if (solution==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solution "+iSolutionId[i]+"."); return; } iProgress.debug("solution["+(i+1)+"] version: "+solution.getUniqueId()+" (created "+solution.getCreated()+", solver group "+solution.getOwner().getName()+")"); if (solution.getNote()!=null) { if (note.length()>0) note += "\n"; note += solution.getNote(); } solutions.put(solution.getOwner().getUniqueId(),solution); } getModel().getProperties().setProperty("General.Note",note); String solutionIdStr = ""; for (int i=0;i<iSolverGroupId.length;i++) { Solution solution = solutions.get(iSolverGroupId[i]); if (solution!=null) { if (solutionIdStr.length()>0) solutionIdStr += ","; solutionIdStr += solution.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.SolutionId",solutionIdStr); } if (iSession==null) iSession = (new SessionDAO()).get(iSessionId, hibSession); if (iSession==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No session loaded."); return; } iProgress.debug("session: "+iSession.getLabel()); getModel().getProperties().setProperty("Data.Term",iSession.getAcademicYearTerm()); getModel().getProperties().setProperty("Data.Initiative",iSession.getAcademicInitiative()); getModel().setYear(iSession.getSessionStartYear()); getModel().getProperties().setProperty("DatePattern.DayOfWeekOffset", String.valueOf( Constants.getDayOfWeek(DateUtils.getDate(1, iSession.getPatternStartMonth(), iSession.getSessionStartYear())))); iAllClasses = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (int i=0;i<iSolverGroup.length;i++) { for (Iterator j=iSolverGroup[i].getDepartments().iterator();j.hasNext();) { Department d = (Department)j.next(); iAllClasses.addAll(d.getClassesFetchWithStructure()); } } if (iAllClasses==null || iAllClasses.isEmpty()) { iProgress.message(msglevel("noClasses", Progress.MSGLEVEL_FATAL), "No classes to load."); return; } iProgress.debug("classes to load: "+iAllClasses.size()); for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getInstrOfferingConfigs()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getInstrOfferingConfig().getSchedulingSubparts()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getClasses()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getClassInstructors()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); for (Iterator j=c.getClassInstructors().iterator();j.hasNext();) { ClassInstructor ci = (ClassInstructor)j.next(); Hibernate.initialize(ci.getInstructor()); } } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getPreferences()); Hibernate.initialize(c.getSchedulingSubpart().getPreferences()); for (Iterator j=c.getClassInstructors().iterator();j.hasNext();) { ClassInstructor ci = (ClassInstructor)j.next(); Hibernate.initialize(ci.getInstructor().getPreferences()); } c.getControllingDept().getPreferences(); c.getManagingDept().getPreferences(); } iProgress.setPhase("Loading classes ...",iAllClasses.size()); int ord = 0; HashSet<SchedulingSubpart> subparts = new HashSet<SchedulingSubpart>(); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = loadClass(clazz,hibSession); subparts.add(clazz.getSchedulingSubpart()); if (lecture!=null) lecture.setOrd(ord++); iClasses.put(clazz.getUniqueId(),clazz); iProgress.incProgress(); } loadInstructorAvailabilities(hibSession); loadRoomAvailabilities(hibSession); iProgress.setPhase("Loading offerings ...", iAllClasses.size()); Set<Long> loadedOfferings = new HashSet<Long>(); for (Class_ clazz: iAllClasses) { Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); iProgress.incProgress(); if (lecture==null) continue; //skip classes that were not loaded InstructionalOffering offering = clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering(); if (!loadedOfferings.add(offering.getUniqueId())) continue; // already loaded iOfferings.put(offering, loadOffering(offering, false)); } /* // old code, replaced by Loading offerings ... part iProgress.setPhase("Setting parent classes ...",iLectures.size()); Hashtable<SchedulingSubpart, List<Lecture>> subparts = new Hashtable<SchedulingSubpart, List<Lecture>>(); Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> offerings = new Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig,Set<SchedulingSubpart>>>(); Hashtable<InstrOfferingConfig, Configuration> configurations = new Hashtable<InstrOfferingConfig, Configuration>(); Hashtable<InstructionalOffering, List<Configuration>> altConfigurations = new Hashtable<InstructionalOffering, List<Configuration>>(); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture==null) continue; //skip classes that were not loaded Class_ parentClazz = clazz.getParentClass(); if (parentClazz!=null) { Lecture parentLecture = null; Class_ c = clazz; while ((parentLecture==null || parentLecture.isCommitted()) && c.getParentClass()!=null) { c = c.getParentClass(); parentLecture = (Lecture)iLectures.get(c.getUniqueId()); } if (parentLecture!=null && !parentLecture.isCommitted()) lecture.setParent(parentLecture); } SchedulingSubpart subpart = clazz.getSchedulingSubpart(); InstrOfferingConfig config = subpart.getInstrOfferingConfig(); InstructionalOffering offering = config.getInstructionalOffering(); iSubparts.put(subpart.getUniqueId(),subpart); if (lecture.getParent()==null) { Configuration cfg = configurations.get(config); if (cfg==null) { cfg = new Configuration(offering.getUniqueId(), config.getUniqueId(), config.getLimit().intValue()); configurations.put(config, cfg); List<Configuration> altCfgs = altConfigurations.get(offering); if (altCfgs==null) { altCfgs = new ArrayList<Configuration>(); altConfigurations.put(offering, altCfgs); } altCfgs.add(cfg); cfg.setAltConfigurations(altCfgs); } lecture.setConfiguration(cfg); Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = offerings.get(offering); if (topSubparts==null) { topSubparts = new Hashtable(); offerings.put(offering,topSubparts); } Set<SchedulingSubpart> topSubpartsThisConfig = topSubparts.get(config); if (topSubpartsThisConfig==null) { topSubpartsThisConfig = new HashSet<SchedulingSubpart>(); topSubparts.put(config, topSubpartsThisConfig); } topSubpartsThisConfig.add(clazz.getSchedulingSubpart()); } List<Lecture> sameSubpart = subparts.get(clazz.getSchedulingSubpart()); if (sameSubpart==null) { sameSubpart = new ArrayList<Lecture>(); subparts.put(clazz.getSchedulingSubpart(), sameSubpart); } sameSubpart.add(lecture); lecture.setSameSubpartLectures(sameSubpart); iProgress.incProgress(); } */ List<DistributionPref> distPrefs = new ArrayList<DistributionPref>(); for (int i=0;i<iSolverGroup.length;i++) { distPrefs.addAll(iSolverGroup[i].getDistributionPreferences()); } iProgress.setPhase("Loading distribution preferences ...",distPrefs.size()); Hibernate.initialize(distPrefs); // Commented out for speeding up issues (calling just // Hibernate.initialize(distPrefs) instead) // May need to call Hibernate.initialize on committed classed // in getLecture(Class_) if this will cause issues. /* for (Iterator i=distPrefs.iterator();i.hasNext();) { DistributionPref distributionPref = (DistributionPref)i.next(); Hibernate.initialize(distributionPref.getDistributionObjects()); } */ for (Iterator i=distPrefs.iterator();i.hasNext();) { DistributionPref distributionPref = (DistributionPref)i.next(); if (!PreferenceLevel.sNeutral.equals(distributionPref.getPrefLevel().getPrefProlog())) loadGroupConstraint(distributionPref); iProgress.incProgress(); } for (int i=0;i<iSolverGroup.length;i++) { for (Iterator j=iSolverGroup[i].getDepartments().iterator();j.hasNext();) { loadInstructorGroupConstraints((Department)j.next(), hibSession); } } if (iAutoSameStudents) { iProgress.setPhase("Posting automatic same_students constraints ...",iAllClasses.size()); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture==null) continue; if (!lecture.hasAnyChildren()) postSameStudentConstraint(clazz, iAutoSameStudentsConstraint); iProgress.incProgress(); } } assignCommited(); iProgress.setPhase("Posting class limit constraints ...", iOfferings.size()); for (Map.Entry<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> entry: iOfferings.entrySet()) { Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = entry.getValue(); for (Map.Entry<InstrOfferingConfig, Set<SchedulingSubpart>> subpartEntry: topSubparts.entrySet()) { InstrOfferingConfig config = subpartEntry.getKey(); Set<SchedulingSubpart> topSubpartsThisConfig = subpartEntry.getValue(); for (SchedulingSubpart subpart: topSubpartsThisConfig) { boolean isMakingSense = false; for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null) continue; createChildrenClassLimitConstraits(lecture); if (!lecture.isCommitted() && lecture.minClassLimit() != lecture.maxClassLimit()) isMakingSense=true; } if (!isMakingSense) continue; if (subpart.getParentSubpart()==null) { ClassLimitConstraint clc = new ClassLimitConstraint(config.getLimit(), getClassLimitConstraitName(subpart)); for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit()); continue; } clc.addVariable(lecture); } if (clc.variables().isEmpty()) continue; iProgress.trace("Added constraint "+clc.getName()+" between "+clc.variables()); getModel().addConstraint(clc); } else { Hashtable<Long, ClassLimitConstraint> clcs = new Hashtable<Long, ClassLimitConstraint>(); for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); Class_ parentClazz = clazz.getParentClass(); ClassLimitConstraint clc = clcs.get(parentClazz.getUniqueId()); if (clc == null) { clc = new ClassLimitConstraint(parentClazz.getClassLimit(), parentClazz.getClassLabel()); clcs.put(parentClazz.getUniqueId(), clc); } if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta()-clazz.getClassLimit()); } else { clc.addVariable(lecture); } } for (ClassLimitConstraint clc: clcs.values()) { if (!clc.variables().isEmpty()) { iProgress.trace("Added constraint "+clc.getName()+" between "+clc.variables()); getModel().addConstraint(clc); } } } } } iProgress.incProgress(); } iStudentCourseDemands.init(hibSession, iProgress, iSession, iOfferings.keySet()); iProgress.setPhase("Loading students ...",iOfferings.size()); for (InstructionalOffering offering: iOfferings.keySet()) { int totalCourseLimit = 0; for (CourseOffering course: offering.getCourseOfferings()) { int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1) courseLimit = offering.getLimit(); else { iProgress.message(msglevel("crossListWithoutReservation", Progress.MSGLEVEL_WARN), "Cross-listed course "+getOfferingLabel(course)+" does not have any course reservation."); if (course.getProjectedDemand() != null) courseLimit = course.getProjectedDemand(); else if (course.getDemand() != null) courseLimit = course.getDemand(); else courseLimit = 0; } } totalCourseLimit += courseLimit; } Double factor = null; if (totalCourseLimit < offering.getLimit()) iProgress.message(msglevel("courseReservationsBelowLimit", Progress.MSGLEVEL_WARN), "Total number of course reservations is below the offering limit for instructional offering "+getOfferingLabel(offering)+" ("+totalCourseLimit+"<"+offering.getLimit().intValue()+")."); if (totalCourseLimit > offering.getLimit().intValue()) iProgress.message(msglevel("courseReservationsOverLimit", Progress.MSGLEVEL_INFO), "Total number of course reservations exceeds the offering limit for instructional offering "+getOfferingLabel(offering)+" ("+totalCourseLimit+">"+offering.getLimit().intValue()+")."); if (totalCourseLimit == 0) continue; if (totalCourseLimit != offering.getLimit()) factor = new Double(((double)offering.getLimit()) / totalCourseLimit); for (CourseOffering course: offering.getCourseOfferings()) { Set<WeightedStudentId> studentIds = iStudentCourseDemands.getDemands(course); float studentWeight = 0.0f; if (studentIds != null) for (WeightedStudentId studentId: studentIds) studentWeight += studentId.getWeight(); int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1) courseLimit = offering.getLimit().intValue(); else { courseLimit = Math.round(studentWeight); } } if (factor!=null) courseLimit = (int)Math.round(courseLimit * factor); if (studentIds == null || studentIds.isEmpty()) { iProgress.message(msglevel("offeringWithoutDemand", Progress.MSGLEVEL_INFO), "No student enrollments for offering "+getOfferingLabel(course)+"."); continue; } if (courseLimit == 0) { iProgress.message(msglevel("noCourseReservation", Progress.MSGLEVEL_WARN), "No reserved space for students of offering "+getOfferingLabel(course)+"."); } double weight = (iStudentCourseDemands.isWeightStudentsToFillUpOffering() && courseLimit != 0 ? (double)courseLimit / studentWeight : 1.0); Set<Lecture> cannotAttendLectures = null; if (offering.getCourseOfferings().size() > 1) { Set<Long> reservedClasses = new HashSet<Long>(); int limit = 0; boolean unlimited = false; for (Reservation r: offering.getReservations()) { if (r instanceof CourseReservation && course.equals(((CourseReservation)r).getCourse())) { for (Class_ clazz: r.getClasses()) { limit += clazz.getMaxExpectedCapacity(); propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config: r.getConfigurations()) { if (config.isUnlimitedEnrollment()) unlimited = true; else limit += config.getLimit(); for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } } if (!reservedClasses.isEmpty()) { iProgress.debug("Course requests for course "+getOfferingLabel(course)+" are "+reservedClasses); if (!unlimited && courseLimit > limit) iProgress.message(msglevel("insufficientCourseReservation", Progress.MSGLEVEL_WARN), "Too little space reserved in for course "+getOfferingLabel(course)+" ("+limit+"<"+courseLimit+")."); cannotAttendLectures = new HashSet<Lecture>(); for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz: subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) cannotAttendLectures.add(lecture); } } } if (!cannotAttendLectures.isEmpty()) { iProgress.debug("Prohibited lectures for course " + getOfferingLabel(course)+" are " + cannotAttendLectures); checkReservation(course, cannotAttendLectures, iAltConfigurations.get(offering)); } } } for (WeightedStudentId studentId: studentIds) { Student student = iStudents.get(studentId.getStudentId()); if (student==null) { student = new Student(studentId.getStudentId()); student.setAcademicArea(studentId.getArea()); student.setAcademicClassification(studentId.getClasf()); student.setMajor(studentId.getMajor()); student.setCurriculum(studentId.getCurriculum()); getModel().addStudent(student); iStudents.put(studentId.getStudentId(), student); } student.addOffering(offering.getUniqueId(), weight * studentId.getWeight()); Set<Student> students = iCourse2students.get(course); if (students==null) { students = new HashSet<Student>(); iCourse2students.put(course,students); } students.add(student); student.addCanNotEnroll(offering.getUniqueId(), cannotAttendLectures); Set<Long> reservedClasses = new HashSet<Long>(); for (Reservation reservation: offering.getReservations()) { if (reservation.getClasses().isEmpty() && reservation.getConfigurations().isEmpty()) continue; if (reservation instanceof CourseReservation) continue; if (reservation instanceof CurriculumReservation) { CurriculumReservation cr = (CurriculumReservation)reservation; if (student.getAcademicArea() == null) continue; if (!cr.getArea().getAcademicAreaAbbreviation().equals(student.getAcademicArea())) continue; if (!cr.getClassifications().isEmpty()) { boolean match = false; for (AcademicClassification clasf: cr.getClassifications()) { if (clasf.getCode().equals(student.getAcademicClassification())) { match = true; break; } } if (!match) continue; } if (!cr.getMajors().isEmpty()) { if (student.getMajor() == null) continue; if (!student.getMajor().isEmpty()) { boolean match = false; majors: for (PosMajor major: cr.getMajors()) { for (String code: student.getMajor().split("\\|")) { if (major.getCode().equals(code)) { match = true; break majors; } } } if (!match) continue; } } } else continue; for (Class_ clazz: reservation.getClasses()) { propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config: reservation.getConfigurations()) { for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } if (!reservedClasses.isEmpty()) { iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " has reserved classes " + reservedClasses); Set<Lecture> prohibited = new HashSet<Lecture>(); for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz: subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) prohibited.add(lecture); } } } iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " cannot attend classes " + prohibited); student.addCanNotEnroll(offering.getUniqueId(), prohibited); } } } iProgress.incProgress(); } iProgress.debug(iStudents.size()+" students loaded."); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iCommittedStudentConflictsMode == CommittedStudentConflictsMode.Load && !iStudentCourseDemands.isMakingUpStudents()) loadCommittedStudentConflicts(hibSession, loadedOfferings); else if (iCommittedStudentConflictsMode != CommittedStudentConflictsMode.Ignore) makeupCommittedStudentConflicts(loadedOfferings); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); Hashtable<Student, Set<Lecture>> iPreEnrollments = new Hashtable<Student, Set<Lecture>>(); if (iLoadStudentEnrlsFromSolution) { if (iStudentCourseDemands.canUseStudentClassEnrollmentsAsSolution()) { // Load real student enrollments (not saved last-like) List<Object[]> enrollments = (List<Object[]>)hibSession.createQuery( "select distinct e.student.uniqueId, e.clazz.uniqueId from " + "StudentClassEnrollment e, Class_ c where " + "e.courseOffering.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")").list(); iProgress.setPhase("Loading current student enrolments ...", enrollments.size()); int totalEnrollments = 0; for (Object[] o: enrollments) { Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture!=null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); totalEnrollments ++; } } iProgress.incProgress(); } iProgress.message(msglevel("enrollmentsLoaded", Progress.MSGLEVEL_INFO), "Loaded " + totalEnrollments + " enrollments of " + iPreEnrollments.size() + " students."); } else { // Load enrollments from selected / committed solutions for (int idx=0;idx<iSolverGroupId.length;idx++) { Solution solution = (solutions == null ? null : solutions.get(iSolverGroupId[idx])); List studentEnrls = null; if (solution != null) { studentEnrls = hibSession .createQuery("select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.uniqueId=:solutionId") .setLong("solutionId", solution.getUniqueId()) .list(); } else { studentEnrls = hibSession .createQuery("select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.owner.uniqueId=:sovlerGroupId and e.solution.commited = true") .setLong("sovlerGroupId", iSolverGroupId[idx]) .list(); } iProgress.setPhase("Loading student enrolments ["+(idx+1)+"] ...",studentEnrls.size()); for (Iterator i1=studentEnrls.iterator();i1.hasNext();) { Object o[] = (Object[])i1.next(); Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); - if (lecture!=null) { + if (lecture != null && lecture.getConfiguration() != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); } } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("Global.LoadOtherCommittedStudentEnrls", true)) { // Other committed enrollments List<Object[]> enrollments = (List<Object[]>)hibSession.createQuery( "select distinct e.studentId, e.clazz.uniqueId from " + "StudentEnrollment e, Class_ c where " + "e.solution.commited = true and e.solution.owner.uniqueId not in (" + iSolverGroupIds + ") and " + "e.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")").list(); iProgress.setPhase("Loading other committed student enrolments ...", enrollments.size()); for (Object[] o: enrollments) { Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture != null && lecture.getConfiguration() != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); } } iProgress.incProgress(); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (hasRoomAvailability()) loadRoomAvailability(RoomAvailability.getInstance()); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); iProgress.setPhase("Initial sectioning ...", iOfferings.size()); for (InstructionalOffering offering: iOfferings.keySet()) { Set<Student> students = new HashSet<Student>(); for (CourseOffering course: offering.getCourseOfferings()) { Set<Student> courseStudents = iCourse2students.get(course); if (courseStudents != null) students.addAll(courseStudents); } if (students.isEmpty()) continue; InitialSectioning.initialSectioningCfg(iProgress, offering.getUniqueId(), offering.getCourseName(), students, iAltConfigurations.get(offering)); iProgress.incProgress(); } for (Enumeration e=iStudents.elements();e.hasMoreElements();) { ((Student)e.nextElement()).clearDistanceCache(); } if (!iPreEnrollments.isEmpty()) { iProgress.setPhase("Checking loaded enrollments ....", iPreEnrollments.size()); for (Map.Entry<Student, Set<Lecture>> entry: iPreEnrollments.entrySet()) { iProgress.incProgress(); Student student = entry.getKey(); Set<Lecture> lectures = entry.getValue(); for (Lecture lecture: lectures) { if (!lecture.students().contains(student)) { iProgress.message(msglevel("studentNotEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is supposed to be enrolled to " + getClassLabel(lecture)); } } for (Lecture lecture: student.getLectures()) { if (!lectures.contains(lecture)) { Lecture instead = null; if (lecture.sameStudentsLectures() != null) { for (Lecture other: lecture.sameStudentsLectures()) { if (lectures.contains(other)) instead = other; } } if (instead != null) iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + ", he/she should have " + getClassLabel(instead) + " instead."); else iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_INFO), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + "."); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); iProgress.setPhase("Computing jenrl ...",iStudents.size()); Hashtable jenrls = new Hashtable(); for (Iterator i1=iStudents.values().iterator();i1.hasNext();) { Student st = (Student)i1.next(); for (Iterator i2=st.getLectures().iterator();i2.hasNext();) { Lecture l1 = (Lecture)i2.next(); for (Iterator i3=st.getLectures().iterator();i3.hasNext();) { Lecture l2 = (Lecture)i3.next(); if (l1.getId()>=l2.getId()) continue; Hashtable x = (Hashtable)jenrls.get(l1); if (x==null) { x = new Hashtable(); jenrls.put(l1, x); } JenrlConstraint jenrl = (JenrlConstraint)x.get(l2); if (jenrl==null) { jenrl = new JenrlConstraint(); getModel().addConstraint(jenrl); jenrl.addVariable(l1); jenrl.addVariable(l2); x.put(l2, jenrl); } jenrl.incJenrl(st); } } iProgress.incProgress(); } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (solutions!=null) { for (int idx=0;idx<iSolverGroupId.length;idx++) { Solution solution = (Solution)solutions.get(iSolverGroupId[idx]); if (solution==null) continue; iProgress.setPhase("Creating initial assignment ["+(idx+1)+"] ...",solution.getAssignments().size()); for (Iterator i1=solution.getAssignments().iterator();i1.hasNext();) { Assignment assignment = (Assignment)i1.next(); loadAssignment(assignment); iProgress.incProgress(); } } } else if (iLoadCommittedAssignments) { iProgress.setPhase("Creating initial assignment ...", getModel().variables().size()); for (Lecture lecture: getModel().variables()) { if (lecture.isCommitted()) continue; Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz != null && clazz.getCommittedAssignment() != null) loadAssignment(clazz.getCommittedAssignment()); iProgress.incProgress(); } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iSpread) { iProgress.setPhase("Posting automatic spread constraints ...", subparts.size()); for (SchedulingSubpart subpart: subparts) { if (subpart.getClasses().size()<=1) { iProgress.incProgress(); continue; } if (!subpart.isAutoSpreadInTime().booleanValue()) { iProgress.debug("Automatic spread constraint disabled for "+getSubpartLabel(subpart)); iProgress.incProgress(); continue; } SpreadConstraint spread = new SpreadConstraint(getModel().getProperties(),subpart.getCourseName()+" "+subpart.getItypeDesc().trim()); for (Iterator i2=subpart.getClasses().iterator();i2.hasNext();) { Class_ clazz = (Class_)i2.next(); Lecture lecture = (Lecture)getLecture(clazz); if (lecture==null) continue; spread.addVariable(lecture); } if (spread.variables().isEmpty()) iProgress.message(msglevel("courseWithNoClasses", Progress.MSGLEVEL_WARN), "No class for course "+getSubpartLabel(subpart)); else getModel().addConstraint(spread); iProgress.incProgress(); } } if (iDeptBalancing) { iProgress.setPhase("Creating dept. spread constraints ...",getModel().variables().size()); Hashtable<Long, DepartmentSpreadConstraint> depSpreadConstraints = new Hashtable<Long, DepartmentSpreadConstraint>(); for (Lecture lecture: getModel().variables()) { if (lecture.getDepartment()==null) continue; DepartmentSpreadConstraint deptConstr = (DepartmentSpreadConstraint)depSpreadConstraints.get(lecture.getDepartment()); if (deptConstr==null) { deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(),lecture.getDepartment(),(String)iDeptNames.get(lecture.getDepartment())); depSpreadConstraints.put(lecture.getDepartment(),deptConstr); getModel().addConstraint(deptConstr); } deptConstr.addVariable(lecture); iProgress.incProgress(); } } if (iSubjectBalancing) { iProgress.setPhase("Creating subject spread constraints ...",getModel().variables().size()); Hashtable<Long, SpreadConstraint> subjectSpreadConstraints = new Hashtable<Long, SpreadConstraint>(); for (Lecture lecture: getModel().variables()) { Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz == null) continue; for (CourseOffering co: clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getCourseOfferings()) { Long subject = co.getSubjectArea().getUniqueId(); SpreadConstraint subjectSpreadConstr = subjectSpreadConstraints.get(subject); if (subjectSpreadConstr==null) { subjectSpreadConstr = new SpreadConstraint(getModel().getProperties(), co.getSubjectArea().getSubjectAreaAbbreviation()); subjectSpreadConstraints.put(subject, subjectSpreadConstr); getModel().addConstraint(subjectSpreadConstr); } subjectSpreadConstr.addVariable(lecture); } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true)) purgeInvalidValues(); for (Constraint c: getModel().constraints()) { if (c instanceof SpreadConstraint) ((SpreadConstraint)c).init(); if (c instanceof DiscouragedRoomConstraint) ((DiscouragedRoomConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedRoomsConstraint) ((MinimizeNumberOfUsedRoomsConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedGroupsOfTime) ((MinimizeNumberOfUsedGroupsOfTime)c).setEnabled(true); } iProgress.setPhase("Checking for inconsistencies...", getModel().variables().size()); for (Lecture lecture: getModel().variables()) { iProgress.incProgress(); for (Iterator i=lecture.students().iterator();i.hasNext();) { Student s = (Student)i.next(); if (!s.canEnroll(lecture)) iProgress.message(msglevel("badStudentEnrollment", Progress.MSGLEVEL_INFO), "Invalid student enrollment of student "+s.getId()+" in class "+getClassLabel(lecture)+" found."); } //check same instructor constraint if (!lecture.values().isEmpty() && lecture.timeLocations().size()==1 && !lecture.getInstructorConstraints().isEmpty()) { for (Lecture other: getModel().variables()) { if (other.values().isEmpty() || other.timeLocations().size()!=1 || lecture.getClassId().compareTo(other.getClassId())<=0) continue; Placement p1 = lecture.values().get(0); Placement p2 = other.values().get(0); if (!other.getInstructorConstraints().isEmpty()) { for (InstructorConstraint ic: lecture.getInstructorConstraints()) { if (!other.getInstructorConstraints().contains(ic)) continue; if (p1.canShareRooms(p2) && p1.sameRooms(p2)) continue; if (p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) { iProgress.message(msglevel("reqInstructorOverlap", Progress.MSGLEVEL_WARN), "Same instructor and overlapping time required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } else if (ic.getDistancePreference(p1,p2)==PreferenceLevel.sIntLevelProhibited && lecture.roomLocations().size()==1 && other.roomLocations().size()==1) { iProgress.message(msglevel("reqInstructorBackToBack", Progress.MSGLEVEL_WARN), "Same instructor, back-to-back time and rooms too far (distance="+Math.round(10.0*Placement.getDistanceInMeters(getModel().getDistanceMetric(),p1,p2))+"m) required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } } } } } if (!lecture.isSingleton()) continue; for (Lecture other: getModel().variables()) { if (!other.isSingleton() || lecture.getClassId().compareTo(other.getClassId())<=0) continue; Placement p1 = lecture.values().get(0); Placement p2 = other.values().get(0); if (p1.shareRooms(p2) && p1.getTimeLocation().hasIntersection(p2.getTimeLocation()) && !p1.canShareRooms(p2)) { iProgress.message(msglevel("reqRoomOverlap", Progress.MSGLEVEL_WARN), "Same room and overlapping time required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } } if (lecture.getAssignment()==null) { Placement placement = lecture.values().get(0); if (!placement.isValid()) { String reason = ""; for (InstructorConstraint ic: lecture.getInstructorConstraints()) { if (!ic.isAvailable(lecture, placement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;instructor "+ic.getName()+" not available"; } if (lecture.getNrRooms()>0) { if (placement.isMultiRoom()) { for (RoomLocation roomLocation: placement.getRoomLocations()) { if (!roomLocation.getRoomConstraint().isAvailable(lecture,placement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+roomLocation.getName()+" not available"; } } else { if (!placement.getRoomLocation().getRoomConstraint().isAvailable(lecture,placement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+placement.getRoomLocation().getName()+" not available"; } } Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(placement); if (!conflictConstraints.isEmpty()) { for (Constraint<Lecture, Placement> c: conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement p: vals) { Lecture l = p.variable(); if (l.isCommitted()) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;conflict with committed assignment "+getClassLabel(l)+" = "+p.getLongName()+" (in constraint "+c+")"; if (p.equals(placement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;constraint "+c; } } } iProgress.message(msglevel("reqInvalidPlacement", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(lecture)+" requires an invalid placement "+placement.getLongName()+(reason.length()==0?".":":"+reason)); } else if (iAssignSingleton && getModel().conflictValues(placement).isEmpty()) lecture.assign(0, placement); } } if (getModel().getProperties().getPropertyBoolean("General.EnrollmentCheck", true)) new EnrollmentCheck(getModel(), msglevel("enrollmentCheck", Progress.MSGLEVEL_WARN)).checkStudentEnrollments(iProgress); if (getModel().getProperties().getPropertyBoolean("General.SwitchStudents",true) && !getModel().assignedVariables().isEmpty() && !iLoadStudentEnrlsFromSolution) getModel().switchStudents(); iProgress.setPhase("Done",1);iProgress.incProgress(); iProgress.message(msglevel("allDone", Progress.MSGLEVEL_INFO), "Model successfully loaded."); } public static class ObjectsByGivenOrderComparator implements Comparator { List<?> iOrderedSet = null; public ObjectsByGivenOrderComparator(List<?> orderedSetOfLectures) { iOrderedSet = orderedSetOfLectures; } public int compare(Object o1, Object o2) { int idx1 = iOrderedSet.indexOf(o1); int idx2 = iOrderedSet.indexOf(o2); int cmp = Double.compare(idx1, idx2); if (cmp!=0) return cmp; return ((Comparable)o1).compareTo(o2); } } public boolean isRemote() { return RemoteSolverServer.getServerThread()!=null; } public boolean hasRoomAvailability() { try { if (isRemote()) { return (Boolean)RemoteSolverServer.query(new Object[]{"hasRoomAvailability"}); } else return RoomAvailability.getInstance()!=null; } catch (Exception e) { sLog.error(e.getMessage(),e); iProgress.message(msglevel("roomAvailabilityFailure", Progress.MSGLEVEL_WARN), "Unable to access room availability service, reason:"+e.getMessage()); return false; } } public void roomAvailabilityActivate(Date startTime, Date endTime) { try { if (isRemote()) { RemoteSolverServer.query(new Object[]{"activateRoomAvailability",iSessionId,startTime,endTime,RoomAvailabilityInterface.sClassType}); } else { RoomAvailability.getInstance().activate(new SessionDAO().get(iSessionId), startTime, endTime, RoomAvailabilityInterface.sClassType, "true".equals(ApplicationProperties.getProperty("tmtbl.room.availability.solver.waitForSync","true"))); } } catch (Exception e) { sLog.error(e.getMessage(),e); iProgress.message(msglevel("roomAvailabilityFailure", Progress.MSGLEVEL_WARN), "Unable to access room availability service, reason:"+e.getMessage()); } } public void loadRoomAvailability(RoomAvailabilityInterface ra) { Date startDate = null, endDate = null; for (Iterator i=iAllUsedDatePatterns.iterator();i.hasNext();) { DatePattern dp = (DatePattern)i.next(); if (startDate == null || startDate.compareTo(dp.getStartDate())>0) startDate = dp.getStartDate(); if (endDate == null || endDate.compareTo(dp.getEndDate())<0) endDate = dp.getEndDate(); } Calendar startDateCal = Calendar.getInstance(Locale.US); startDateCal.setTime(startDate); startDateCal.set(Calendar.HOUR_OF_DAY, 0); startDateCal.set(Calendar.MINUTE, 0); startDateCal.set(Calendar.SECOND, 0); Calendar endDateCal = Calendar.getInstance(Locale.US); endDateCal.setTime(endDate); endDateCal.set(Calendar.HOUR_OF_DAY, 23); endDateCal.set(Calendar.MINUTE, 59); endDateCal.set(Calendar.SECOND, 59); roomAvailabilityActivate(startDateCal.getTime(),endDateCal.getTime()); iProgress.setPhase("Loading room availability...", iRooms.size()); int firstDOY = iSession.getDayOfYear(1,iSession.getPatternStartMonth()); int lastDOY = iSession.getDayOfYear(0,iSession.getPatternEndMonth()+1); int size = lastDOY - firstDOY; Calendar c = Calendar.getInstance(Locale.US); SimpleDateFormat df = new SimpleDateFormat("MM/dd"); long id = 0; int sessionYear = iSession.getSessionStartYear(); for (Enumeration e=iRooms.elements();e.hasMoreElements();) { RoomConstraint room = (RoomConstraint)e.nextElement(); iProgress.incProgress(); Collection<TimeBlock> times = getRoomAvailability(room, startDateCal.getTime(),endDateCal.getTime()); if (times==null) continue; for (TimeBlock time : times) { iProgress.debug(room.getName()+" not available due to "+time); int dayCode = 0; c.setTime(time.getStartTime()); int m = c.get(Calendar.MONTH); int d = c.get(Calendar.DAY_OF_MONTH); if (c.get(Calendar.YEAR)<sessionYear) m-=(12 * (sessionYear - c.get(Calendar.YEAR))); if (c.get(Calendar.YEAR)>sessionYear) m+=(12 * (c.get(Calendar.YEAR) - sessionYear)); BitSet weekCode = new BitSet(size); int offset = iSession.getDayOfYear(d,m) - firstDOY; if (offset < 0 || offset >= size) continue; weekCode.set(offset); switch (c.get(Calendar.DAY_OF_WEEK)) { case Calendar.MONDAY : dayCode = Constants.DAY_CODES[Constants.DAY_MON]; break; case Calendar.TUESDAY : dayCode = Constants.DAY_CODES[Constants.DAY_TUE]; break; case Calendar.WEDNESDAY : dayCode = Constants.DAY_CODES[Constants.DAY_WED]; break; case Calendar.THURSDAY : dayCode = Constants.DAY_CODES[Constants.DAY_THU]; break; case Calendar.FRIDAY : dayCode = Constants.DAY_CODES[Constants.DAY_FRI]; break; case Calendar.SATURDAY : dayCode = Constants.DAY_CODES[Constants.DAY_SAT]; break; case Calendar.SUNDAY : dayCode = Constants.DAY_CODES[Constants.DAY_SUN]; break; } int startSlot = (c.get(Calendar.HOUR_OF_DAY)*60 + c.get(Calendar.MINUTE) - Constants.FIRST_SLOT_TIME_MIN) / Constants.SLOT_LENGTH_MIN; c.setTime(time.getEndTime()); int endSlot = (c.get(Calendar.HOUR_OF_DAY)*60 + c.get(Calendar.MINUTE) - Constants.FIRST_SLOT_TIME_MIN) / Constants.SLOT_LENGTH_MIN; int length = endSlot - startSlot; if (length<=0) continue; TimeLocation timeLocation = new TimeLocation(dayCode, startSlot, length, 0, 0, null, df.format(time.getStartTime()), weekCode, 0); List<TimeLocation> timeLocations = new ArrayList<TimeLocation>(1); timeLocations.add(timeLocation); RoomLocation roomLocation = new RoomLocation(room.getResourceId(), room.getName(), room.getBuildingId(), 0, room.getCapacity(), room.getPosX(), room.getPosY(), room.getIgnoreTooFar(), room); List<RoomLocation> roomLocations = new ArrayList<RoomLocation>(1); roomLocations.add(roomLocation); Lecture lecture = new Lecture( new Long(--id), null, null, time.getEventName(), timeLocations, roomLocations, 1, new Placement(null,timeLocation,roomLocations), 0, 0, 1.0); lecture.setNote(time.getEventType()); Placement p = (Placement)lecture.getInitialAssignment(); lecture.setBestAssignment(p); lecture.setCommitted(true); room.setNotAvailable(p); getModel().addVariable(p.variable()); } } } public Collection<TimeBlock> getRoomAvailability(RoomConstraint room, Date startTime, Date endTime) { Collection<TimeBlock> ret = null; String ts = null; try { if (isRemote()) { ret = (Collection<TimeBlock>)RemoteSolverServer.query(new Object[]{"getRoomAvailability",room.getResourceId(),startTime,endTime, RoomAvailabilityInterface.sClassType}); if (!iRoomAvailabilityTimeStampIsSet) ts = (String)RemoteSolverServer.query(new Object[]{"getRoomAvailabilityTimeStamp",startTime, endTime, RoomAvailabilityInterface.sClassType}); } else { ret = RoomAvailability.getInstance().getRoomAvailability( LocationDAO.getInstance().get(room.getResourceId()), startTime, endTime, RoomAvailabilityInterface.sClassType); if (!iRoomAvailabilityTimeStampIsSet) ts = RoomAvailability.getInstance().getTimeStamp(startTime, endTime, RoomAvailabilityInterface.sClassType); } } catch (Exception e) { sLog.error(e.getMessage(),e); iProgress.message(msglevel("roomAvailabilityFailure", Progress.MSGLEVEL_WARN), "Unable to access room availability service, reason:"+e.getMessage()); } if (!iRoomAvailabilityTimeStampIsSet) { iRoomAvailabilityTimeStampIsSet = true; if (ts!=null) { getModel().getProperties().setProperty("RoomAvailability.TimeStamp", ts); iProgress.message(msglevel("roomAvailabilityUpdated", Progress.MSGLEVEL_INFO), "Using room availability that was updated on "+ts+"."); } else { iProgress.message(msglevel("roomAvailabilityFailure", Progress.MSGLEVEL_ERROR), "Room availability is not available."); } } return ret; } }
true
true
private void load(org.hibernate.Session hibSession) throws Exception { iProgress.setStatus("Loading input data ..."); SolverGroupDAO dao = new SolverGroupDAO(); hibSession = dao.getSession(); hibSession.setFlushMode(FlushMode.COMMIT); iSolverGroup = null; iSession = null; if (iSolverGroup==null) { iSolverGroup = new SolverGroup[iSolverGroupId.length]; for (int i=0;i<iSolverGroupId.length;i++) { iSolverGroup[i] = dao.get(iSolverGroupId[i], hibSession); if (iSolverGroup[i]==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solver group "+iSolverGroupId[i]+"."); return; } iProgress.debug("solver group["+(i+1)+"]: "+iSolverGroup[i].getName()); } } if (iSolverGroup==null || iSolverGroup.length==0) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No solver group loaded."); return; } iDepartmentIds = ""; for (int j=0;j<iSolverGroup.length;j++) { for (Iterator i=iSolverGroup[j].getDepartments().iterator();i.hasNext();) { Department d = (Department)i.next(); if (iDepartmentIds.length()>0) iDepartmentIds += ","; iDepartmentIds += d.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.DepartmentIds",iDepartmentIds); Hashtable<Long, Solution> solutions = null; if (iSolutionId!=null && iSolutionId.length>0) { solutions = new Hashtable<Long, Solution>(); String note=""; for (int i=0;i<iSolutionId.length;i++) { Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession); if (solution==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solution "+iSolutionId[i]+"."); return; } iProgress.debug("solution["+(i+1)+"] version: "+solution.getUniqueId()+" (created "+solution.getCreated()+", solver group "+solution.getOwner().getName()+")"); if (solution.getNote()!=null) { if (note.length()>0) note += "\n"; note += solution.getNote(); } solutions.put(solution.getOwner().getUniqueId(),solution); } getModel().getProperties().setProperty("General.Note",note); String solutionIdStr = ""; for (int i=0;i<iSolverGroupId.length;i++) { Solution solution = solutions.get(iSolverGroupId[i]); if (solution!=null) { if (solutionIdStr.length()>0) solutionIdStr += ","; solutionIdStr += solution.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.SolutionId",solutionIdStr); } if (iSession==null) iSession = (new SessionDAO()).get(iSessionId, hibSession); if (iSession==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No session loaded."); return; } iProgress.debug("session: "+iSession.getLabel()); getModel().getProperties().setProperty("Data.Term",iSession.getAcademicYearTerm()); getModel().getProperties().setProperty("Data.Initiative",iSession.getAcademicInitiative()); getModel().setYear(iSession.getSessionStartYear()); getModel().getProperties().setProperty("DatePattern.DayOfWeekOffset", String.valueOf( Constants.getDayOfWeek(DateUtils.getDate(1, iSession.getPatternStartMonth(), iSession.getSessionStartYear())))); iAllClasses = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (int i=0;i<iSolverGroup.length;i++) { for (Iterator j=iSolverGroup[i].getDepartments().iterator();j.hasNext();) { Department d = (Department)j.next(); iAllClasses.addAll(d.getClassesFetchWithStructure()); } } if (iAllClasses==null || iAllClasses.isEmpty()) { iProgress.message(msglevel("noClasses", Progress.MSGLEVEL_FATAL), "No classes to load."); return; } iProgress.debug("classes to load: "+iAllClasses.size()); for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getInstrOfferingConfigs()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getInstrOfferingConfig().getSchedulingSubparts()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getClasses()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getClassInstructors()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); for (Iterator j=c.getClassInstructors().iterator();j.hasNext();) { ClassInstructor ci = (ClassInstructor)j.next(); Hibernate.initialize(ci.getInstructor()); } } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getPreferences()); Hibernate.initialize(c.getSchedulingSubpart().getPreferences()); for (Iterator j=c.getClassInstructors().iterator();j.hasNext();) { ClassInstructor ci = (ClassInstructor)j.next(); Hibernate.initialize(ci.getInstructor().getPreferences()); } c.getControllingDept().getPreferences(); c.getManagingDept().getPreferences(); } iProgress.setPhase("Loading classes ...",iAllClasses.size()); int ord = 0; HashSet<SchedulingSubpart> subparts = new HashSet<SchedulingSubpart>(); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = loadClass(clazz,hibSession); subparts.add(clazz.getSchedulingSubpart()); if (lecture!=null) lecture.setOrd(ord++); iClasses.put(clazz.getUniqueId(),clazz); iProgress.incProgress(); } loadInstructorAvailabilities(hibSession); loadRoomAvailabilities(hibSession); iProgress.setPhase("Loading offerings ...", iAllClasses.size()); Set<Long> loadedOfferings = new HashSet<Long>(); for (Class_ clazz: iAllClasses) { Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); iProgress.incProgress(); if (lecture==null) continue; //skip classes that were not loaded InstructionalOffering offering = clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering(); if (!loadedOfferings.add(offering.getUniqueId())) continue; // already loaded iOfferings.put(offering, loadOffering(offering, false)); } /* // old code, replaced by Loading offerings ... part iProgress.setPhase("Setting parent classes ...",iLectures.size()); Hashtable<SchedulingSubpart, List<Lecture>> subparts = new Hashtable<SchedulingSubpart, List<Lecture>>(); Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> offerings = new Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig,Set<SchedulingSubpart>>>(); Hashtable<InstrOfferingConfig, Configuration> configurations = new Hashtable<InstrOfferingConfig, Configuration>(); Hashtable<InstructionalOffering, List<Configuration>> altConfigurations = new Hashtable<InstructionalOffering, List<Configuration>>(); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture==null) continue; //skip classes that were not loaded Class_ parentClazz = clazz.getParentClass(); if (parentClazz!=null) { Lecture parentLecture = null; Class_ c = clazz; while ((parentLecture==null || parentLecture.isCommitted()) && c.getParentClass()!=null) { c = c.getParentClass(); parentLecture = (Lecture)iLectures.get(c.getUniqueId()); } if (parentLecture!=null && !parentLecture.isCommitted()) lecture.setParent(parentLecture); } SchedulingSubpart subpart = clazz.getSchedulingSubpart(); InstrOfferingConfig config = subpart.getInstrOfferingConfig(); InstructionalOffering offering = config.getInstructionalOffering(); iSubparts.put(subpart.getUniqueId(),subpart); if (lecture.getParent()==null) { Configuration cfg = configurations.get(config); if (cfg==null) { cfg = new Configuration(offering.getUniqueId(), config.getUniqueId(), config.getLimit().intValue()); configurations.put(config, cfg); List<Configuration> altCfgs = altConfigurations.get(offering); if (altCfgs==null) { altCfgs = new ArrayList<Configuration>(); altConfigurations.put(offering, altCfgs); } altCfgs.add(cfg); cfg.setAltConfigurations(altCfgs); } lecture.setConfiguration(cfg); Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = offerings.get(offering); if (topSubparts==null) { topSubparts = new Hashtable(); offerings.put(offering,topSubparts); } Set<SchedulingSubpart> topSubpartsThisConfig = topSubparts.get(config); if (topSubpartsThisConfig==null) { topSubpartsThisConfig = new HashSet<SchedulingSubpart>(); topSubparts.put(config, topSubpartsThisConfig); } topSubpartsThisConfig.add(clazz.getSchedulingSubpart()); } List<Lecture> sameSubpart = subparts.get(clazz.getSchedulingSubpart()); if (sameSubpart==null) { sameSubpart = new ArrayList<Lecture>(); subparts.put(clazz.getSchedulingSubpart(), sameSubpart); } sameSubpart.add(lecture); lecture.setSameSubpartLectures(sameSubpart); iProgress.incProgress(); } */ List<DistributionPref> distPrefs = new ArrayList<DistributionPref>(); for (int i=0;i<iSolverGroup.length;i++) { distPrefs.addAll(iSolverGroup[i].getDistributionPreferences()); } iProgress.setPhase("Loading distribution preferences ...",distPrefs.size()); Hibernate.initialize(distPrefs); // Commented out for speeding up issues (calling just // Hibernate.initialize(distPrefs) instead) // May need to call Hibernate.initialize on committed classed // in getLecture(Class_) if this will cause issues. /* for (Iterator i=distPrefs.iterator();i.hasNext();) { DistributionPref distributionPref = (DistributionPref)i.next(); Hibernate.initialize(distributionPref.getDistributionObjects()); } */ for (Iterator i=distPrefs.iterator();i.hasNext();) { DistributionPref distributionPref = (DistributionPref)i.next(); if (!PreferenceLevel.sNeutral.equals(distributionPref.getPrefLevel().getPrefProlog())) loadGroupConstraint(distributionPref); iProgress.incProgress(); } for (int i=0;i<iSolverGroup.length;i++) { for (Iterator j=iSolverGroup[i].getDepartments().iterator();j.hasNext();) { loadInstructorGroupConstraints((Department)j.next(), hibSession); } } if (iAutoSameStudents) { iProgress.setPhase("Posting automatic same_students constraints ...",iAllClasses.size()); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture==null) continue; if (!lecture.hasAnyChildren()) postSameStudentConstraint(clazz, iAutoSameStudentsConstraint); iProgress.incProgress(); } } assignCommited(); iProgress.setPhase("Posting class limit constraints ...", iOfferings.size()); for (Map.Entry<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> entry: iOfferings.entrySet()) { Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = entry.getValue(); for (Map.Entry<InstrOfferingConfig, Set<SchedulingSubpart>> subpartEntry: topSubparts.entrySet()) { InstrOfferingConfig config = subpartEntry.getKey(); Set<SchedulingSubpart> topSubpartsThisConfig = subpartEntry.getValue(); for (SchedulingSubpart subpart: topSubpartsThisConfig) { boolean isMakingSense = false; for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null) continue; createChildrenClassLimitConstraits(lecture); if (!lecture.isCommitted() && lecture.minClassLimit() != lecture.maxClassLimit()) isMakingSense=true; } if (!isMakingSense) continue; if (subpart.getParentSubpart()==null) { ClassLimitConstraint clc = new ClassLimitConstraint(config.getLimit(), getClassLimitConstraitName(subpart)); for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit()); continue; } clc.addVariable(lecture); } if (clc.variables().isEmpty()) continue; iProgress.trace("Added constraint "+clc.getName()+" between "+clc.variables()); getModel().addConstraint(clc); } else { Hashtable<Long, ClassLimitConstraint> clcs = new Hashtable<Long, ClassLimitConstraint>(); for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); Class_ parentClazz = clazz.getParentClass(); ClassLimitConstraint clc = clcs.get(parentClazz.getUniqueId()); if (clc == null) { clc = new ClassLimitConstraint(parentClazz.getClassLimit(), parentClazz.getClassLabel()); clcs.put(parentClazz.getUniqueId(), clc); } if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta()-clazz.getClassLimit()); } else { clc.addVariable(lecture); } } for (ClassLimitConstraint clc: clcs.values()) { if (!clc.variables().isEmpty()) { iProgress.trace("Added constraint "+clc.getName()+" between "+clc.variables()); getModel().addConstraint(clc); } } } } } iProgress.incProgress(); } iStudentCourseDemands.init(hibSession, iProgress, iSession, iOfferings.keySet()); iProgress.setPhase("Loading students ...",iOfferings.size()); for (InstructionalOffering offering: iOfferings.keySet()) { int totalCourseLimit = 0; for (CourseOffering course: offering.getCourseOfferings()) { int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1) courseLimit = offering.getLimit(); else { iProgress.message(msglevel("crossListWithoutReservation", Progress.MSGLEVEL_WARN), "Cross-listed course "+getOfferingLabel(course)+" does not have any course reservation."); if (course.getProjectedDemand() != null) courseLimit = course.getProjectedDemand(); else if (course.getDemand() != null) courseLimit = course.getDemand(); else courseLimit = 0; } } totalCourseLimit += courseLimit; } Double factor = null; if (totalCourseLimit < offering.getLimit()) iProgress.message(msglevel("courseReservationsBelowLimit", Progress.MSGLEVEL_WARN), "Total number of course reservations is below the offering limit for instructional offering "+getOfferingLabel(offering)+" ("+totalCourseLimit+"<"+offering.getLimit().intValue()+")."); if (totalCourseLimit > offering.getLimit().intValue()) iProgress.message(msglevel("courseReservationsOverLimit", Progress.MSGLEVEL_INFO), "Total number of course reservations exceeds the offering limit for instructional offering "+getOfferingLabel(offering)+" ("+totalCourseLimit+">"+offering.getLimit().intValue()+")."); if (totalCourseLimit == 0) continue; if (totalCourseLimit != offering.getLimit()) factor = new Double(((double)offering.getLimit()) / totalCourseLimit); for (CourseOffering course: offering.getCourseOfferings()) { Set<WeightedStudentId> studentIds = iStudentCourseDemands.getDemands(course); float studentWeight = 0.0f; if (studentIds != null) for (WeightedStudentId studentId: studentIds) studentWeight += studentId.getWeight(); int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1) courseLimit = offering.getLimit().intValue(); else { courseLimit = Math.round(studentWeight); } } if (factor!=null) courseLimit = (int)Math.round(courseLimit * factor); if (studentIds == null || studentIds.isEmpty()) { iProgress.message(msglevel("offeringWithoutDemand", Progress.MSGLEVEL_INFO), "No student enrollments for offering "+getOfferingLabel(course)+"."); continue; } if (courseLimit == 0) { iProgress.message(msglevel("noCourseReservation", Progress.MSGLEVEL_WARN), "No reserved space for students of offering "+getOfferingLabel(course)+"."); } double weight = (iStudentCourseDemands.isWeightStudentsToFillUpOffering() && courseLimit != 0 ? (double)courseLimit / studentWeight : 1.0); Set<Lecture> cannotAttendLectures = null; if (offering.getCourseOfferings().size() > 1) { Set<Long> reservedClasses = new HashSet<Long>(); int limit = 0; boolean unlimited = false; for (Reservation r: offering.getReservations()) { if (r instanceof CourseReservation && course.equals(((CourseReservation)r).getCourse())) { for (Class_ clazz: r.getClasses()) { limit += clazz.getMaxExpectedCapacity(); propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config: r.getConfigurations()) { if (config.isUnlimitedEnrollment()) unlimited = true; else limit += config.getLimit(); for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } } if (!reservedClasses.isEmpty()) { iProgress.debug("Course requests for course "+getOfferingLabel(course)+" are "+reservedClasses); if (!unlimited && courseLimit > limit) iProgress.message(msglevel("insufficientCourseReservation", Progress.MSGLEVEL_WARN), "Too little space reserved in for course "+getOfferingLabel(course)+" ("+limit+"<"+courseLimit+")."); cannotAttendLectures = new HashSet<Lecture>(); for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz: subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) cannotAttendLectures.add(lecture); } } } if (!cannotAttendLectures.isEmpty()) { iProgress.debug("Prohibited lectures for course " + getOfferingLabel(course)+" are " + cannotAttendLectures); checkReservation(course, cannotAttendLectures, iAltConfigurations.get(offering)); } } } for (WeightedStudentId studentId: studentIds) { Student student = iStudents.get(studentId.getStudentId()); if (student==null) { student = new Student(studentId.getStudentId()); student.setAcademicArea(studentId.getArea()); student.setAcademicClassification(studentId.getClasf()); student.setMajor(studentId.getMajor()); student.setCurriculum(studentId.getCurriculum()); getModel().addStudent(student); iStudents.put(studentId.getStudentId(), student); } student.addOffering(offering.getUniqueId(), weight * studentId.getWeight()); Set<Student> students = iCourse2students.get(course); if (students==null) { students = new HashSet<Student>(); iCourse2students.put(course,students); } students.add(student); student.addCanNotEnroll(offering.getUniqueId(), cannotAttendLectures); Set<Long> reservedClasses = new HashSet<Long>(); for (Reservation reservation: offering.getReservations()) { if (reservation.getClasses().isEmpty() && reservation.getConfigurations().isEmpty()) continue; if (reservation instanceof CourseReservation) continue; if (reservation instanceof CurriculumReservation) { CurriculumReservation cr = (CurriculumReservation)reservation; if (student.getAcademicArea() == null) continue; if (!cr.getArea().getAcademicAreaAbbreviation().equals(student.getAcademicArea())) continue; if (!cr.getClassifications().isEmpty()) { boolean match = false; for (AcademicClassification clasf: cr.getClassifications()) { if (clasf.getCode().equals(student.getAcademicClassification())) { match = true; break; } } if (!match) continue; } if (!cr.getMajors().isEmpty()) { if (student.getMajor() == null) continue; if (!student.getMajor().isEmpty()) { boolean match = false; majors: for (PosMajor major: cr.getMajors()) { for (String code: student.getMajor().split("\\|")) { if (major.getCode().equals(code)) { match = true; break majors; } } } if (!match) continue; } } } else continue; for (Class_ clazz: reservation.getClasses()) { propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config: reservation.getConfigurations()) { for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } if (!reservedClasses.isEmpty()) { iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " has reserved classes " + reservedClasses); Set<Lecture> prohibited = new HashSet<Lecture>(); for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz: subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) prohibited.add(lecture); } } } iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " cannot attend classes " + prohibited); student.addCanNotEnroll(offering.getUniqueId(), prohibited); } } } iProgress.incProgress(); } iProgress.debug(iStudents.size()+" students loaded."); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iCommittedStudentConflictsMode == CommittedStudentConflictsMode.Load && !iStudentCourseDemands.isMakingUpStudents()) loadCommittedStudentConflicts(hibSession, loadedOfferings); else if (iCommittedStudentConflictsMode != CommittedStudentConflictsMode.Ignore) makeupCommittedStudentConflicts(loadedOfferings); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); Hashtable<Student, Set<Lecture>> iPreEnrollments = new Hashtable<Student, Set<Lecture>>(); if (iLoadStudentEnrlsFromSolution) { if (iStudentCourseDemands.canUseStudentClassEnrollmentsAsSolution()) { // Load real student enrollments (not saved last-like) List<Object[]> enrollments = (List<Object[]>)hibSession.createQuery( "select distinct e.student.uniqueId, e.clazz.uniqueId from " + "StudentClassEnrollment e, Class_ c where " + "e.courseOffering.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")").list(); iProgress.setPhase("Loading current student enrolments ...", enrollments.size()); int totalEnrollments = 0; for (Object[] o: enrollments) { Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture!=null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); totalEnrollments ++; } } iProgress.incProgress(); } iProgress.message(msglevel("enrollmentsLoaded", Progress.MSGLEVEL_INFO), "Loaded " + totalEnrollments + " enrollments of " + iPreEnrollments.size() + " students."); } else { // Load enrollments from selected / committed solutions for (int idx=0;idx<iSolverGroupId.length;idx++) { Solution solution = (solutions == null ? null : solutions.get(iSolverGroupId[idx])); List studentEnrls = null; if (solution != null) { studentEnrls = hibSession .createQuery("select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.uniqueId=:solutionId") .setLong("solutionId", solution.getUniqueId()) .list(); } else { studentEnrls = hibSession .createQuery("select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.owner.uniqueId=:sovlerGroupId and e.solution.commited = true") .setLong("sovlerGroupId", iSolverGroupId[idx]) .list(); } iProgress.setPhase("Loading student enrolments ["+(idx+1)+"] ...",studentEnrls.size()); for (Iterator i1=studentEnrls.iterator();i1.hasNext();) { Object o[] = (Object[])i1.next(); Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture!=null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); } } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("Global.LoadOtherCommittedStudentEnrls", true)) { // Other committed enrollments List<Object[]> enrollments = (List<Object[]>)hibSession.createQuery( "select distinct e.studentId, e.clazz.uniqueId from " + "StudentEnrollment e, Class_ c where " + "e.solution.commited = true and e.solution.owner.uniqueId not in (" + iSolverGroupIds + ") and " + "e.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")").list(); iProgress.setPhase("Loading other committed student enrolments ...", enrollments.size()); for (Object[] o: enrollments) { Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture != null && lecture.getConfiguration() != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); } } iProgress.incProgress(); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (hasRoomAvailability()) loadRoomAvailability(RoomAvailability.getInstance()); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); iProgress.setPhase("Initial sectioning ...", iOfferings.size()); for (InstructionalOffering offering: iOfferings.keySet()) { Set<Student> students = new HashSet<Student>(); for (CourseOffering course: offering.getCourseOfferings()) { Set<Student> courseStudents = iCourse2students.get(course); if (courseStudents != null) students.addAll(courseStudents); } if (students.isEmpty()) continue; InitialSectioning.initialSectioningCfg(iProgress, offering.getUniqueId(), offering.getCourseName(), students, iAltConfigurations.get(offering)); iProgress.incProgress(); } for (Enumeration e=iStudents.elements();e.hasMoreElements();) { ((Student)e.nextElement()).clearDistanceCache(); } if (!iPreEnrollments.isEmpty()) { iProgress.setPhase("Checking loaded enrollments ....", iPreEnrollments.size()); for (Map.Entry<Student, Set<Lecture>> entry: iPreEnrollments.entrySet()) { iProgress.incProgress(); Student student = entry.getKey(); Set<Lecture> lectures = entry.getValue(); for (Lecture lecture: lectures) { if (!lecture.students().contains(student)) { iProgress.message(msglevel("studentNotEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is supposed to be enrolled to " + getClassLabel(lecture)); } } for (Lecture lecture: student.getLectures()) { if (!lectures.contains(lecture)) { Lecture instead = null; if (lecture.sameStudentsLectures() != null) { for (Lecture other: lecture.sameStudentsLectures()) { if (lectures.contains(other)) instead = other; } } if (instead != null) iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + ", he/she should have " + getClassLabel(instead) + " instead."); else iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_INFO), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + "."); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); iProgress.setPhase("Computing jenrl ...",iStudents.size()); Hashtable jenrls = new Hashtable(); for (Iterator i1=iStudents.values().iterator();i1.hasNext();) { Student st = (Student)i1.next(); for (Iterator i2=st.getLectures().iterator();i2.hasNext();) { Lecture l1 = (Lecture)i2.next(); for (Iterator i3=st.getLectures().iterator();i3.hasNext();) { Lecture l2 = (Lecture)i3.next(); if (l1.getId()>=l2.getId()) continue; Hashtable x = (Hashtable)jenrls.get(l1); if (x==null) { x = new Hashtable(); jenrls.put(l1, x); } JenrlConstraint jenrl = (JenrlConstraint)x.get(l2); if (jenrl==null) { jenrl = new JenrlConstraint(); getModel().addConstraint(jenrl); jenrl.addVariable(l1); jenrl.addVariable(l2); x.put(l2, jenrl); } jenrl.incJenrl(st); } } iProgress.incProgress(); } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (solutions!=null) { for (int idx=0;idx<iSolverGroupId.length;idx++) { Solution solution = (Solution)solutions.get(iSolverGroupId[idx]); if (solution==null) continue; iProgress.setPhase("Creating initial assignment ["+(idx+1)+"] ...",solution.getAssignments().size()); for (Iterator i1=solution.getAssignments().iterator();i1.hasNext();) { Assignment assignment = (Assignment)i1.next(); loadAssignment(assignment); iProgress.incProgress(); } } } else if (iLoadCommittedAssignments) { iProgress.setPhase("Creating initial assignment ...", getModel().variables().size()); for (Lecture lecture: getModel().variables()) { if (lecture.isCommitted()) continue; Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz != null && clazz.getCommittedAssignment() != null) loadAssignment(clazz.getCommittedAssignment()); iProgress.incProgress(); } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iSpread) { iProgress.setPhase("Posting automatic spread constraints ...", subparts.size()); for (SchedulingSubpart subpart: subparts) { if (subpart.getClasses().size()<=1) { iProgress.incProgress(); continue; } if (!subpart.isAutoSpreadInTime().booleanValue()) { iProgress.debug("Automatic spread constraint disabled for "+getSubpartLabel(subpart)); iProgress.incProgress(); continue; } SpreadConstraint spread = new SpreadConstraint(getModel().getProperties(),subpart.getCourseName()+" "+subpart.getItypeDesc().trim()); for (Iterator i2=subpart.getClasses().iterator();i2.hasNext();) { Class_ clazz = (Class_)i2.next(); Lecture lecture = (Lecture)getLecture(clazz); if (lecture==null) continue; spread.addVariable(lecture); } if (spread.variables().isEmpty()) iProgress.message(msglevel("courseWithNoClasses", Progress.MSGLEVEL_WARN), "No class for course "+getSubpartLabel(subpart)); else getModel().addConstraint(spread); iProgress.incProgress(); } } if (iDeptBalancing) { iProgress.setPhase("Creating dept. spread constraints ...",getModel().variables().size()); Hashtable<Long, DepartmentSpreadConstraint> depSpreadConstraints = new Hashtable<Long, DepartmentSpreadConstraint>(); for (Lecture lecture: getModel().variables()) { if (lecture.getDepartment()==null) continue; DepartmentSpreadConstraint deptConstr = (DepartmentSpreadConstraint)depSpreadConstraints.get(lecture.getDepartment()); if (deptConstr==null) { deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(),lecture.getDepartment(),(String)iDeptNames.get(lecture.getDepartment())); depSpreadConstraints.put(lecture.getDepartment(),deptConstr); getModel().addConstraint(deptConstr); } deptConstr.addVariable(lecture); iProgress.incProgress(); } } if (iSubjectBalancing) { iProgress.setPhase("Creating subject spread constraints ...",getModel().variables().size()); Hashtable<Long, SpreadConstraint> subjectSpreadConstraints = new Hashtable<Long, SpreadConstraint>(); for (Lecture lecture: getModel().variables()) { Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz == null) continue; for (CourseOffering co: clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getCourseOfferings()) { Long subject = co.getSubjectArea().getUniqueId(); SpreadConstraint subjectSpreadConstr = subjectSpreadConstraints.get(subject); if (subjectSpreadConstr==null) { subjectSpreadConstr = new SpreadConstraint(getModel().getProperties(), co.getSubjectArea().getSubjectAreaAbbreviation()); subjectSpreadConstraints.put(subject, subjectSpreadConstr); getModel().addConstraint(subjectSpreadConstr); } subjectSpreadConstr.addVariable(lecture); } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true)) purgeInvalidValues(); for (Constraint c: getModel().constraints()) { if (c instanceof SpreadConstraint) ((SpreadConstraint)c).init(); if (c instanceof DiscouragedRoomConstraint) ((DiscouragedRoomConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedRoomsConstraint) ((MinimizeNumberOfUsedRoomsConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedGroupsOfTime) ((MinimizeNumberOfUsedGroupsOfTime)c).setEnabled(true); } iProgress.setPhase("Checking for inconsistencies...", getModel().variables().size()); for (Lecture lecture: getModel().variables()) { iProgress.incProgress(); for (Iterator i=lecture.students().iterator();i.hasNext();) { Student s = (Student)i.next(); if (!s.canEnroll(lecture)) iProgress.message(msglevel("badStudentEnrollment", Progress.MSGLEVEL_INFO), "Invalid student enrollment of student "+s.getId()+" in class "+getClassLabel(lecture)+" found."); } //check same instructor constraint if (!lecture.values().isEmpty() && lecture.timeLocations().size()==1 && !lecture.getInstructorConstraints().isEmpty()) { for (Lecture other: getModel().variables()) { if (other.values().isEmpty() || other.timeLocations().size()!=1 || lecture.getClassId().compareTo(other.getClassId())<=0) continue; Placement p1 = lecture.values().get(0); Placement p2 = other.values().get(0); if (!other.getInstructorConstraints().isEmpty()) { for (InstructorConstraint ic: lecture.getInstructorConstraints()) { if (!other.getInstructorConstraints().contains(ic)) continue; if (p1.canShareRooms(p2) && p1.sameRooms(p2)) continue; if (p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) { iProgress.message(msglevel("reqInstructorOverlap", Progress.MSGLEVEL_WARN), "Same instructor and overlapping time required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } else if (ic.getDistancePreference(p1,p2)==PreferenceLevel.sIntLevelProhibited && lecture.roomLocations().size()==1 && other.roomLocations().size()==1) { iProgress.message(msglevel("reqInstructorBackToBack", Progress.MSGLEVEL_WARN), "Same instructor, back-to-back time and rooms too far (distance="+Math.round(10.0*Placement.getDistanceInMeters(getModel().getDistanceMetric(),p1,p2))+"m) required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } } } } } if (!lecture.isSingleton()) continue; for (Lecture other: getModel().variables()) { if (!other.isSingleton() || lecture.getClassId().compareTo(other.getClassId())<=0) continue; Placement p1 = lecture.values().get(0); Placement p2 = other.values().get(0); if (p1.shareRooms(p2) && p1.getTimeLocation().hasIntersection(p2.getTimeLocation()) && !p1.canShareRooms(p2)) { iProgress.message(msglevel("reqRoomOverlap", Progress.MSGLEVEL_WARN), "Same room and overlapping time required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } } if (lecture.getAssignment()==null) { Placement placement = lecture.values().get(0); if (!placement.isValid()) { String reason = ""; for (InstructorConstraint ic: lecture.getInstructorConstraints()) { if (!ic.isAvailable(lecture, placement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;instructor "+ic.getName()+" not available"; } if (lecture.getNrRooms()>0) { if (placement.isMultiRoom()) { for (RoomLocation roomLocation: placement.getRoomLocations()) { if (!roomLocation.getRoomConstraint().isAvailable(lecture,placement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+roomLocation.getName()+" not available"; } } else { if (!placement.getRoomLocation().getRoomConstraint().isAvailable(lecture,placement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+placement.getRoomLocation().getName()+" not available"; } } Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(placement); if (!conflictConstraints.isEmpty()) { for (Constraint<Lecture, Placement> c: conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement p: vals) { Lecture l = p.variable(); if (l.isCommitted()) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;conflict with committed assignment "+getClassLabel(l)+" = "+p.getLongName()+" (in constraint "+c+")"; if (p.equals(placement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;constraint "+c; } } } iProgress.message(msglevel("reqInvalidPlacement", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(lecture)+" requires an invalid placement "+placement.getLongName()+(reason.length()==0?".":":"+reason)); } else if (iAssignSingleton && getModel().conflictValues(placement).isEmpty()) lecture.assign(0, placement); } } if (getModel().getProperties().getPropertyBoolean("General.EnrollmentCheck", true)) new EnrollmentCheck(getModel(), msglevel("enrollmentCheck", Progress.MSGLEVEL_WARN)).checkStudentEnrollments(iProgress); if (getModel().getProperties().getPropertyBoolean("General.SwitchStudents",true) && !getModel().assignedVariables().isEmpty() && !iLoadStudentEnrlsFromSolution) getModel().switchStudents(); iProgress.setPhase("Done",1);iProgress.incProgress(); iProgress.message(msglevel("allDone", Progress.MSGLEVEL_INFO), "Model successfully loaded."); }
private void load(org.hibernate.Session hibSession) throws Exception { iProgress.setStatus("Loading input data ..."); SolverGroupDAO dao = new SolverGroupDAO(); hibSession = dao.getSession(); hibSession.setFlushMode(FlushMode.COMMIT); iSolverGroup = null; iSession = null; if (iSolverGroup==null) { iSolverGroup = new SolverGroup[iSolverGroupId.length]; for (int i=0;i<iSolverGroupId.length;i++) { iSolverGroup[i] = dao.get(iSolverGroupId[i], hibSession); if (iSolverGroup[i]==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solver group "+iSolverGroupId[i]+"."); return; } iProgress.debug("solver group["+(i+1)+"]: "+iSolverGroup[i].getName()); } } if (iSolverGroup==null || iSolverGroup.length==0) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No solver group loaded."); return; } iDepartmentIds = ""; for (int j=0;j<iSolverGroup.length;j++) { for (Iterator i=iSolverGroup[j].getDepartments().iterator();i.hasNext();) { Department d = (Department)i.next(); if (iDepartmentIds.length()>0) iDepartmentIds += ","; iDepartmentIds += d.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.DepartmentIds",iDepartmentIds); Hashtable<Long, Solution> solutions = null; if (iSolutionId!=null && iSolutionId.length>0) { solutions = new Hashtable<Long, Solution>(); String note=""; for (int i=0;i<iSolutionId.length;i++) { Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession); if (solution==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solution "+iSolutionId[i]+"."); return; } iProgress.debug("solution["+(i+1)+"] version: "+solution.getUniqueId()+" (created "+solution.getCreated()+", solver group "+solution.getOwner().getName()+")"); if (solution.getNote()!=null) { if (note.length()>0) note += "\n"; note += solution.getNote(); } solutions.put(solution.getOwner().getUniqueId(),solution); } getModel().getProperties().setProperty("General.Note",note); String solutionIdStr = ""; for (int i=0;i<iSolverGroupId.length;i++) { Solution solution = solutions.get(iSolverGroupId[i]); if (solution!=null) { if (solutionIdStr.length()>0) solutionIdStr += ","; solutionIdStr += solution.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.SolutionId",solutionIdStr); } if (iSession==null) iSession = (new SessionDAO()).get(iSessionId, hibSession); if (iSession==null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No session loaded."); return; } iProgress.debug("session: "+iSession.getLabel()); getModel().getProperties().setProperty("Data.Term",iSession.getAcademicYearTerm()); getModel().getProperties().setProperty("Data.Initiative",iSession.getAcademicInitiative()); getModel().setYear(iSession.getSessionStartYear()); getModel().getProperties().setProperty("DatePattern.DayOfWeekOffset", String.valueOf( Constants.getDayOfWeek(DateUtils.getDate(1, iSession.getPatternStartMonth(), iSession.getSessionStartYear())))); iAllClasses = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (int i=0;i<iSolverGroup.length;i++) { for (Iterator j=iSolverGroup[i].getDepartments().iterator();j.hasNext();) { Department d = (Department)j.next(); iAllClasses.addAll(d.getClassesFetchWithStructure()); } } if (iAllClasses==null || iAllClasses.isEmpty()) { iProgress.message(msglevel("noClasses", Progress.MSGLEVEL_FATAL), "No classes to load."); return; } iProgress.debug("classes to load: "+iAllClasses.size()); for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getInstrOfferingConfigs()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getInstrOfferingConfig().getSchedulingSubparts()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getSchedulingSubpart().getClasses()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getClassInstructors()); } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); for (Iterator j=c.getClassInstructors().iterator();j.hasNext();) { ClassInstructor ci = (ClassInstructor)j.next(); Hibernate.initialize(ci.getInstructor()); } } for (Iterator i=iAllClasses.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Hibernate.initialize(c.getPreferences()); Hibernate.initialize(c.getSchedulingSubpart().getPreferences()); for (Iterator j=c.getClassInstructors().iterator();j.hasNext();) { ClassInstructor ci = (ClassInstructor)j.next(); Hibernate.initialize(ci.getInstructor().getPreferences()); } c.getControllingDept().getPreferences(); c.getManagingDept().getPreferences(); } iProgress.setPhase("Loading classes ...",iAllClasses.size()); int ord = 0; HashSet<SchedulingSubpart> subparts = new HashSet<SchedulingSubpart>(); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = loadClass(clazz,hibSession); subparts.add(clazz.getSchedulingSubpart()); if (lecture!=null) lecture.setOrd(ord++); iClasses.put(clazz.getUniqueId(),clazz); iProgress.incProgress(); } loadInstructorAvailabilities(hibSession); loadRoomAvailabilities(hibSession); iProgress.setPhase("Loading offerings ...", iAllClasses.size()); Set<Long> loadedOfferings = new HashSet<Long>(); for (Class_ clazz: iAllClasses) { Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); iProgress.incProgress(); if (lecture==null) continue; //skip classes that were not loaded InstructionalOffering offering = clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering(); if (!loadedOfferings.add(offering.getUniqueId())) continue; // already loaded iOfferings.put(offering, loadOffering(offering, false)); } /* // old code, replaced by Loading offerings ... part iProgress.setPhase("Setting parent classes ...",iLectures.size()); Hashtable<SchedulingSubpart, List<Lecture>> subparts = new Hashtable<SchedulingSubpart, List<Lecture>>(); Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> offerings = new Hashtable<InstructionalOffering, Hashtable<InstrOfferingConfig,Set<SchedulingSubpart>>>(); Hashtable<InstrOfferingConfig, Configuration> configurations = new Hashtable<InstrOfferingConfig, Configuration>(); Hashtable<InstructionalOffering, List<Configuration>> altConfigurations = new Hashtable<InstructionalOffering, List<Configuration>>(); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture==null) continue; //skip classes that were not loaded Class_ parentClazz = clazz.getParentClass(); if (parentClazz!=null) { Lecture parentLecture = null; Class_ c = clazz; while ((parentLecture==null || parentLecture.isCommitted()) && c.getParentClass()!=null) { c = c.getParentClass(); parentLecture = (Lecture)iLectures.get(c.getUniqueId()); } if (parentLecture!=null && !parentLecture.isCommitted()) lecture.setParent(parentLecture); } SchedulingSubpart subpart = clazz.getSchedulingSubpart(); InstrOfferingConfig config = subpart.getInstrOfferingConfig(); InstructionalOffering offering = config.getInstructionalOffering(); iSubparts.put(subpart.getUniqueId(),subpart); if (lecture.getParent()==null) { Configuration cfg = configurations.get(config); if (cfg==null) { cfg = new Configuration(offering.getUniqueId(), config.getUniqueId(), config.getLimit().intValue()); configurations.put(config, cfg); List<Configuration> altCfgs = altConfigurations.get(offering); if (altCfgs==null) { altCfgs = new ArrayList<Configuration>(); altConfigurations.put(offering, altCfgs); } altCfgs.add(cfg); cfg.setAltConfigurations(altCfgs); } lecture.setConfiguration(cfg); Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = offerings.get(offering); if (topSubparts==null) { topSubparts = new Hashtable(); offerings.put(offering,topSubparts); } Set<SchedulingSubpart> topSubpartsThisConfig = topSubparts.get(config); if (topSubpartsThisConfig==null) { topSubpartsThisConfig = new HashSet<SchedulingSubpart>(); topSubparts.put(config, topSubpartsThisConfig); } topSubpartsThisConfig.add(clazz.getSchedulingSubpart()); } List<Lecture> sameSubpart = subparts.get(clazz.getSchedulingSubpart()); if (sameSubpart==null) { sameSubpart = new ArrayList<Lecture>(); subparts.put(clazz.getSchedulingSubpart(), sameSubpart); } sameSubpart.add(lecture); lecture.setSameSubpartLectures(sameSubpart); iProgress.incProgress(); } */ List<DistributionPref> distPrefs = new ArrayList<DistributionPref>(); for (int i=0;i<iSolverGroup.length;i++) { distPrefs.addAll(iSolverGroup[i].getDistributionPreferences()); } iProgress.setPhase("Loading distribution preferences ...",distPrefs.size()); Hibernate.initialize(distPrefs); // Commented out for speeding up issues (calling just // Hibernate.initialize(distPrefs) instead) // May need to call Hibernate.initialize on committed classed // in getLecture(Class_) if this will cause issues. /* for (Iterator i=distPrefs.iterator();i.hasNext();) { DistributionPref distributionPref = (DistributionPref)i.next(); Hibernate.initialize(distributionPref.getDistributionObjects()); } */ for (Iterator i=distPrefs.iterator();i.hasNext();) { DistributionPref distributionPref = (DistributionPref)i.next(); if (!PreferenceLevel.sNeutral.equals(distributionPref.getPrefLevel().getPrefProlog())) loadGroupConstraint(distributionPref); iProgress.incProgress(); } for (int i=0;i<iSolverGroup.length;i++) { for (Iterator j=iSolverGroup[i].getDepartments().iterator();j.hasNext();) { loadInstructorGroupConstraints((Department)j.next(), hibSession); } } if (iAutoSameStudents) { iProgress.setPhase("Posting automatic same_students constraints ...",iAllClasses.size()); for (Iterator i1=iAllClasses.iterator();i1.hasNext();) { Class_ clazz = (Class_)i1.next(); Lecture lecture = (Lecture)iLectures.get(clazz.getUniqueId()); if (lecture==null) continue; if (!lecture.hasAnyChildren()) postSameStudentConstraint(clazz, iAutoSameStudentsConstraint); iProgress.incProgress(); } } assignCommited(); iProgress.setPhase("Posting class limit constraints ...", iOfferings.size()); for (Map.Entry<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> entry: iOfferings.entrySet()) { Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = entry.getValue(); for (Map.Entry<InstrOfferingConfig, Set<SchedulingSubpart>> subpartEntry: topSubparts.entrySet()) { InstrOfferingConfig config = subpartEntry.getKey(); Set<SchedulingSubpart> topSubpartsThisConfig = subpartEntry.getValue(); for (SchedulingSubpart subpart: topSubpartsThisConfig) { boolean isMakingSense = false; for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null) continue; createChildrenClassLimitConstraits(lecture); if (!lecture.isCommitted() && lecture.minClassLimit() != lecture.maxClassLimit()) isMakingSense=true; } if (!isMakingSense) continue; if (subpart.getParentSubpart()==null) { ClassLimitConstraint clc = new ClassLimitConstraint(config.getLimit(), getClassLimitConstraitName(subpart)); for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit()); continue; } clc.addVariable(lecture); } if (clc.variables().isEmpty()) continue; iProgress.trace("Added constraint "+clc.getName()+" between "+clc.variables()); getModel().addConstraint(clc); } else { Hashtable<Long, ClassLimitConstraint> clcs = new Hashtable<Long, ClassLimitConstraint>(); for (Class_ clazz: subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); Class_ parentClazz = clazz.getParentClass(); ClassLimitConstraint clc = clcs.get(parentClazz.getUniqueId()); if (clc == null) { clc = new ClassLimitConstraint(parentClazz.getClassLimit(), parentClazz.getClassLabel()); clcs.put(parentClazz.getUniqueId(), clc); } if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta()-clazz.getClassLimit()); } else { clc.addVariable(lecture); } } for (ClassLimitConstraint clc: clcs.values()) { if (!clc.variables().isEmpty()) { iProgress.trace("Added constraint "+clc.getName()+" between "+clc.variables()); getModel().addConstraint(clc); } } } } } iProgress.incProgress(); } iStudentCourseDemands.init(hibSession, iProgress, iSession, iOfferings.keySet()); iProgress.setPhase("Loading students ...",iOfferings.size()); for (InstructionalOffering offering: iOfferings.keySet()) { int totalCourseLimit = 0; for (CourseOffering course: offering.getCourseOfferings()) { int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1) courseLimit = offering.getLimit(); else { iProgress.message(msglevel("crossListWithoutReservation", Progress.MSGLEVEL_WARN), "Cross-listed course "+getOfferingLabel(course)+" does not have any course reservation."); if (course.getProjectedDemand() != null) courseLimit = course.getProjectedDemand(); else if (course.getDemand() != null) courseLimit = course.getDemand(); else courseLimit = 0; } } totalCourseLimit += courseLimit; } Double factor = null; if (totalCourseLimit < offering.getLimit()) iProgress.message(msglevel("courseReservationsBelowLimit", Progress.MSGLEVEL_WARN), "Total number of course reservations is below the offering limit for instructional offering "+getOfferingLabel(offering)+" ("+totalCourseLimit+"<"+offering.getLimit().intValue()+")."); if (totalCourseLimit > offering.getLimit().intValue()) iProgress.message(msglevel("courseReservationsOverLimit", Progress.MSGLEVEL_INFO), "Total number of course reservations exceeds the offering limit for instructional offering "+getOfferingLabel(offering)+" ("+totalCourseLimit+">"+offering.getLimit().intValue()+")."); if (totalCourseLimit == 0) continue; if (totalCourseLimit != offering.getLimit()) factor = new Double(((double)offering.getLimit()) / totalCourseLimit); for (CourseOffering course: offering.getCourseOfferings()) { Set<WeightedStudentId> studentIds = iStudentCourseDemands.getDemands(course); float studentWeight = 0.0f; if (studentIds != null) for (WeightedStudentId studentId: studentIds) studentWeight += studentId.getWeight(); int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1) courseLimit = offering.getLimit().intValue(); else { courseLimit = Math.round(studentWeight); } } if (factor!=null) courseLimit = (int)Math.round(courseLimit * factor); if (studentIds == null || studentIds.isEmpty()) { iProgress.message(msglevel("offeringWithoutDemand", Progress.MSGLEVEL_INFO), "No student enrollments for offering "+getOfferingLabel(course)+"."); continue; } if (courseLimit == 0) { iProgress.message(msglevel("noCourseReservation", Progress.MSGLEVEL_WARN), "No reserved space for students of offering "+getOfferingLabel(course)+"."); } double weight = (iStudentCourseDemands.isWeightStudentsToFillUpOffering() && courseLimit != 0 ? (double)courseLimit / studentWeight : 1.0); Set<Lecture> cannotAttendLectures = null; if (offering.getCourseOfferings().size() > 1) { Set<Long> reservedClasses = new HashSet<Long>(); int limit = 0; boolean unlimited = false; for (Reservation r: offering.getReservations()) { if (r instanceof CourseReservation && course.equals(((CourseReservation)r).getCourse())) { for (Class_ clazz: r.getClasses()) { limit += clazz.getMaxExpectedCapacity(); propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config: r.getConfigurations()) { if (config.isUnlimitedEnrollment()) unlimited = true; else limit += config.getLimit(); for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } } if (!reservedClasses.isEmpty()) { iProgress.debug("Course requests for course "+getOfferingLabel(course)+" are "+reservedClasses); if (!unlimited && courseLimit > limit) iProgress.message(msglevel("insufficientCourseReservation", Progress.MSGLEVEL_WARN), "Too little space reserved in for course "+getOfferingLabel(course)+" ("+limit+"<"+courseLimit+")."); cannotAttendLectures = new HashSet<Lecture>(); for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz: subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) cannotAttendLectures.add(lecture); } } } if (!cannotAttendLectures.isEmpty()) { iProgress.debug("Prohibited lectures for course " + getOfferingLabel(course)+" are " + cannotAttendLectures); checkReservation(course, cannotAttendLectures, iAltConfigurations.get(offering)); } } } for (WeightedStudentId studentId: studentIds) { Student student = iStudents.get(studentId.getStudentId()); if (student==null) { student = new Student(studentId.getStudentId()); student.setAcademicArea(studentId.getArea()); student.setAcademicClassification(studentId.getClasf()); student.setMajor(studentId.getMajor()); student.setCurriculum(studentId.getCurriculum()); getModel().addStudent(student); iStudents.put(studentId.getStudentId(), student); } student.addOffering(offering.getUniqueId(), weight * studentId.getWeight()); Set<Student> students = iCourse2students.get(course); if (students==null) { students = new HashSet<Student>(); iCourse2students.put(course,students); } students.add(student); student.addCanNotEnroll(offering.getUniqueId(), cannotAttendLectures); Set<Long> reservedClasses = new HashSet<Long>(); for (Reservation reservation: offering.getReservations()) { if (reservation.getClasses().isEmpty() && reservation.getConfigurations().isEmpty()) continue; if (reservation instanceof CourseReservation) continue; if (reservation instanceof CurriculumReservation) { CurriculumReservation cr = (CurriculumReservation)reservation; if (student.getAcademicArea() == null) continue; if (!cr.getArea().getAcademicAreaAbbreviation().equals(student.getAcademicArea())) continue; if (!cr.getClassifications().isEmpty()) { boolean match = false; for (AcademicClassification clasf: cr.getClassifications()) { if (clasf.getCode().equals(student.getAcademicClassification())) { match = true; break; } } if (!match) continue; } if (!cr.getMajors().isEmpty()) { if (student.getMajor() == null) continue; if (!student.getMajor().isEmpty()) { boolean match = false; majors: for (PosMajor major: cr.getMajors()) { for (String code: student.getMajor().split("\\|")) { if (major.getCode().equals(code)) { match = true; break majors; } } } if (!match) continue; } } } else continue; for (Class_ clazz: reservation.getClasses()) { propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config: reservation.getConfigurations()) { for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } if (!reservedClasses.isEmpty()) { iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " has reserved classes " + reservedClasses); Set<Lecture> prohibited = new HashSet<Lecture>(); for (InstrOfferingConfig config: course.getInstructionalOffering().getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart: config.getSchedulingSubparts()) for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart: config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz: subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz: subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) prohibited.add(lecture); } } } iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " cannot attend classes " + prohibited); student.addCanNotEnroll(offering.getUniqueId(), prohibited); } } } iProgress.incProgress(); } iProgress.debug(iStudents.size()+" students loaded."); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iCommittedStudentConflictsMode == CommittedStudentConflictsMode.Load && !iStudentCourseDemands.isMakingUpStudents()) loadCommittedStudentConflicts(hibSession, loadedOfferings); else if (iCommittedStudentConflictsMode != CommittedStudentConflictsMode.Ignore) makeupCommittedStudentConflicts(loadedOfferings); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); Hashtable<Student, Set<Lecture>> iPreEnrollments = new Hashtable<Student, Set<Lecture>>(); if (iLoadStudentEnrlsFromSolution) { if (iStudentCourseDemands.canUseStudentClassEnrollmentsAsSolution()) { // Load real student enrollments (not saved last-like) List<Object[]> enrollments = (List<Object[]>)hibSession.createQuery( "select distinct e.student.uniqueId, e.clazz.uniqueId from " + "StudentClassEnrollment e, Class_ c where " + "e.courseOffering.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")").list(); iProgress.setPhase("Loading current student enrolments ...", enrollments.size()); int totalEnrollments = 0; for (Object[] o: enrollments) { Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture!=null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); totalEnrollments ++; } } iProgress.incProgress(); } iProgress.message(msglevel("enrollmentsLoaded", Progress.MSGLEVEL_INFO), "Loaded " + totalEnrollments + " enrollments of " + iPreEnrollments.size() + " students."); } else { // Load enrollments from selected / committed solutions for (int idx=0;idx<iSolverGroupId.length;idx++) { Solution solution = (solutions == null ? null : solutions.get(iSolverGroupId[idx])); List studentEnrls = null; if (solution != null) { studentEnrls = hibSession .createQuery("select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.uniqueId=:solutionId") .setLong("solutionId", solution.getUniqueId()) .list(); } else { studentEnrls = hibSession .createQuery("select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.owner.uniqueId=:sovlerGroupId and e.solution.commited = true") .setLong("sovlerGroupId", iSolverGroupId[idx]) .list(); } iProgress.setPhase("Loading student enrolments ["+(idx+1)+"] ...",studentEnrls.size()); for (Iterator i1=studentEnrls.iterator();i1.hasNext();) { Object o[] = (Object[])i1.next(); Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture != null && lecture.getConfiguration() != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); } } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("Global.LoadOtherCommittedStudentEnrls", true)) { // Other committed enrollments List<Object[]> enrollments = (List<Object[]>)hibSession.createQuery( "select distinct e.studentId, e.clazz.uniqueId from " + "StudentEnrollment e, Class_ c where " + "e.solution.commited = true and e.solution.owner.uniqueId not in (" + iSolverGroupIds + ") and " + "e.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")").list(); iProgress.setPhase("Loading other committed student enrolments ...", enrollments.size()); for (Object[] o: enrollments) { Long studentId = (Long)o[0]; Long clazzId = (Long)o[1]; Student student = (Student)iStudents.get(studentId); if (student==null) continue; Lecture lecture = (Lecture)iLectures.get(clazzId); if (lecture != null && lecture.getConfiguration() != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(student); } } iProgress.incProgress(); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (hasRoomAvailability()) loadRoomAvailability(RoomAvailability.getInstance()); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); iProgress.setPhase("Initial sectioning ...", iOfferings.size()); for (InstructionalOffering offering: iOfferings.keySet()) { Set<Student> students = new HashSet<Student>(); for (CourseOffering course: offering.getCourseOfferings()) { Set<Student> courseStudents = iCourse2students.get(course); if (courseStudents != null) students.addAll(courseStudents); } if (students.isEmpty()) continue; InitialSectioning.initialSectioningCfg(iProgress, offering.getUniqueId(), offering.getCourseName(), students, iAltConfigurations.get(offering)); iProgress.incProgress(); } for (Enumeration e=iStudents.elements();e.hasMoreElements();) { ((Student)e.nextElement()).clearDistanceCache(); } if (!iPreEnrollments.isEmpty()) { iProgress.setPhase("Checking loaded enrollments ....", iPreEnrollments.size()); for (Map.Entry<Student, Set<Lecture>> entry: iPreEnrollments.entrySet()) { iProgress.incProgress(); Student student = entry.getKey(); Set<Lecture> lectures = entry.getValue(); for (Lecture lecture: lectures) { if (!lecture.students().contains(student)) { iProgress.message(msglevel("studentNotEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is supposed to be enrolled to " + getClassLabel(lecture)); } } for (Lecture lecture: student.getLectures()) { if (!lectures.contains(lecture)) { Lecture instead = null; if (lecture.sameStudentsLectures() != null) { for (Lecture other: lecture.sameStudentsLectures()) { if (lectures.contains(other)) instead = other; } } if (instead != null) iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + ", he/she should have " + getClassLabel(instead) + " instead."); else iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_INFO), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + "."); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); iProgress.setPhase("Computing jenrl ...",iStudents.size()); Hashtable jenrls = new Hashtable(); for (Iterator i1=iStudents.values().iterator();i1.hasNext();) { Student st = (Student)i1.next(); for (Iterator i2=st.getLectures().iterator();i2.hasNext();) { Lecture l1 = (Lecture)i2.next(); for (Iterator i3=st.getLectures().iterator();i3.hasNext();) { Lecture l2 = (Lecture)i3.next(); if (l1.getId()>=l2.getId()) continue; Hashtable x = (Hashtable)jenrls.get(l1); if (x==null) { x = new Hashtable(); jenrls.put(l1, x); } JenrlConstraint jenrl = (JenrlConstraint)x.get(l2); if (jenrl==null) { jenrl = new JenrlConstraint(); getModel().addConstraint(jenrl); jenrl.addVariable(l1); jenrl.addVariable(l2); x.put(l2, jenrl); } jenrl.incJenrl(st); } } iProgress.incProgress(); } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (solutions!=null) { for (int idx=0;idx<iSolverGroupId.length;idx++) { Solution solution = (Solution)solutions.get(iSolverGroupId[idx]); if (solution==null) continue; iProgress.setPhase("Creating initial assignment ["+(idx+1)+"] ...",solution.getAssignments().size()); for (Iterator i1=solution.getAssignments().iterator();i1.hasNext();) { Assignment assignment = (Assignment)i1.next(); loadAssignment(assignment); iProgress.incProgress(); } } } else if (iLoadCommittedAssignments) { iProgress.setPhase("Creating initial assignment ...", getModel().variables().size()); for (Lecture lecture: getModel().variables()) { if (lecture.isCommitted()) continue; Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz != null && clazz.getCommittedAssignment() != null) loadAssignment(clazz.getCommittedAssignment()); iProgress.incProgress(); } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iSpread) { iProgress.setPhase("Posting automatic spread constraints ...", subparts.size()); for (SchedulingSubpart subpart: subparts) { if (subpart.getClasses().size()<=1) { iProgress.incProgress(); continue; } if (!subpart.isAutoSpreadInTime().booleanValue()) { iProgress.debug("Automatic spread constraint disabled for "+getSubpartLabel(subpart)); iProgress.incProgress(); continue; } SpreadConstraint spread = new SpreadConstraint(getModel().getProperties(),subpart.getCourseName()+" "+subpart.getItypeDesc().trim()); for (Iterator i2=subpart.getClasses().iterator();i2.hasNext();) { Class_ clazz = (Class_)i2.next(); Lecture lecture = (Lecture)getLecture(clazz); if (lecture==null) continue; spread.addVariable(lecture); } if (spread.variables().isEmpty()) iProgress.message(msglevel("courseWithNoClasses", Progress.MSGLEVEL_WARN), "No class for course "+getSubpartLabel(subpart)); else getModel().addConstraint(spread); iProgress.incProgress(); } } if (iDeptBalancing) { iProgress.setPhase("Creating dept. spread constraints ...",getModel().variables().size()); Hashtable<Long, DepartmentSpreadConstraint> depSpreadConstraints = new Hashtable<Long, DepartmentSpreadConstraint>(); for (Lecture lecture: getModel().variables()) { if (lecture.getDepartment()==null) continue; DepartmentSpreadConstraint deptConstr = (DepartmentSpreadConstraint)depSpreadConstraints.get(lecture.getDepartment()); if (deptConstr==null) { deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(),lecture.getDepartment(),(String)iDeptNames.get(lecture.getDepartment())); depSpreadConstraints.put(lecture.getDepartment(),deptConstr); getModel().addConstraint(deptConstr); } deptConstr.addVariable(lecture); iProgress.incProgress(); } } if (iSubjectBalancing) { iProgress.setPhase("Creating subject spread constraints ...",getModel().variables().size()); Hashtable<Long, SpreadConstraint> subjectSpreadConstraints = new Hashtable<Long, SpreadConstraint>(); for (Lecture lecture: getModel().variables()) { Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz == null) continue; for (CourseOffering co: clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getCourseOfferings()) { Long subject = co.getSubjectArea().getUniqueId(); SpreadConstraint subjectSpreadConstr = subjectSpreadConstraints.get(subject); if (subjectSpreadConstr==null) { subjectSpreadConstr = new SpreadConstraint(getModel().getProperties(), co.getSubjectArea().getSubjectAreaAbbreviation()); subjectSpreadConstraints.put(subject, subjectSpreadConstr); getModel().addConstraint(subjectSpreadConstr); } subjectSpreadConstr.addVariable(lecture); } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true)) purgeInvalidValues(); for (Constraint c: getModel().constraints()) { if (c instanceof SpreadConstraint) ((SpreadConstraint)c).init(); if (c instanceof DiscouragedRoomConstraint) ((DiscouragedRoomConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedRoomsConstraint) ((MinimizeNumberOfUsedRoomsConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedGroupsOfTime) ((MinimizeNumberOfUsedGroupsOfTime)c).setEnabled(true); } iProgress.setPhase("Checking for inconsistencies...", getModel().variables().size()); for (Lecture lecture: getModel().variables()) { iProgress.incProgress(); for (Iterator i=lecture.students().iterator();i.hasNext();) { Student s = (Student)i.next(); if (!s.canEnroll(lecture)) iProgress.message(msglevel("badStudentEnrollment", Progress.MSGLEVEL_INFO), "Invalid student enrollment of student "+s.getId()+" in class "+getClassLabel(lecture)+" found."); } //check same instructor constraint if (!lecture.values().isEmpty() && lecture.timeLocations().size()==1 && !lecture.getInstructorConstraints().isEmpty()) { for (Lecture other: getModel().variables()) { if (other.values().isEmpty() || other.timeLocations().size()!=1 || lecture.getClassId().compareTo(other.getClassId())<=0) continue; Placement p1 = lecture.values().get(0); Placement p2 = other.values().get(0); if (!other.getInstructorConstraints().isEmpty()) { for (InstructorConstraint ic: lecture.getInstructorConstraints()) { if (!other.getInstructorConstraints().contains(ic)) continue; if (p1.canShareRooms(p2) && p1.sameRooms(p2)) continue; if (p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) { iProgress.message(msglevel("reqInstructorOverlap", Progress.MSGLEVEL_WARN), "Same instructor and overlapping time required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } else if (ic.getDistancePreference(p1,p2)==PreferenceLevel.sIntLevelProhibited && lecture.roomLocations().size()==1 && other.roomLocations().size()==1) { iProgress.message(msglevel("reqInstructorBackToBack", Progress.MSGLEVEL_WARN), "Same instructor, back-to-back time and rooms too far (distance="+Math.round(10.0*Placement.getDistanceInMeters(getModel().getDistanceMetric(),p1,p2))+"m) required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } } } } } if (!lecture.isSingleton()) continue; for (Lecture other: getModel().variables()) { if (!other.isSingleton() || lecture.getClassId().compareTo(other.getClassId())<=0) continue; Placement p1 = lecture.values().get(0); Placement p2 = other.values().get(0); if (p1.shareRooms(p2) && p1.getTimeLocation().hasIntersection(p2.getTimeLocation()) && !p1.canShareRooms(p2)) { iProgress.message(msglevel("reqRoomOverlap", Progress.MSGLEVEL_WARN), "Same room and overlapping time required:"+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(lecture)+" &larr; "+p1.getLongName()+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;"+getClassLabel(other)+" &larr; "+p2.getLongName()); } } if (lecture.getAssignment()==null) { Placement placement = lecture.values().get(0); if (!placement.isValid()) { String reason = ""; for (InstructorConstraint ic: lecture.getInstructorConstraints()) { if (!ic.isAvailable(lecture, placement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;instructor "+ic.getName()+" not available"; } if (lecture.getNrRooms()>0) { if (placement.isMultiRoom()) { for (RoomLocation roomLocation: placement.getRoomLocations()) { if (!roomLocation.getRoomConstraint().isAvailable(lecture,placement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+roomLocation.getName()+" not available"; } } else { if (!placement.getRoomLocation().getRoomConstraint().isAvailable(lecture,placement.getTimeLocation(),lecture.getScheduler())) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;room "+placement.getRoomLocation().getName()+" not available"; } } Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(placement); if (!conflictConstraints.isEmpty()) { for (Constraint<Lecture, Placement> c: conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement p: vals) { Lecture l = p.variable(); if (l.isCommitted()) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;conflict with committed assignment "+getClassLabel(l)+" = "+p.getLongName()+" (in constraint "+c+")"; if (p.equals(placement)) reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;constraint "+c; } } } iProgress.message(msglevel("reqInvalidPlacement", Progress.MSGLEVEL_WARN), "Class "+getClassLabel(lecture)+" requires an invalid placement "+placement.getLongName()+(reason.length()==0?".":":"+reason)); } else if (iAssignSingleton && getModel().conflictValues(placement).isEmpty()) lecture.assign(0, placement); } } if (getModel().getProperties().getPropertyBoolean("General.EnrollmentCheck", true)) new EnrollmentCheck(getModel(), msglevel("enrollmentCheck", Progress.MSGLEVEL_WARN)).checkStudentEnrollments(iProgress); if (getModel().getProperties().getPropertyBoolean("General.SwitchStudents",true) && !getModel().assignedVariables().isEmpty() && !iLoadStudentEnrlsFromSolution) getModel().switchStudents(); iProgress.setPhase("Done",1);iProgress.incProgress(); iProgress.message(msglevel("allDone", Progress.MSGLEVEL_INFO), "Model successfully loaded."); }
diff --git a/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java b/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java index 8e162f76d..9e7faf8df 100644 --- a/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java +++ b/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java @@ -1,174 +1,174 @@ /* * Copyright 2010-2011 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.account.dao; import java.sql.DataTruncation; import java.util.List; import java.util.UUID; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.ning.billing.ErrorCode; import com.ning.billing.account.api.Account; import com.ning.billing.account.api.AccountApiException; import com.ning.billing.account.api.AccountChangeEvent; import com.ning.billing.account.api.AccountCreationEvent; import com.ning.billing.account.api.user.DefaultAccountChangeEvent; import com.ning.billing.account.api.user.DefaultAccountCreationEvent; import com.ning.billing.util.ChangeType; import com.ning.billing.util.bus.Bus; import com.ning.billing.util.bus.Bus.EventBusException; import com.ning.billing.util.callcontext.CallContext; import com.ning.billing.util.dao.EntityAudit; import com.ning.billing.util.dao.EntityHistory; import com.ning.billing.util.dao.TableName; import com.ning.billing.util.entity.EntityPersistenceException; public class AuditedAccountDao implements AccountDao { private static final Logger log = LoggerFactory.getLogger(AuditedAccountDao.class); private final AccountSqlDao accountSqlDao; private final Bus eventBus; @Inject public AuditedAccountDao(final IDBI dbi, final Bus eventBus) { this.eventBus = eventBus; this.accountSqlDao = dbi.onDemand(AccountSqlDao.class); } @Override public Account getAccountByKey(final String key) { return accountSqlDao.getAccountByKey(key); } @Override public UUID getIdFromKey(final String externalKey) throws AccountApiException { if (externalKey == null) { throw new AccountApiException(ErrorCode.ACCOUNT_CANNOT_MAP_NULL_KEY, ""); } return accountSqlDao.getIdFromKey(externalKey); } @Override public Account getById(final UUID id) { return accountSqlDao.getById(id.toString()); } @Override public List<Account> get() { return accountSqlDao.get(); } @Override public void create(final Account account, final CallContext context) throws EntityPersistenceException { final String key = account.getExternalKey(); try { accountSqlDao.inTransaction(new Transaction<Void, AccountSqlDao>() { @Override public Void inTransaction(final AccountSqlDao transactionalDao, final TransactionStatus status) throws AccountApiException, Bus.EventBusException { final Account currentAccount = transactionalDao.getAccountByKey(key); if (currentAccount != null) { throw new AccountApiException(ErrorCode.ACCOUNT_ALREADY_EXISTS, key); } transactionalDao.create(account, context); // Insert history final Long recordId = accountSqlDao.getRecordId(account.getId().toString()); final EntityHistory<Account> history = new EntityHistory<Account>(account.getId(), recordId, account, ChangeType.INSERT); accountSqlDao.insertHistoryFromTransaction(history, context); // Insert audit final Long historyRecordId = accountSqlDao.getHistoryRecordId(recordId); final EntityAudit audit = new EntityAudit(TableName.ACCOUNT_HISTORY, historyRecordId, ChangeType.INSERT); accountSqlDao.insertAuditFromTransaction(audit, context); final AccountCreationEvent creationEvent = new DefaultAccountCreationEvent(account, context.getUserToken()); try { eventBus.postFromTransaction(creationEvent, transactionalDao); } catch (EventBusException e) { log.warn("Failed to post account creation event for account " + account.getId(), e); } return null; } }); } catch (RuntimeException re) { if (re.getCause() instanceof EntityPersistenceException) { throw (EntityPersistenceException) re.getCause(); } else if (re.getCause() instanceof DataTruncation) { throw new EntityPersistenceException(ErrorCode.DATA_TRUNCATION, re.getCause().getMessage()); } else { throw re; } } } @Override public void update(final Account specifiedAccount, final CallContext context) throws EntityPersistenceException { try { accountSqlDao.inTransaction(new Transaction<Void, AccountSqlDao>() { @Override public Void inTransaction(final AccountSqlDao transactional, final TransactionStatus status) throws EntityPersistenceException, Bus.EventBusException { final UUID accountId = specifiedAccount.getId(); final Account currentAccount = transactional.getById(accountId.toString()); if (currentAccount == null) { throw new EntityPersistenceException(ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID, accountId); } // Set unspecified (null) fields to their current values final Account account = specifiedAccount.mergeWithDelegate(currentAccount); transactional.update(account, context); final Long recordId = accountSqlDao.getRecordId(accountId.toString()); - final EntityHistory<Account> history = new EntityHistory<Account>(accountId, recordId, account, ChangeType.INSERT); + final EntityHistory<Account> history = new EntityHistory<Account>(accountId, recordId, account, ChangeType.UPDATE); accountSqlDao.insertHistoryFromTransaction(history, context); final Long historyRecordId = accountSqlDao.getHistoryRecordId(recordId); - final EntityAudit audit = new EntityAudit(TableName.ACCOUNT_HISTORY, historyRecordId, ChangeType.INSERT); + final EntityAudit audit = new EntityAudit(TableName.ACCOUNT_HISTORY, historyRecordId, ChangeType.UPDATE); accountSqlDao.insertAuditFromTransaction(audit, context); final AccountChangeEvent changeEvent = new DefaultAccountChangeEvent(accountId, context.getUserToken(), currentAccount, account); if (changeEvent.hasChanges()) { try { eventBus.postFromTransaction(changeEvent, transactional); } catch (EventBusException e) { log.warn("Failed to post account change event for account " + accountId, e); } } return null; } }); } catch (RuntimeException re) { if (re.getCause() instanceof EntityPersistenceException) { throw (EntityPersistenceException) re.getCause(); } else { throw re; } } } @Override public void test() { accountSqlDao.test(); } }
false
true
public void update(final Account specifiedAccount, final CallContext context) throws EntityPersistenceException { try { accountSqlDao.inTransaction(new Transaction<Void, AccountSqlDao>() { @Override public Void inTransaction(final AccountSqlDao transactional, final TransactionStatus status) throws EntityPersistenceException, Bus.EventBusException { final UUID accountId = specifiedAccount.getId(); final Account currentAccount = transactional.getById(accountId.toString()); if (currentAccount == null) { throw new EntityPersistenceException(ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID, accountId); } // Set unspecified (null) fields to their current values final Account account = specifiedAccount.mergeWithDelegate(currentAccount); transactional.update(account, context); final Long recordId = accountSqlDao.getRecordId(accountId.toString()); final EntityHistory<Account> history = new EntityHistory<Account>(accountId, recordId, account, ChangeType.INSERT); accountSqlDao.insertHistoryFromTransaction(history, context); final Long historyRecordId = accountSqlDao.getHistoryRecordId(recordId); final EntityAudit audit = new EntityAudit(TableName.ACCOUNT_HISTORY, historyRecordId, ChangeType.INSERT); accountSqlDao.insertAuditFromTransaction(audit, context); final AccountChangeEvent changeEvent = new DefaultAccountChangeEvent(accountId, context.getUserToken(), currentAccount, account); if (changeEvent.hasChanges()) { try { eventBus.postFromTransaction(changeEvent, transactional); } catch (EventBusException e) { log.warn("Failed to post account change event for account " + accountId, e); } } return null; } }); } catch (RuntimeException re) { if (re.getCause() instanceof EntityPersistenceException) { throw (EntityPersistenceException) re.getCause(); } else { throw re; } } }
public void update(final Account specifiedAccount, final CallContext context) throws EntityPersistenceException { try { accountSqlDao.inTransaction(new Transaction<Void, AccountSqlDao>() { @Override public Void inTransaction(final AccountSqlDao transactional, final TransactionStatus status) throws EntityPersistenceException, Bus.EventBusException { final UUID accountId = specifiedAccount.getId(); final Account currentAccount = transactional.getById(accountId.toString()); if (currentAccount == null) { throw new EntityPersistenceException(ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID, accountId); } // Set unspecified (null) fields to their current values final Account account = specifiedAccount.mergeWithDelegate(currentAccount); transactional.update(account, context); final Long recordId = accountSqlDao.getRecordId(accountId.toString()); final EntityHistory<Account> history = new EntityHistory<Account>(accountId, recordId, account, ChangeType.UPDATE); accountSqlDao.insertHistoryFromTransaction(history, context); final Long historyRecordId = accountSqlDao.getHistoryRecordId(recordId); final EntityAudit audit = new EntityAudit(TableName.ACCOUNT_HISTORY, historyRecordId, ChangeType.UPDATE); accountSqlDao.insertAuditFromTransaction(audit, context); final AccountChangeEvent changeEvent = new DefaultAccountChangeEvent(accountId, context.getUserToken(), currentAccount, account); if (changeEvent.hasChanges()) { try { eventBus.postFromTransaction(changeEvent, transactional); } catch (EventBusException e) { log.warn("Failed to post account change event for account " + accountId, e); } } return null; } }); } catch (RuntimeException re) { if (re.getCause() instanceof EntityPersistenceException) { throw (EntityPersistenceException) re.getCause(); } else { throw re; } } }
diff --git a/geoserver/community/RESTConfig/src/main/java/org/geoserver/restconfig/AutoXMLFormat.java b/geoserver/community/RESTConfig/src/main/java/org/geoserver/restconfig/AutoXMLFormat.java index abb3ac5094..18b90ae886 100644 --- a/geoserver/community/RESTConfig/src/main/java/org/geoserver/restconfig/AutoXMLFormat.java +++ b/geoserver/community/RESTConfig/src/main/java/org/geoserver/restconfig/AutoXMLFormat.java @@ -1,118 +1,118 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.geoserver.restconfig; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.restlet.data.MediaType; import org.restlet.resource.OutputRepresentation; import org.restlet.resource.Representation; public class AutoXMLFormat implements DataFormat { String myRootName; public AutoXMLFormat(){ this("root"); } public AutoXMLFormat(String s){ myRootName = s; } public Representation makeRepresentation(Map map) { map.remove("page"); Element root = new Element(myRootName); final Document doc = new Document(root); insert(root, map); return new OutputRepresentation(MediaType.APPLICATION_XML){ public void write(OutputStream outputStream){ try{ XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(doc, outputStream); } catch(IOException ioe){ ioe.printStackTrace(); } } }; } public void insert(Element elem, Object o){ if (o instanceof Map){ Iterator it = ((Map)o).entrySet().iterator(); while (it.hasNext()){ Map.Entry entry = (Map.Entry)it.next(); Element newElem = new Element(entry.getKey().toString()); insert(newElem, entry.getValue()); elem.addContent(newElem); } } else if (o instanceof Collection) { Iterator it = ((Collection)o).iterator(); while (it.hasNext()){ Element newElem = new Element("entry"); Object entry = it.next(); insert(newElem, entry); elem.addContent(newElem); } } else { elem.addContent(o == null ? "" : o.toString()); } } public Map readRepresentation(Representation rep) { Map m; try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(rep.getStream()); Element elem = doc.getRootElement(); m = (Map)convert(elem); } catch (Exception e){ m = new HashMap(); } return m; } private Object convert(Element elem){ List children = elem.getChildren(); if (children.size() == 0){ - if (elem.getText() == null){ + if (elem.getContent().size() == 0){ return null; } else { return elem.getText(); } } else if (children.get(0) instanceof Element){ Element child = (Element)children.get(0); if (child.getName().equals("entry")){ List l = new ArrayList(); Iterator it = elem.getChildren("entry").iterator(); while(it.hasNext()){ Element curr = (Element)it.next(); l.add(convert(curr)); } return l; } else { Map m = new HashMap(); Iterator it = children.iterator(); while (it.hasNext()){ Element curr = (Element)it.next(); m.put(curr.getName(), convert(curr)); } return m; } } throw new RuntimeException("Hm, there was a problem parsing XML"); } }
true
true
private Object convert(Element elem){ List children = elem.getChildren(); if (children.size() == 0){ if (elem.getText() == null){ return null; } else { return elem.getText(); } } else if (children.get(0) instanceof Element){ Element child = (Element)children.get(0); if (child.getName().equals("entry")){ List l = new ArrayList(); Iterator it = elem.getChildren("entry").iterator(); while(it.hasNext()){ Element curr = (Element)it.next(); l.add(convert(curr)); } return l; } else { Map m = new HashMap(); Iterator it = children.iterator(); while (it.hasNext()){ Element curr = (Element)it.next(); m.put(curr.getName(), convert(curr)); } return m; } } throw new RuntimeException("Hm, there was a problem parsing XML"); }
private Object convert(Element elem){ List children = elem.getChildren(); if (children.size() == 0){ if (elem.getContent().size() == 0){ return null; } else { return elem.getText(); } } else if (children.get(0) instanceof Element){ Element child = (Element)children.get(0); if (child.getName().equals("entry")){ List l = new ArrayList(); Iterator it = elem.getChildren("entry").iterator(); while(it.hasNext()){ Element curr = (Element)it.next(); l.add(convert(curr)); } return l; } else { Map m = new HashMap(); Iterator it = children.iterator(); while (it.hasNext()){ Element curr = (Element)it.next(); m.put(curr.getName(), convert(curr)); } return m; } } throw new RuntimeException("Hm, there was a problem parsing XML"); }
diff --git a/rest-api/rest-api-server/src/main/java/org/bonitasoft/web/rest/server/api/bpm/flownode/AbstractAPIHumanTask.java b/rest-api/rest-api-server/src/main/java/org/bonitasoft/web/rest/server/api/bpm/flownode/AbstractAPIHumanTask.java index 602d276c4..9bc26645a 100644 --- a/rest-api/rest-api-server/src/main/java/org/bonitasoft/web/rest/server/api/bpm/flownode/AbstractAPIHumanTask.java +++ b/rest-api/rest-api-server/src/main/java/org/bonitasoft/web/rest/server/api/bpm/flownode/AbstractAPIHumanTask.java @@ -1,90 +1,90 @@ /** * Copyright (C) 2013 BonitaSoft S.A. * BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble * 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.0 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 org.bonitasoft.web.rest.server.api.bpm.flownode; import java.util.List; import java.util.Map; import org.bonitasoft.web.rest.model.bpm.flownode.HumanTaskDefinition; import org.bonitasoft.web.rest.model.bpm.flownode.HumanTaskItem; import org.bonitasoft.web.rest.model.bpm.flownode.IHumanTaskItem; import org.bonitasoft.web.rest.server.datastore.bpm.flownode.HumanTaskDatastore; import org.bonitasoft.web.rest.server.framework.api.Datastore; import org.bonitasoft.web.toolkit.client.common.exception.api.APIForbiddenException; import org.bonitasoft.web.toolkit.client.common.util.StringUtil; import org.bonitasoft.web.toolkit.client.data.APIID; /** * @author Séverin Moussel * */ public class AbstractAPIHumanTask<ITEM extends IHumanTaskItem> extends AbstractAPITask<ITEM> { @Override protected HumanTaskDefinition defineItemDefinition() { return HumanTaskDefinition.get(); } @Override protected Datastore defineDefaultDatastore() { return new HumanTaskDatastore(getEngineSession()); } @Override public String defineDefaultSearchOrder() { // FIXME return HumanTaskItem.ATTRIBUTE_PRIORITY + " DESC"; } // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CRUDS // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public ITEM update(final APIID id, final Map<String, String> attributes) { // Cant unassigned a manual task final String assignedUserId = attributes.get(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID); if (assignedUserId.length() > 0) { ITEM humanTask = get(id); - if (humanTask.isManualTask() && !StringUtil.isBlank(assignedUserId)) { + if (humanTask.isManualTask() && StringUtil.isBlank(assignedUserId)) { throw new APIForbiddenException("Can't unassigned a manual task."); } if (humanTask.getAttributes().containsKey(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID)) { if (humanTask.getAttributeValue(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID) != null - && !humanTask.getAttributeValue(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID).contentEquals(assignedUserId)) { + && !humanTask.getAttributeValue(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID).equals(assignedUserId)) { throw new APIForbiddenException("Can't assign this task because it has already been assigned."); } } } return super.update(id, attributes); } // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // UTILS // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override protected List<String> defineReadOnlyAttributes() { final List<String> attributes = super.defineReadOnlyAttributes(); attributes.add(HumanTaskItem.ATTRIBUTE_ACTOR_ID); attributes.add(HumanTaskItem.ATTRIBUTE_ASSIGNED_DATE); return attributes; } }
false
true
public ITEM update(final APIID id, final Map<String, String> attributes) { // Cant unassigned a manual task final String assignedUserId = attributes.get(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID); if (assignedUserId.length() > 0) { ITEM humanTask = get(id); if (humanTask.isManualTask() && !StringUtil.isBlank(assignedUserId)) { throw new APIForbiddenException("Can't unassigned a manual task."); } if (humanTask.getAttributes().containsKey(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID)) { if (humanTask.getAttributeValue(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID) != null && !humanTask.getAttributeValue(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID).contentEquals(assignedUserId)) { throw new APIForbiddenException("Can't assign this task because it has already been assigned."); } } } return super.update(id, attributes); }
public ITEM update(final APIID id, final Map<String, String> attributes) { // Cant unassigned a manual task final String assignedUserId = attributes.get(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID); if (assignedUserId.length() > 0) { ITEM humanTask = get(id); if (humanTask.isManualTask() && StringUtil.isBlank(assignedUserId)) { throw new APIForbiddenException("Can't unassigned a manual task."); } if (humanTask.getAttributes().containsKey(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID)) { if (humanTask.getAttributeValue(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID) != null && !humanTask.getAttributeValue(HumanTaskItem.ATTRIBUTE_ASSIGNED_USER_ID).equals(assignedUserId)) { throw new APIForbiddenException("Can't assign this task because it has already been assigned."); } } } return super.update(id, attributes); }
diff --git a/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/StringCombine.java b/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/StringCombine.java index 1b39b37..0affa27 100644 --- a/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/StringCombine.java +++ b/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/StringCombine.java @@ -1,64 +1,64 @@ package com.mingebag.grover.falsebook.ic.datatype.string; import org.bukkit.block.Sign; import com.bukkit.gemo.FalseBook.IC.ICs.BaseChip; import com.bukkit.gemo.FalseBook.IC.ICs.ICGroup; import com.bukkit.gemo.FalseBook.IC.ICs.InputState; import com.grover.mingebag.ic.BaseData; import com.grover.mingebag.ic.BaseDataChip; import com.grover.mingebag.ic.DataTypes; import com.grover.mingebag.ic.StringData; public class StringCombine extends BaseDataChip { public StringCombine() { this.ICName = "String Combine"; this.ICNumber = "ic.string.comb"; setICGroup(ICGroup.CUSTOM_0); this.chipState = new BaseChip(false, true, true, "String", "String", "String"); this.chipState.setOutputs("String", "", ""); this.chipState.setLines("", ""); this.ICDescription = "This combines strings from left to right or combines the input string with the string provided on line 4."; } public void Execute(Sign signBlock, InputState currentInputs, InputState previousInputs) { String inputLeft = null; String inputRight = null; String out = null; String def = signBlock.getLine(2); - if (currentInputs.isInputTwoHigh() && previousInputs.isInputTwoLow()) { + if (currentInputs.isInputTwoHigh()) { BaseData dataLeft = getDataLeft(signBlock); if (dataLeft != null) { if (dataLeft.getType() == DataTypes.STRING) { inputLeft = ((StringData) dataLeft).getString(); } } } - if (currentInputs.isInputThreeHigh() && previousInputs.isInputThreeLow()) { + if (currentInputs.isInputThreeHigh()) { BaseData dataRight = getDataRight(signBlock); if (dataRight != null) { if (dataRight.getType() == DataTypes.STRING) { inputRight = ((StringData) dataRight).getString(); } } } if (inputLeft != null && inputRight != null) { out = inputLeft + inputRight; } if (def.length() > 0 && (inputLeft != null || inputRight != null)) { if (inputLeft != null) { out = inputLeft + def; } if (inputRight != null) { out = def + inputRight; } } if (out != null) this.outputData(new StringData(out), signBlock, 2); } }
false
true
public void Execute(Sign signBlock, InputState currentInputs, InputState previousInputs) { String inputLeft = null; String inputRight = null; String out = null; String def = signBlock.getLine(2); if (currentInputs.isInputTwoHigh() && previousInputs.isInputTwoLow()) { BaseData dataLeft = getDataLeft(signBlock); if (dataLeft != null) { if (dataLeft.getType() == DataTypes.STRING) { inputLeft = ((StringData) dataLeft).getString(); } } } if (currentInputs.isInputThreeHigh() && previousInputs.isInputThreeLow()) { BaseData dataRight = getDataRight(signBlock); if (dataRight != null) { if (dataRight.getType() == DataTypes.STRING) { inputRight = ((StringData) dataRight).getString(); } } } if (inputLeft != null && inputRight != null) { out = inputLeft + inputRight; } if (def.length() > 0 && (inputLeft != null || inputRight != null)) { if (inputLeft != null) { out = inputLeft + def; } if (inputRight != null) { out = def + inputRight; } } if (out != null) this.outputData(new StringData(out), signBlock, 2); }
public void Execute(Sign signBlock, InputState currentInputs, InputState previousInputs) { String inputLeft = null; String inputRight = null; String out = null; String def = signBlock.getLine(2); if (currentInputs.isInputTwoHigh()) { BaseData dataLeft = getDataLeft(signBlock); if (dataLeft != null) { if (dataLeft.getType() == DataTypes.STRING) { inputLeft = ((StringData) dataLeft).getString(); } } } if (currentInputs.isInputThreeHigh()) { BaseData dataRight = getDataRight(signBlock); if (dataRight != null) { if (dataRight.getType() == DataTypes.STRING) { inputRight = ((StringData) dataRight).getString(); } } } if (inputLeft != null && inputRight != null) { out = inputLeft + inputRight; } if (def.length() > 0 && (inputLeft != null || inputRight != null)) { if (inputLeft != null) { out = inputLeft + def; } if (inputRight != null) { out = def + inputRight; } } if (out != null) this.outputData(new StringData(out), signBlock, 2); }
diff --git a/agro-search/src/main/java/com/agroknow/search/web/bootstrap/AgroSearchInitializer.java b/agro-search/src/main/java/com/agroknow/search/web/bootstrap/AgroSearchInitializer.java index 572cebd..08a4f03 100644 --- a/agro-search/src/main/java/com/agroknow/search/web/bootstrap/AgroSearchInitializer.java +++ b/agro-search/src/main/java/com/agroknow/search/web/bootstrap/AgroSearchInitializer.java @@ -1,103 +1,103 @@ package com.agroknow.search.web.bootstrap; import com.agroknow.search.config.CoreConfig; import com.agroknow.search.config.WebConfig; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextCleanupListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.DispatcherServlet; import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter; /** * * @author aggelos */ public class AgroSearchInitializer implements WebApplicationInitializer { private static final Logger LOG = LoggerFactory.getLogger(AgroSearchInitializer.class); private static final String DEFAULT_ENV = "dev"; @Override public void onStartup(ServletContext container) { String environment = System.getProperty("com.agroknow.environment", DEFAULT_ENV).toLowerCase(); String[] activeProfiles = getActiveProfiles(environment); LOG.info("Starting application context with the following active profiles: " + Arrays.toString(activeProfiles)); //setup the parent context AnnotationConfigWebApplicationContext parentContext = new AnnotationConfigWebApplicationContext(); parentContext.getEnvironment().setActiveProfiles(activeProfiles); parentContext.setServletContext(container); parentContext.register(CoreConfig.class); parentContext.refresh(); //setup the web context AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.setEnvironment(parentContext.getEnvironment()); webContext.setParent(parentContext); webContext.getEnvironment().setActiveProfiles(activeProfiles); webContext.setServletContext(container); webContext.register(WebConfig.class); webContext.refresh(); //add the servlet with the web context ServletRegistration.Dynamic dispatcher = container.addServlet("default", new DispatcherServlet(webContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/search-api"); //add encoding filter CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); FilterRegistration.Dynamic encodingRegisteredFilter = container.addFilter("characterEncodingFilter", encodingFilter); - encodingRegisteredFilter.addMappingForUrlPatterns(null, false, "/search-api/*"); + encodingRegisteredFilter.addMappingForUrlPatterns(null, false, "/*"); //add url rewrite filter - order of addition matters so keep this filter before securityFilter UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter(); FilterRegistration.Dynamic urlRewriteRegisteredFilter = container.addFilter("urlRewriteFilter", urlRewriteFilter); urlRewriteRegisteredFilter.setInitParameter("confPath", "/WEB-INF/urlrewrite."+environment+".xml"); urlRewriteRegisteredFilter.setInitParameter("statusEnabled", "false"); - urlRewriteRegisteredFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/search-api/*"); + urlRewriteRegisteredFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/*"); //add a shutdown listener that closes spring web and parent contexts container.addListener(ContextCleanupListener.class); //change the name of the session cookie SessionCookieConfig sessCookieConfig = container.getSessionCookieConfig(); sessCookieConfig.setName("AGROSESSID"); container.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); } public String[] getActiveProfiles() { // get running environment String environment = System.getProperty("com.agroknow.environment", DEFAULT_ENV).toLowerCase(); return this.getActiveProfiles(environment); } public String[] getActiveProfiles(String environment) { // get spring active profiles String activeProfilesProp = System.getProperty("spring.profiles.active"); List<String> activeProfiles = (activeProfilesProp != null) ? new ArrayList<String>(Arrays.asList(activeProfilesProp.split(","))) : new ArrayList<String>(1); // add environment as the first active profile activeProfiles.add(0, environment); return activeProfiles.toArray(new String[activeProfiles.size()]); } }
false
true
public void onStartup(ServletContext container) { String environment = System.getProperty("com.agroknow.environment", DEFAULT_ENV).toLowerCase(); String[] activeProfiles = getActiveProfiles(environment); LOG.info("Starting application context with the following active profiles: " + Arrays.toString(activeProfiles)); //setup the parent context AnnotationConfigWebApplicationContext parentContext = new AnnotationConfigWebApplicationContext(); parentContext.getEnvironment().setActiveProfiles(activeProfiles); parentContext.setServletContext(container); parentContext.register(CoreConfig.class); parentContext.refresh(); //setup the web context AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.setEnvironment(parentContext.getEnvironment()); webContext.setParent(parentContext); webContext.getEnvironment().setActiveProfiles(activeProfiles); webContext.setServletContext(container); webContext.register(WebConfig.class); webContext.refresh(); //add the servlet with the web context ServletRegistration.Dynamic dispatcher = container.addServlet("default", new DispatcherServlet(webContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/search-api"); //add encoding filter CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); FilterRegistration.Dynamic encodingRegisteredFilter = container.addFilter("characterEncodingFilter", encodingFilter); encodingRegisteredFilter.addMappingForUrlPatterns(null, false, "/search-api/*"); //add url rewrite filter - order of addition matters so keep this filter before securityFilter UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter(); FilterRegistration.Dynamic urlRewriteRegisteredFilter = container.addFilter("urlRewriteFilter", urlRewriteFilter); urlRewriteRegisteredFilter.setInitParameter("confPath", "/WEB-INF/urlrewrite."+environment+".xml"); urlRewriteRegisteredFilter.setInitParameter("statusEnabled", "false"); urlRewriteRegisteredFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/search-api/*"); //add a shutdown listener that closes spring web and parent contexts container.addListener(ContextCleanupListener.class); //change the name of the session cookie SessionCookieConfig sessCookieConfig = container.getSessionCookieConfig(); sessCookieConfig.setName("AGROSESSID"); container.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); }
public void onStartup(ServletContext container) { String environment = System.getProperty("com.agroknow.environment", DEFAULT_ENV).toLowerCase(); String[] activeProfiles = getActiveProfiles(environment); LOG.info("Starting application context with the following active profiles: " + Arrays.toString(activeProfiles)); //setup the parent context AnnotationConfigWebApplicationContext parentContext = new AnnotationConfigWebApplicationContext(); parentContext.getEnvironment().setActiveProfiles(activeProfiles); parentContext.setServletContext(container); parentContext.register(CoreConfig.class); parentContext.refresh(); //setup the web context AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.setEnvironment(parentContext.getEnvironment()); webContext.setParent(parentContext); webContext.getEnvironment().setActiveProfiles(activeProfiles); webContext.setServletContext(container); webContext.register(WebConfig.class); webContext.refresh(); //add the servlet with the web context ServletRegistration.Dynamic dispatcher = container.addServlet("default", new DispatcherServlet(webContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/search-api"); //add encoding filter CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); FilterRegistration.Dynamic encodingRegisteredFilter = container.addFilter("characterEncodingFilter", encodingFilter); encodingRegisteredFilter.addMappingForUrlPatterns(null, false, "/*"); //add url rewrite filter - order of addition matters so keep this filter before securityFilter UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter(); FilterRegistration.Dynamic urlRewriteRegisteredFilter = container.addFilter("urlRewriteFilter", urlRewriteFilter); urlRewriteRegisteredFilter.setInitParameter("confPath", "/WEB-INF/urlrewrite."+environment+".xml"); urlRewriteRegisteredFilter.setInitParameter("statusEnabled", "false"); urlRewriteRegisteredFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/*"); //add a shutdown listener that closes spring web and parent contexts container.addListener(ContextCleanupListener.class); //change the name of the session cookie SessionCookieConfig sessCookieConfig = container.getSessionCookieConfig(); sessCookieConfig.setName("AGROSESSID"); container.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); }
diff --git a/src/com/emergentideas/webhandle/files/FileInfo.java b/src/com/emergentideas/webhandle/files/FileInfo.java index da6f41e..69e97e7 100644 --- a/src/com/emergentideas/webhandle/files/FileInfo.java +++ b/src/com/emergentideas/webhandle/files/FileInfo.java @@ -1,112 +1,112 @@ package com.emergentideas.webhandle.files; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Date; import java.util.Map; import com.emergentideas.utils.DateUtils; import com.emergentideas.utils.ReflectionUtils; public class FileInfo { public enum FileType { FILE, DIRECTORY } protected static Boolean java7 = null; protected static Method toPath = null; protected static Method readAttributes = null; protected static Object linkOptionsArrayForCall = null; /** * Returns a file info object with a few io ops as possible using Java 7 * code if possible, legacy if not. Returns null if the file does not exist. * @param file * @return */ public static FileInfo getInfo(File file) { if(isJava7()) { try { initReflectionObjects(); Object path = toPath.invoke(file); Map<String, Object> attrs = (Map<String, Object>)readAttributes.invoke(null, path, "*", linkOptionsArrayForCall); String last = attrs.get("lastModifiedTime").toString(); FileType type = (Boolean)attrs.get("isDirectory") ? FileType.DIRECTORY : FileType.FILE; return new FileInfo(last, type); } catch(Exception e) { - e.printStackTrace(); + // This is okay. It just means that there's no file at the path. } } else { if(file.exists()) { FileType type = file.isDirectory() ? FileType.DIRECTORY : FileType.FILE; long last = file.lastModified(); String sLast = DateUtils.javaNIODateFormat().format(new Date(last)); return new FileInfo(sLast, type); } } return null; } protected static void initReflectionObjects() throws ClassNotFoundException, NoSuchMethodException { if(toPath == null && isJava7()) { toPath = ReflectionUtils.getFirstMethod(File.class, "toPath"); Class files = ReflectionUtils.getClassForName("java.nio.file.Files"); Class path = ReflectionUtils.getClassForName("java.nio.file.Path"); Class linkOption = ReflectionUtils.getClassForName("java.nio.file.LinkOption"); Class linkOptionArray = ReflectionUtils.getArrayStyle(linkOption); linkOptionsArrayForCall = Array.newInstance(linkOption, 0); readAttributes = files.getMethod("readAttributes", path, String.class, linkOptionArray); } } protected static boolean isJava7() { if(java7 == null) { try { java7 = ReflectionUtils.getClassForName("java.nio.file.Path") != null; } catch(ClassNotFoundException e) { java7 = false; } } return java7; } protected String lastModified; protected FileType type; public FileInfo() {} public FileInfo(String lastModified, FileType type) { super(); this.lastModified = lastModified; this.type = type; } public String getLastModified() { return lastModified; } public void setLastModified(String lastModified) { this.lastModified = lastModified; } public FileType getType() { return type; } public void setType(FileType type) { this.type = type; } }
true
true
public static FileInfo getInfo(File file) { if(isJava7()) { try { initReflectionObjects(); Object path = toPath.invoke(file); Map<String, Object> attrs = (Map<String, Object>)readAttributes.invoke(null, path, "*", linkOptionsArrayForCall); String last = attrs.get("lastModifiedTime").toString(); FileType type = (Boolean)attrs.get("isDirectory") ? FileType.DIRECTORY : FileType.FILE; return new FileInfo(last, type); } catch(Exception e) { e.printStackTrace(); } } else { if(file.exists()) { FileType type = file.isDirectory() ? FileType.DIRECTORY : FileType.FILE; long last = file.lastModified(); String sLast = DateUtils.javaNIODateFormat().format(new Date(last)); return new FileInfo(sLast, type); } } return null; }
public static FileInfo getInfo(File file) { if(isJava7()) { try { initReflectionObjects(); Object path = toPath.invoke(file); Map<String, Object> attrs = (Map<String, Object>)readAttributes.invoke(null, path, "*", linkOptionsArrayForCall); String last = attrs.get("lastModifiedTime").toString(); FileType type = (Boolean)attrs.get("isDirectory") ? FileType.DIRECTORY : FileType.FILE; return new FileInfo(last, type); } catch(Exception e) { // This is okay. It just means that there's no file at the path. } } else { if(file.exists()) { FileType type = file.isDirectory() ? FileType.DIRECTORY : FileType.FILE; long last = file.lastModified(); String sLast = DateUtils.javaNIODateFormat().format(new Date(last)); return new FileInfo(sLast, type); } } return null; }
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/impl/RunTask.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/impl/RunTask.java index aebc7166e..3fb2fe357 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/impl/RunTask.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/impl/RunTask.java @@ -1,216 +1,216 @@ /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.api.impl; import java.io.IOException; import java.util.HashMap; import java.util.logging.Level; import org.eclipse.birt.core.archive.FileArchiveWriter; import org.eclipse.birt.core.archive.IDocArchiveWriter; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.IPageHandler; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.IRunTask; import org.eclipse.birt.report.engine.api.ReportEngine; import org.eclipse.birt.report.engine.emitter.EngineEmitterServices; import org.eclipse.birt.report.engine.emitter.IContentEmitter; import org.eclipse.birt.report.engine.executor.ReportExecutor; import org.eclipse.birt.report.engine.i18n.MessageConstants; import org.eclipse.birt.report.engine.presentation.HTMLPaginationEmitter; import org.eclipse.birt.report.engine.presentation.ReportDocumentEmitter; import org.eclipse.birt.report.engine.script.internal.ReportScriptExecutor; import org.eclipse.birt.report.model.api.ReportDesignHandle; /** * A task for running a report design to get a report document */ public class RunTask extends AbstractRunTask implements IRunTask { private IDocArchiveWriter archive; private ReportDocumentWriter writer; private IPageHandler pageHandler; /** * @param engine * the report engine * @param runnable * the report runnable instance */ public RunTask( ReportEngine engine, IReportRunnable runnable ) { super( engine, runnable ); executionContext.setFactoryMode( true ); executionContext.setPresentationMode( false ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IRunTask#setPageHandler(org.eclipse.birt.report.engine.api.IPageHandler) */ public void setPageHandler( IPageHandler callback ) { this.pageHandler = callback; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IRunTask#run(java.lang.String) */ public void run( String reportDocName ) throws EngineException { if ( reportDocName == null || reportDocName.length( ) == 0 ) throw new EngineException( "Report document name is not specified when running a report." ); //$NON-NLS-1$ try { archive = new FileArchiveWriter( reportDocName ); } catch ( IOException e ) { throw new EngineException( e.getLocalizedMessage( ) ); } run( archive ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.IRunTask#run(org.eclipse.birt.core.archive.IDocumentArchive) */ public void run( IDocArchiveWriter archive ) throws EngineException { if ( archive == null ) throw new EngineException( "Report archive is not specified when running a report." ); //$NON-NLS-1$ this.archive = archive; doRun( ); } private void openReportDocument( ) throws EngineException { try { ReportDesignHandle reportDesign = executionContext.getDesign( ); ReportScriptExecutor.handleBeforeOpenDoc( reportDesign, executionContext ); archive.initialize( ); writer = new ReportDocumentWriter( archive ); executionContext.setReportDocWriter( writer ); ReportScriptExecutor.handleAfterOpenDoc( reportDesign, executionContext ); } catch ( IOException ex ) { throw new EngineException( "Can't open the report archive.", ex ); //$NON-NLS-1$ } } private void closeReportDocument( ) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ReportScriptExecutor.handleBeforeCloseDoc( reportDesign, executionContext ); writer.close( ); ReportScriptExecutor.handleAfterCloseDoc( reportDesign, executionContext ); } private IContentEmitter createContentEmitter( ReportExecutor executor ) { // create the emitter services object that is needed in the emitters. EngineEmitterServices services = new EngineEmitterServices( this ); EngineConfig config = engine.getConfig( ); if ( config != null ) { HashMap emitterConfigs = config.getEmitterConfigs( ); services.setEmitterConfig( emitterConfigs ); } services.setRenderOption( renderOptions ); services.setExecutor( executor ); services.setRenderContext( appContext ); services.setReportRunnable( runnable ); IContentEmitter emitter = new HTMLPaginationEmitter( executor, pageHandler, new ReportDocumentEmitter( writer ) ); // emitter is not null emitter.initialize( services ); return emitter; } /** * runs the report * * @throws EngineException * throws exception when there is a run error */ protected void doRun( ) throws EngineException { ReportDesignHandle reportDesign = executionContext.getDesign( ); // using paramters if ( !validateParameters( ) ) { throw new EngineException( MessageConstants.INVALID_PARAMETER_EXCEPTION ); //$NON-NLS-1$ } loadDesign( ); prepareDesign( ); startFactory( ); openReportDocument( ); try { ReportExecutor executor = new ReportExecutor( executionContext ); executionContext.setExecutor( executor ); IContentEmitter emitter = createContentEmitter( executor ); executionContext.openDataEngine( ); executor.execute( reportDesign, emitter ); executionContext.closeDataEngine( ); writer.saveDesign( reportDesign ); writer.saveParamters( inputValues ); writer.savePersistentObjects( executionContext.getGlobalBeans( ) ); closeReportDocument( ); closeFactory( ); } catch ( Exception ex ) { log.log( Level.SEVERE, "An error happened while running the report. Cause:", ex ); //$NON-NLS-1$ throw new EngineException( - "Error happended while runntine the report", ex ); + "Error happended while running the report", ex ); } catch ( OutOfMemoryError err ) { log.log( Level.SEVERE, "An OutOfMemory error happened while running the report." ); //$NON-NLS-1$ throw err; } } public void close( ) { super.close( ); } }
true
true
protected void doRun( ) throws EngineException { ReportDesignHandle reportDesign = executionContext.getDesign( ); // using paramters if ( !validateParameters( ) ) { throw new EngineException( MessageConstants.INVALID_PARAMETER_EXCEPTION ); //$NON-NLS-1$ } loadDesign( ); prepareDesign( ); startFactory( ); openReportDocument( ); try { ReportExecutor executor = new ReportExecutor( executionContext ); executionContext.setExecutor( executor ); IContentEmitter emitter = createContentEmitter( executor ); executionContext.openDataEngine( ); executor.execute( reportDesign, emitter ); executionContext.closeDataEngine( ); writer.saveDesign( reportDesign ); writer.saveParamters( inputValues ); writer.savePersistentObjects( executionContext.getGlobalBeans( ) ); closeReportDocument( ); closeFactory( ); } catch ( Exception ex ) { log.log( Level.SEVERE, "An error happened while running the report. Cause:", ex ); //$NON-NLS-1$ throw new EngineException( "Error happended while runntine the report", ex ); } catch ( OutOfMemoryError err ) { log.log( Level.SEVERE, "An OutOfMemory error happened while running the report." ); //$NON-NLS-1$ throw err; } }
protected void doRun( ) throws EngineException { ReportDesignHandle reportDesign = executionContext.getDesign( ); // using paramters if ( !validateParameters( ) ) { throw new EngineException( MessageConstants.INVALID_PARAMETER_EXCEPTION ); //$NON-NLS-1$ } loadDesign( ); prepareDesign( ); startFactory( ); openReportDocument( ); try { ReportExecutor executor = new ReportExecutor( executionContext ); executionContext.setExecutor( executor ); IContentEmitter emitter = createContentEmitter( executor ); executionContext.openDataEngine( ); executor.execute( reportDesign, emitter ); executionContext.closeDataEngine( ); writer.saveDesign( reportDesign ); writer.saveParamters( inputValues ); writer.savePersistentObjects( executionContext.getGlobalBeans( ) ); closeReportDocument( ); closeFactory( ); } catch ( Exception ex ) { log.log( Level.SEVERE, "An error happened while running the report. Cause:", ex ); //$NON-NLS-1$ throw new EngineException( "Error happended while running the report", ex ); } catch ( OutOfMemoryError err ) { log.log( Level.SEVERE, "An OutOfMemory error happened while running the report." ); //$NON-NLS-1$ throw err; } }
diff --git a/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/compute/AtlasComputeService.java b/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/compute/AtlasComputeService.java index 41b9cb56f..d98b873ce 100644 --- a/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/compute/AtlasComputeService.java +++ b/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/compute/AtlasComputeService.java @@ -1,109 +1,109 @@ /* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.analytics.compute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.gxa.R.AtlasRFactory; import uk.ac.ebi.gxa.R.AtlasRServicesException; import uk.ac.ebi.rcloud.server.RServices; /** * Provides access to R computational infrastructure via an AtlasRFactory. To use, pass a {@link ComputeTask} to the * method {@link #computeTask(ComputeTask)}, the return type is determined by the type parameter to {@code * ComputeTask}. * <p/> * For example: * <code><pre> * RNumeric i = computeService.computeTask(new ComputeTask<RNumeric> () { * public compute(RServices R) throws RemoteException { * return (RNumeric) R.getObject("1 + 3"); * } * ); * </pre></code> * * @author Misha Kapushesky * @author Tony Burdett */ public class AtlasComputeService implements Compute { private AtlasRFactory atlasRFactory; private final Logger log = LoggerFactory.getLogger(getClass()); public AtlasRFactory getAtlasRFactory() { return atlasRFactory; } public void setAtlasRFactory(AtlasRFactory atlasRFactory) { this.atlasRFactory = atlasRFactory; } /** * Executes task on a borrowed worker. Returns type specified in generic type parameter T to the method. * * @param task task to evaluate, {@link ComputeTask} * @param <T> type that the task returns on completion * @return T */ public <T> T computeTask(ComputeTask<T> task) throws ComputeException { RServices rService = null; try { log.debug("Acquiring RServices"); rService = getAtlasRFactory().createRServices(); if(rService == null) { log.error("Can't create R service, so can't compute!"); - return null; + throw new ComputeException("Can't create R service, so can't compute!"); } if(rService.getServantName() != null) log.debug("Computing on " + rService.getServantName()); return task.compute(rService); } catch (ComputeException e) { throw e; } catch (Exception e) { log.error("Problem computing task!", e); throw new ComputeException(e); } finally { if (rService != null) { try { log.debug("Recycling R service"); getAtlasRFactory().recycleRServices(rService); } catch (Exception e) { log.error("Problem returning worker!", e); } } } } /** * Releases any resources that are retained by this AtlasComputeService */ public void shutdown() { log.debug("Shutting down..."); getAtlasRFactory().releaseResources(); } }
true
true
public <T> T computeTask(ComputeTask<T> task) throws ComputeException { RServices rService = null; try { log.debug("Acquiring RServices"); rService = getAtlasRFactory().createRServices(); if(rService == null) { log.error("Can't create R service, so can't compute!"); return null; } if(rService.getServantName() != null) log.debug("Computing on " + rService.getServantName()); return task.compute(rService); } catch (ComputeException e) { throw e; } catch (Exception e) { log.error("Problem computing task!", e); throw new ComputeException(e); } finally { if (rService != null) { try { log.debug("Recycling R service"); getAtlasRFactory().recycleRServices(rService); } catch (Exception e) { log.error("Problem returning worker!", e); } } } }
public <T> T computeTask(ComputeTask<T> task) throws ComputeException { RServices rService = null; try { log.debug("Acquiring RServices"); rService = getAtlasRFactory().createRServices(); if(rService == null) { log.error("Can't create R service, so can't compute!"); throw new ComputeException("Can't create R service, so can't compute!"); } if(rService.getServantName() != null) log.debug("Computing on " + rService.getServantName()); return task.compute(rService); } catch (ComputeException e) { throw e; } catch (Exception e) { log.error("Problem computing task!", e); throw new ComputeException(e); } finally { if (rService != null) { try { log.debug("Recycling R service"); getAtlasRFactory().recycleRServices(rService); } catch (Exception e) { log.error("Problem returning worker!", e); } } } }
diff --git a/src/test/java/org/sonar/plugins/cxx/CxxPluginTest.java b/src/test/java/org/sonar/plugins/cxx/CxxPluginTest.java index b11acddd..766a996b 100644 --- a/src/test/java/org/sonar/plugins/cxx/CxxPluginTest.java +++ b/src/test/java/org/sonar/plugins/cxx/CxxPluginTest.java @@ -1,33 +1,33 @@ /* * Sonar Cxx Plugin, open source software quality management tool. * Copyright (C) 2010 - 2011, Neticoa SAS France - Tous droits reserves. * Author(s) : Franck Bonin, Neticoa SAS France. * * Sonar Cxx Plugin is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar Cxx Plugin 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 Sonar Cxx Plugin; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.cxx; import static org.junit.Assert.assertEquals; import org.junit.Test; public class CxxPluginTest { @Test public void testGetExtensions() throws Exception { CxxPlugin plugin = new CxxPlugin(); - assertEquals(20, plugin.getExtensions().size()); + assertEquals(21, plugin.getExtensions().size()); } }
true
true
public void testGetExtensions() throws Exception { CxxPlugin plugin = new CxxPlugin(); assertEquals(20, plugin.getExtensions().size()); }
public void testGetExtensions() throws Exception { CxxPlugin plugin = new CxxPlugin(); assertEquals(21, plugin.getExtensions().size()); }
diff --git a/visural-common/src/com/visural/common/datastruct/BeanList.java b/visural-common/src/com/visural/common/datastruct/BeanList.java index b30832a..f368c2a 100644 --- a/visural-common/src/com/visural/common/datastruct/BeanList.java +++ b/visural-common/src/com/visural/common/datastruct/BeanList.java @@ -1,327 +1,326 @@ /* * Copyright 2010 Visural. * * 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. * under the License. */ package com.visural.common.datastruct; import com.visural.common.BeanUtil; import com.visural.common.collection.readonly.ReadOnlyList; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; /** * Wrapper for a List of JavaBeans, which allows sorting on different properties. * @author Visural */ public class BeanList<T> implements List<T>, Serializable { private static final String[] StringArray = new String[]{}; private final List<T> list; private int numberOfSorts = 1; private List<String> sortProperties = new ArrayList<String>(); private Nulls nullHandling = Nulls.HandledByComparators; public BeanList(List<T> real) { this.list = real; } public BeanList(List<T> real, int numberOfSorts) { this.list = real; this.numberOfSorts = numberOfSorts; } public BeanList(List<T> real, int numberOfSorts, String... initialSort) { this(real, numberOfSorts); sortByProperties(initialSort); } public BeanList(List<T> real, int numberOfSorts, Nulls nullHandling, String... initialSort) { this(real, numberOfSorts); setNullHandling(nullHandling); sortByProperties(initialSort); } public void sortByProperties(String... properties) { for (int n = properties.length-1; n >= 0; n--) { popIfRequiredThenAdd(properties[n]); } sort(properties); } public BeanList<T> resortByProperty(String property) { popIfRequiredThenAdd(property); sort(sortProperties.toArray(StringArray)); return this; } private void popIfRequiredThenAdd(String property) { if (sortProperties.size() > 0 && sortProperties.size() >= numberOfSorts) { String propAdj = property.startsWith("-") ? property.substring(1) : property; if (sortProperties.contains(propAdj)) { // remove old sort on this property sortProperties.remove(propAdj); } else if (sortProperties.contains("-"+propAdj)) { sortProperties.remove("-"+propAdj); } else { // sort pops oldest sort from end sortProperties.remove(sortProperties.size()-1); } } sortProperties.add(0, property); } public BeanList<T> resort() { sort(sortProperties.toArray(StringArray)); return this; } private BeanList<T> sort(final String... properties) { Collections.sort(list, new Comparator<T>() { - @Override public int compare(T o1, T o2) { try { for (int n = 0; n < properties.length; n++) { boolean ascending = true; String property = properties[n]; if (property.startsWith("-")) { ascending = false; property = property.substring(1); } Class type = BeanUtil.getPropertyType(o1, property); Method getter1 = BeanUtil.findGetter(o1.getClass(), property); if (getter1 == null) { throw new IllegalStateException(String.format("Property '%s' on class '%s' can not be resolved.", property, o1.getClass().getName())); } Method getter2 = BeanUtil.findGetter(o2.getClass(), property); if (getter2 == null) { throw new IllegalStateException(String.format("Property '%s' on class '%s' can not be resolved.", property, o2.getClass().getName())); } Object val1 = getter1.invoke(o1); Object val2 = getter2.invoke(o2); int result = 0; switch (nullHandling) { case AreLess: if (val1 == null && val2 == null) { continue; } else if (val1 == null && val2 != null) { return ascending ? -1 : 1; } else if (val1 != null && val2 == null) { return ascending ? 1 : -1; } break; case AreMore: if (val1 == null && val2 == null) { continue; } else if(val1 == null && val2 != null) { return ascending ? 1 : -1; } else if (val1 != null && val2 == null) { return ascending ? -1 : 1; } break; } Comparator comparator = getComparator(property, type); if (comparator != null) { result = comparator.compare(val1, val2); } else if (Comparable.class.isAssignableFrom(type)) { if (val1 != null) { result = ((Comparable)val1).compareTo(val2); } else if (val2 != null) { result = ((Comparable)val2).compareTo(val1); } else { result = 0; } } else { throw new IllegalStateException("Don't know how to compare type '"+type.getName()+"'"); } if (result < 0 || result > 0) { return ascending ? result : -result; } // if result == 0 we continue for next property comparison } // if all properties return 0, we return 0 too return 0; } catch (Exception e) { throw new IllegalStateException("Error invoking methods.", e); } } }); return this; } private Comparator getComparator(String property, Class type) { Comparator c = propertyComparators.get(property); if (c == null) { c = typeComparators.get(type); } return c; } private final Map<Class, Comparator> typeComparators = new HashMap<Class, Comparator>(); public BeanList<T> registerTypeComparator(Class type, Comparator comparator) { typeComparators.put(type, comparator); return this; } private final Map<String, Comparator> propertyComparators = new HashMap<String, Comparator>(); public BeanList<T> registerPropertyComparator(String property, Comparator comparator) { propertyComparators.put(property, comparator); return this; } public int getNumberOfSorts() { return numberOfSorts; } public void setNumberOfSorts(int numberOfSorts) { this.numberOfSorts = numberOfSorts; while (numberOfSorts < sortProperties.size()) { sortProperties.remove(sortProperties.size()-1); } } public ReadOnlyList<String> getSortProperties() { return new ReadOnlyList(sortProperties); } public Nulls getNullHandling() { return nullHandling; } public void setNullHandling(Nulls nullHandling) { this.nullHandling = nullHandling; } /* wrapped list methods follow */ public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } public boolean contains(Object o) { return list.contains(o); } public Iterator<T> iterator() { return list.iterator(); } public Object[] toArray() { return list.toArray(); } public <T> T[] toArray(T[] a) { return list.toArray(a); } public boolean add(T e) { return list.add(e); } public boolean remove(Object o) { return list.remove(o); } public boolean containsAll(Collection<?> c) { return list.containsAll(c); } public boolean addAll(Collection<? extends T> c) { return list.addAll(c); } public boolean addAll(int index, Collection<? extends T> c) { return list.addAll(index, c); } public boolean removeAll(Collection<?> c) { return list.removeAll(c); } public boolean retainAll(Collection<?> c) { return list.retainAll(c); } public void clear() { list.clear(); } public T get(int index) { return list.get(index); } public T set(int index, T element) { return list.set(index, element); } public void add(int index, T element) { list.add(index, element); } public T remove(int index) { return list.remove(index); } public int indexOf(Object o) { return list.indexOf(o); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public ListIterator<T> listIterator() { return list.listIterator(); } public ListIterator<T> listIterator(int index) { return list.listIterator(); } public List<T> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } @Override public String toString() { return "Sort"+sortProperties+"-"+list.toString(); } public enum Nulls { AreLess, AreMore, HandledByComparators } }
true
true
private BeanList<T> sort(final String... properties) { Collections.sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { try { for (int n = 0; n < properties.length; n++) { boolean ascending = true; String property = properties[n]; if (property.startsWith("-")) { ascending = false; property = property.substring(1); } Class type = BeanUtil.getPropertyType(o1, property); Method getter1 = BeanUtil.findGetter(o1.getClass(), property); if (getter1 == null) { throw new IllegalStateException(String.format("Property '%s' on class '%s' can not be resolved.", property, o1.getClass().getName())); } Method getter2 = BeanUtil.findGetter(o2.getClass(), property); if (getter2 == null) { throw new IllegalStateException(String.format("Property '%s' on class '%s' can not be resolved.", property, o2.getClass().getName())); } Object val1 = getter1.invoke(o1); Object val2 = getter2.invoke(o2); int result = 0; switch (nullHandling) { case AreLess: if (val1 == null && val2 == null) { continue; } else if (val1 == null && val2 != null) { return ascending ? -1 : 1; } else if (val1 != null && val2 == null) { return ascending ? 1 : -1; } break; case AreMore: if (val1 == null && val2 == null) { continue; } else if(val1 == null && val2 != null) { return ascending ? 1 : -1; } else if (val1 != null && val2 == null) { return ascending ? -1 : 1; } break; } Comparator comparator = getComparator(property, type); if (comparator != null) { result = comparator.compare(val1, val2); } else if (Comparable.class.isAssignableFrom(type)) { if (val1 != null) { result = ((Comparable)val1).compareTo(val2); } else if (val2 != null) { result = ((Comparable)val2).compareTo(val1); } else { result = 0; } } else { throw new IllegalStateException("Don't know how to compare type '"+type.getName()+"'"); } if (result < 0 || result > 0) { return ascending ? result : -result; } // if result == 0 we continue for next property comparison } // if all properties return 0, we return 0 too return 0; } catch (Exception e) { throw new IllegalStateException("Error invoking methods.", e); } } }); return this; }
private BeanList<T> sort(final String... properties) { Collections.sort(list, new Comparator<T>() { public int compare(T o1, T o2) { try { for (int n = 0; n < properties.length; n++) { boolean ascending = true; String property = properties[n]; if (property.startsWith("-")) { ascending = false; property = property.substring(1); } Class type = BeanUtil.getPropertyType(o1, property); Method getter1 = BeanUtil.findGetter(o1.getClass(), property); if (getter1 == null) { throw new IllegalStateException(String.format("Property '%s' on class '%s' can not be resolved.", property, o1.getClass().getName())); } Method getter2 = BeanUtil.findGetter(o2.getClass(), property); if (getter2 == null) { throw new IllegalStateException(String.format("Property '%s' on class '%s' can not be resolved.", property, o2.getClass().getName())); } Object val1 = getter1.invoke(o1); Object val2 = getter2.invoke(o2); int result = 0; switch (nullHandling) { case AreLess: if (val1 == null && val2 == null) { continue; } else if (val1 == null && val2 != null) { return ascending ? -1 : 1; } else if (val1 != null && val2 == null) { return ascending ? 1 : -1; } break; case AreMore: if (val1 == null && val2 == null) { continue; } else if(val1 == null && val2 != null) { return ascending ? 1 : -1; } else if (val1 != null && val2 == null) { return ascending ? -1 : 1; } break; } Comparator comparator = getComparator(property, type); if (comparator != null) { result = comparator.compare(val1, val2); } else if (Comparable.class.isAssignableFrom(type)) { if (val1 != null) { result = ((Comparable)val1).compareTo(val2); } else if (val2 != null) { result = ((Comparable)val2).compareTo(val1); } else { result = 0; } } else { throw new IllegalStateException("Don't know how to compare type '"+type.getName()+"'"); } if (result < 0 || result > 0) { return ascending ? result : -result; } // if result == 0 we continue for next property comparison } // if all properties return 0, we return 0 too return 0; } catch (Exception e) { throw new IllegalStateException("Error invoking methods.", e); } } }); return this; }
diff --git a/src/net/spato/sve/app/Updater.java b/src/net/spato/sve/app/Updater.java index 4785d07..f3ac396 100644 --- a/src/net/spato/sve/app/Updater.java +++ b/src/net/spato/sve/app/Updater.java @@ -1,311 +1,310 @@ /* * Copyright 2011 Christian Thiemann <[email protected]> * Developed at Northwestern University <http://rocs.northwestern.edu> * * This file is part of the SPaTo Visual Explorer (SPaTo). * * SPaTo 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. * * SPaTo 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 SPaTo. If not, see <http://www.gnu.org/licenses/>. */ package net.spato.sve.app; import java.awt.BorderLayout; import java.awt.Dimension; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.security.KeyFactory; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import net.spato.sve.app.util.*; import org.xhtmlrenderer.simple.FSScrollPane; import org.xhtmlrenderer.simple.XHTMLPanel; import processing.core.PApplet; import processing.xml.StdXMLBuilder; import processing.xml.StdXMLParser; import processing.xml.StdXMLReader; import processing.xml.XMLElement; import processing.xml.XMLException; import processing.xml.XMLValidator; public class Updater extends Thread { protected SPaTo_Visual_Explorer app = null; boolean force = false; String updateURL = "http://update.spato.net/latest/"; String releaseNotesURL = "http://update.spato.net/release-notes/"; String indexName = null; String appRootFolder = null; String cacheFolder = null; XMLElement index = null; String updateVersion = null; // public key for file verification (base64-encoded) String pubKey64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrWkHeVPecXQeOd2" + "C3K4UUzgBqXYJwfGNKZnLp17wy/45nH7/llxBKR7eioJPdYCauxQ8M" + "nuArSltlIV9AnBKxb8h28xoBsEx1ek04jvJEtd93Bw7ILa3eF4MDGl" + "ZxwPnmTaTICIVUXtiZveOHDl1dQBKvinyU8fe3Xi7+j9klnwIDAQAB"; public Updater(SPaTo_Visual_Explorer app, boolean force) { setPriority(Thread.MIN_PRIORITY); this.app = app; this.force = force; } public void printOut(String msg) { System.out.println("+++ SPaTo Updater: " + msg); } public void printErr(String msg) { System.err.println("!!! SPaTo Updater: " + msg); } public void setupEnvironment() { printOut("updateURL = " + updateURL); // determine which INDEX file to download switch (PApplet.platform) { case PApplet.LINUX: indexName = "INDEX.linux"; break; case PApplet.MACOSX: indexName = "INDEX.macosx"; break; case PApplet.WINDOWS: indexName = "INDEX.windows"; break; default: throw new RuntimeException("unsupported platform"); } printOut("indexName = " + indexName); // check application root folder appRootFolder = System.getProperty("spato.app-dir"); if ((appRootFolder == null) || !new File(appRootFolder).exists()) throw new RuntimeException("invalid application root folder: " + appRootFolder); if (!appRootFolder.endsWith(File.separator)) appRootFolder += File.separator; printOut("appRootFolder = " + appRootFolder); // check update cache folder switch (PApplet.platform) { case PApplet.LINUX: cacheFolder = System.getProperty("user.home") + "/.spato/update"; break; case PApplet.MACOSX: cacheFolder = appRootFolder + "Contents/Resources/update"; break; default: cacheFolder = appRootFolder + "update"; break; } if ((cacheFolder == null) || !new File(cacheFolder).exists() && !new File(cacheFolder).mkdirs()) throw new RuntimeException("could not create cache folder: " + cacheFolder); if (!cacheFolder.endsWith(File.separator)) cacheFolder += File.separator; printOut("cacheFolder = " + cacheFolder); } public boolean checkAndFetch() { // returns true if update is available int count = 0, totalSize = 0; BufferedReader reader = null; // fetch the index try { // reader creation copied from PApplet so we can catch exceptions InputStream is = new URL(updateURL + indexName).openStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); // XML parsing copied from XMLElement so we can catch exceptions index = new XMLElement(); StdXMLParser parser = new StdXMLParser(); parser.setBuilder(new StdXMLBuilder(index)); parser.setValidator(new XMLValidator()); parser.setReader(new StdXMLReader(reader)); parser.parse(); } catch (XMLException xmle) { index = null; throw new RuntimeException("Not a valid XML file: " + updateURL + indexName + "<br>" + "Are you properly connected to the interwebs?"); } catch (Exception e) { // FIXME: react to specific exceptions index = null; throw new RuntimeException("could not download " + indexName, e); } finally { try { reader.close(); } catch (Exception e) { } } // check whether the user wants to ignore this update try { updateVersion = index.getChild("release").getString("version"); } catch (Exception e) {} printOut("INDEX is for version " + updateVersion); if ((updateVersion != null) && updateVersion.equals(app.prefs.get("update.skip", null))) { printOut("user requested to skip this version"); return false; } else app.prefs.remove("update.skip"); // delete possibly existing locally cached index new File(cacheFolder + "INDEX").delete(); // setup signature verification Signature sig = null; try { sig = Signature.getInstance("MD5withRSA"); X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decode(pubKey64)); sig.initVerify(KeyFactory.getInstance("RSA").generatePublic(spec)); } catch (Exception e) { throw new RuntimeException("failed to setup signature verification", e); } // iterate over all file records for (XMLElement file : index.getChildren("file")) { XMLElement remote = file.getChild("remote"), local = file.getChild("local"); // check if all information is present if ((remote == null) || (remote.getString("path") == null) || (remote.getString("md5") == null) || (local == null) || (local.getString("path") == null)) throw new RuntimeException("malformed file record: " + file); // check for signature and decode byte signature[] = null; if ((file.getChild("signature") == null) || (file.getChild("signature").getContent() == null)) throw new RuntimeException("missing file signature: " + file); try { signature = Base64.decode(file.getChild("signature").getContent()); } catch (Exception e) { throw new RuntimeException("error decoding signature: " + file, e); } // download update file if necessary local.setString("md5", "" + MD5.digest(appRootFolder + local.getString("path"))); // "" forces "null" if md5 returns null if (!remote.getString("md5").equals(local.getString("md5"))) { count++; // count number of outdated files String cacheFilename = cacheFolder + remote.getString("path").replace('/', File.separatorChar); if (remote.getString("md5").equals(MD5.digest(cacheFilename))) printOut(remote.getString("path") + " is outdated, but update is already cached"); else { printOut(remote.getString("path") + " is outdated, downloading update (" + remote.getInt("size") + " bytes)"); - byte buf[] = new byte[remote.getInt("size", 0)]; + byte buf[] = new byte[remote.getInt("size", 0)]; int len = 0; InputStream is = null; try { - int read = 0; is = new URL(updateURL + remote.getString("path")).openStream(); - while (read < buf.length) - is.read(buf, read, buf.length - read); + while (len < buf.length) + len += is.read(buf, len, buf.length - len); } catch (Exception e) { printErr("download failed"); e.printStackTrace(); return false; } finally { try { is.close(); } catch (Exception e) {} } try { sig.update(buf); if (!sig.verify(signature)) throw new Exception("signature verification failure"); } catch (Exception e) { printErr("failed to verify file"); e.printStackTrace(); return false; } app.saveBytes(cacheFilename, buf); totalSize += remote.getInt("size"); // keep track of total download volume if (!remote.getString("md5").equals(MD5.digest(cacheFilename))) throw new RuntimeException("md5 mismatch: " + file); } } } // clean up and return if (count > 0) { printOut("updates available for " + count + " files, downloaded " + totalSize + " bytes"); return true; } else { printOut("no updates available"); new File(cacheFolder).delete(); return false; } } public String[] getRestartCmd() { switch (PApplet.platform) { case PApplet.LINUX: return new String[] { appRootFolder + "SPaTo_Visual_Explorer", "--restart" }; case PApplet.MACOSX: return new String[] { appRootFolder + "Contents/Resources/restart.sh" }; case PApplet.WINDOWS: return new String[] { appRootFolder + "SPaTo Visual Explorer.exe", "sleep", "3" }; default: return null; } } final static int NOTHING = -1, IGNORE = 0, INSTALL = 1, RESTART = 2; public int showReleaseNotesDialog(boolean canRestart) { // construct URL request String url = releaseNotesURL + "?version=" + app.VERSION + "&index=" + indexName; // setup HTML renderer for release notes XHTMLPanel htmlView = new XHTMLPanel(); try { htmlView.setDocument(url); } catch (Exception e) { throw new RuntimeException("could not fetch release notes from " + url, e); } JScrollPane scrollPane = new FSScrollPane(htmlView); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // compose everything in a panel JPanel panel = new JPanel(new BorderLayout(0, 10)); panel.add(new JLabel("An update is available and can be applied the next time you start SPaTo Visual Explorer."), BorderLayout.NORTH); panel.add(scrollPane, BorderLayout.CENTER); panel.add(new JLabel("<html>You are currently running version <b>" + app.VERSION + "</b> (" + app.VERSION_DATE + ").</html>"), BorderLayout.SOUTH); panel.setPreferredSize(new Dimension(600, 400)); panel.setMinimumSize(new Dimension(300, 200)); // add the auto-check checkbox JCheckBox cbAutoUpdate = new JCheckBox("Automatically check for updates in the future", app.prefs.getBoolean("update.check", true)); JPanel panel2 = new JPanel(new BorderLayout(0, 20)); panel2.add(panel, BorderLayout.CENTER); panel2.add(cbAutoUpdate, BorderLayout.SOUTH); // setup the options Object options[] = canRestart ? new Object[] { "Restart now", "Restart later", "Skip this update" } : new Object[] { "Awesome!", "Skip this update" }; // show the dialog int result = JOptionPane.showOptionDialog(app.frame, panel2, "Good news, everyone!", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); // save the auto-check selection app.prefs.putBoolean("update.check", cbAutoUpdate.isSelected()); // return the proper action constant if (result == (canRestart ? 2 : 1)) return IGNORE; // skip this update if (result == (canRestart ? 1 : 0)) return INSTALL; // install on next application launch if (result == 0 && canRestart) return RESTART; // install now return NOTHING; // this will cause to do nothing (no kidding!) } public void askAndAct() { while (app.fireworks) try { Thread.sleep(5000); } catch (Exception e) {} String cmd[] = getRestartCmd(); int action = showReleaseNotesDialog(cmd != null); // check if the user wants to ignore this update if (action == IGNORE) app.prefs.put("update.skip", updateVersion); // save the INDEX into the update cache folder to indicate that the update should be installed if ((action == INSTALL) || (action == RESTART)) index.write(app.createWriter(cacheFolder + "INDEX")); // restart application if requested if (action == RESTART) try { new ProcessBuilder(cmd).start(); app.exit(); // FIXME: unsaved documents? } catch (Exception e) { // catch this one here to give a slightly more optimistic error message printErr("could not restart application"); e.printStackTrace(); JOptionPane.showMessageDialog(app.frame, "<html>The restart application could not be lauched:<br><br>" + PApplet.join(cmd, " ") + "<br>" + e.getClass().getName() + ": " + e.getMessage() + "<br><br>" + "However, the update should install automatically when you manually restart the application.</html>", "Slightly disappointing news", JOptionPane.ERROR_MESSAGE); } } public void run() { try { setupEnvironment(); if (checkAndFetch()) askAndAct(); else if (force) JOptionPane.showMessageDialog(app.frame, "No updates available", "Update", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { printErr("Something's wrong. Stack trace follows..."); e.printStackTrace(); // prepare error dialog JPanel panel = new JPanel(new BorderLayout(0, 20)); String str = "<html>Something went wrong while checking for updates.<br><br>" + e.getMessage().substring(0, 1).toUpperCase() + e.getMessage().substring(1); if (e.getCause() != null) str += "\ndue to " + e.getCause().getClass().getName() + ": " + e.getCause().getMessage(); str += "</html>"; panel.add(new JLabel(str), BorderLayout.CENTER); JCheckBox cbAutoUpdate = new JCheckBox("Automatically check for updates in the future", app.prefs.getBoolean("update.check", true)); panel.add(cbAutoUpdate, BorderLayout.SOUTH); // show dialog JOptionPane.showMessageDialog(app.frame, panel, "Bollocks!", JOptionPane.ERROR_MESSAGE); // save the auto-check selection app.prefs.putBoolean("update.check", cbAutoUpdate.isSelected()); } } }
false
true
public boolean checkAndFetch() { // returns true if update is available int count = 0, totalSize = 0; BufferedReader reader = null; // fetch the index try { // reader creation copied from PApplet so we can catch exceptions InputStream is = new URL(updateURL + indexName).openStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); // XML parsing copied from XMLElement so we can catch exceptions index = new XMLElement(); StdXMLParser parser = new StdXMLParser(); parser.setBuilder(new StdXMLBuilder(index)); parser.setValidator(new XMLValidator()); parser.setReader(new StdXMLReader(reader)); parser.parse(); } catch (XMLException xmle) { index = null; throw new RuntimeException("Not a valid XML file: " + updateURL + indexName + "<br>" + "Are you properly connected to the interwebs?"); } catch (Exception e) { // FIXME: react to specific exceptions index = null; throw new RuntimeException("could not download " + indexName, e); } finally { try { reader.close(); } catch (Exception e) { } } // check whether the user wants to ignore this update try { updateVersion = index.getChild("release").getString("version"); } catch (Exception e) {} printOut("INDEX is for version " + updateVersion); if ((updateVersion != null) && updateVersion.equals(app.prefs.get("update.skip", null))) { printOut("user requested to skip this version"); return false; } else app.prefs.remove("update.skip"); // delete possibly existing locally cached index new File(cacheFolder + "INDEX").delete(); // setup signature verification Signature sig = null; try { sig = Signature.getInstance("MD5withRSA"); X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decode(pubKey64)); sig.initVerify(KeyFactory.getInstance("RSA").generatePublic(spec)); } catch (Exception e) { throw new RuntimeException("failed to setup signature verification", e); } // iterate over all file records for (XMLElement file : index.getChildren("file")) { XMLElement remote = file.getChild("remote"), local = file.getChild("local"); // check if all information is present if ((remote == null) || (remote.getString("path") == null) || (remote.getString("md5") == null) || (local == null) || (local.getString("path") == null)) throw new RuntimeException("malformed file record: " + file); // check for signature and decode byte signature[] = null; if ((file.getChild("signature") == null) || (file.getChild("signature").getContent() == null)) throw new RuntimeException("missing file signature: " + file); try { signature = Base64.decode(file.getChild("signature").getContent()); } catch (Exception e) { throw new RuntimeException("error decoding signature: " + file, e); } // download update file if necessary local.setString("md5", "" + MD5.digest(appRootFolder + local.getString("path"))); // "" forces "null" if md5 returns null if (!remote.getString("md5").equals(local.getString("md5"))) { count++; // count number of outdated files String cacheFilename = cacheFolder + remote.getString("path").replace('/', File.separatorChar); if (remote.getString("md5").equals(MD5.digest(cacheFilename))) printOut(remote.getString("path") + " is outdated, but update is already cached"); else { printOut(remote.getString("path") + " is outdated, downloading update (" + remote.getInt("size") + " bytes)"); byte buf[] = new byte[remote.getInt("size", 0)]; InputStream is = null; try { int read = 0; is = new URL(updateURL + remote.getString("path")).openStream(); while (read < buf.length) is.read(buf, read, buf.length - read); } catch (Exception e) { printErr("download failed"); e.printStackTrace(); return false; } finally { try { is.close(); } catch (Exception e) {} } try { sig.update(buf); if (!sig.verify(signature)) throw new Exception("signature verification failure"); } catch (Exception e) { printErr("failed to verify file"); e.printStackTrace(); return false; } app.saveBytes(cacheFilename, buf); totalSize += remote.getInt("size"); // keep track of total download volume if (!remote.getString("md5").equals(MD5.digest(cacheFilename))) throw new RuntimeException("md5 mismatch: " + file); } } } // clean up and return if (count > 0) { printOut("updates available for " + count + " files, downloaded " + totalSize + " bytes"); return true; } else { printOut("no updates available"); new File(cacheFolder).delete(); return false; } }
public boolean checkAndFetch() { // returns true if update is available int count = 0, totalSize = 0; BufferedReader reader = null; // fetch the index try { // reader creation copied from PApplet so we can catch exceptions InputStream is = new URL(updateURL + indexName).openStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); // XML parsing copied from XMLElement so we can catch exceptions index = new XMLElement(); StdXMLParser parser = new StdXMLParser(); parser.setBuilder(new StdXMLBuilder(index)); parser.setValidator(new XMLValidator()); parser.setReader(new StdXMLReader(reader)); parser.parse(); } catch (XMLException xmle) { index = null; throw new RuntimeException("Not a valid XML file: " + updateURL + indexName + "<br>" + "Are you properly connected to the interwebs?"); } catch (Exception e) { // FIXME: react to specific exceptions index = null; throw new RuntimeException("could not download " + indexName, e); } finally { try { reader.close(); } catch (Exception e) { } } // check whether the user wants to ignore this update try { updateVersion = index.getChild("release").getString("version"); } catch (Exception e) {} printOut("INDEX is for version " + updateVersion); if ((updateVersion != null) && updateVersion.equals(app.prefs.get("update.skip", null))) { printOut("user requested to skip this version"); return false; } else app.prefs.remove("update.skip"); // delete possibly existing locally cached index new File(cacheFolder + "INDEX").delete(); // setup signature verification Signature sig = null; try { sig = Signature.getInstance("MD5withRSA"); X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decode(pubKey64)); sig.initVerify(KeyFactory.getInstance("RSA").generatePublic(spec)); } catch (Exception e) { throw new RuntimeException("failed to setup signature verification", e); } // iterate over all file records for (XMLElement file : index.getChildren("file")) { XMLElement remote = file.getChild("remote"), local = file.getChild("local"); // check if all information is present if ((remote == null) || (remote.getString("path") == null) || (remote.getString("md5") == null) || (local == null) || (local.getString("path") == null)) throw new RuntimeException("malformed file record: " + file); // check for signature and decode byte signature[] = null; if ((file.getChild("signature") == null) || (file.getChild("signature").getContent() == null)) throw new RuntimeException("missing file signature: " + file); try { signature = Base64.decode(file.getChild("signature").getContent()); } catch (Exception e) { throw new RuntimeException("error decoding signature: " + file, e); } // download update file if necessary local.setString("md5", "" + MD5.digest(appRootFolder + local.getString("path"))); // "" forces "null" if md5 returns null if (!remote.getString("md5").equals(local.getString("md5"))) { count++; // count number of outdated files String cacheFilename = cacheFolder + remote.getString("path").replace('/', File.separatorChar); if (remote.getString("md5").equals(MD5.digest(cacheFilename))) printOut(remote.getString("path") + " is outdated, but update is already cached"); else { printOut(remote.getString("path") + " is outdated, downloading update (" + remote.getInt("size") + " bytes)"); byte buf[] = new byte[remote.getInt("size", 0)]; int len = 0; InputStream is = null; try { is = new URL(updateURL + remote.getString("path")).openStream(); while (len < buf.length) len += is.read(buf, len, buf.length - len); } catch (Exception e) { printErr("download failed"); e.printStackTrace(); return false; } finally { try { is.close(); } catch (Exception e) {} } try { sig.update(buf); if (!sig.verify(signature)) throw new Exception("signature verification failure"); } catch (Exception e) { printErr("failed to verify file"); e.printStackTrace(); return false; } app.saveBytes(cacheFilename, buf); totalSize += remote.getInt("size"); // keep track of total download volume if (!remote.getString("md5").equals(MD5.digest(cacheFilename))) throw new RuntimeException("md5 mismatch: " + file); } } } // clean up and return if (count > 0) { printOut("updates available for " + count + " files, downloaded " + totalSize + " bytes"); return true; } else { printOut("no updates available"); new File(cacheFolder).delete(); return false; } }
diff --git a/core/src/test/java/me/prettyprint/cassandra/service/CassandraClusterTest.java b/core/src/test/java/me/prettyprint/cassandra/service/CassandraClusterTest.java index d0a3f4eb..8b0cfe2e 100644 --- a/core/src/test/java/me/prettyprint/cassandra/service/CassandraClusterTest.java +++ b/core/src/test/java/me/prettyprint/cassandra/service/CassandraClusterTest.java @@ -1,271 +1,273 @@ package me.prettyprint.cassandra.service; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import me.prettyprint.cassandra.BaseEmbededServerSetupTest; import me.prettyprint.cassandra.model.BasicColumnDefinition; import me.prettyprint.cassandra.model.BasicColumnFamilyDefinition; import me.prettyprint.cassandra.model.BasicKeyspaceDefinition; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition; import me.prettyprint.hector.api.ddl.ColumnIndexType; import me.prettyprint.hector.api.ddl.ComparatorType; import me.prettyprint.hector.api.ddl.KeyspaceDefinition; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.ColumnQuery; import org.apache.cassandra.thrift.NotFoundException; import org.apache.cassandra.thrift.TokenRange; import org.apache.thrift.TException; import org.apache.thrift.transport.TTransportException; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class CassandraClusterTest extends BaseEmbededServerSetupTest { private ThriftCluster cassandraCluster; private CassandraHostConfigurator cassandraHostConfigurator; @Before public void setupCase() throws TTransportException, TException, IllegalArgumentException, NotFoundException, UnknownHostException, Exception { cassandraHostConfigurator = new CassandraHostConfigurator("localhost:9170"); cassandraCluster = new ThriftCluster("Test Cluster", cassandraHostConfigurator); } @Test public void testDescribeKeyspaces() throws Exception { List<KeyspaceDefinition> keyspaces = cassandraCluster.describeKeyspaces(); assertEquals(2,keyspaces.size()); } @Test public void testDescribeClusterName() throws Exception { assertEquals("Test Cluster",cassandraCluster.describeClusterName()); } /** * This will need to be updated as we update the Thrift API, but probably a good sanity check * */ @Test public void testDescribeThriftVersion() throws Exception { assertEquals("19.19.0",cassandraCluster.describeThriftVersion()); } @Test public void testDescribeRing() throws Exception { List<TokenRange> ring = cassandraCluster.describeRing("Keyspace1"); assertEquals(1, ring.size()); } @Test public void testDescribeKeyspace() throws Exception { KeyspaceDefinition keyspaceDetail = cassandraCluster.describeKeyspace("Keyspace1"); assertNotNull(keyspaceDetail); assertEquals(22, keyspaceDetail.getCfDefs().size()); } @Test public void testDescribePartitioner() throws Exception { String partitioner = cassandraCluster.describePartitioner(); assertEquals("org.apache.cassandra.dht.OrderPreservingPartitioner",partitioner); } @Test public void testAddDropColumnFamily() throws Exception { ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition("Keyspace1", "DynCf"); cassandraCluster.addColumnFamily(cfDef); String cfid2 = cassandraCluster.dropColumnFamily("Keyspace1", "DynCf"); assertNotNull(cfid2); // Let's wait for agreement cassandraCluster.addColumnFamily(cfDef, true); cfid2 = cassandraCluster.dropColumnFamily("Keyspace1", "DynCf", true); assertNotNull(cfid2); } @Test public void testTruncateColumnFamily() throws Exception { ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition("Keyspace1", "TruncateableCf"); cassandraCluster.addColumnFamily(cfDef); Keyspace workingKeyspace = HFactory.createKeyspace("Keyspace1", cassandraCluster); Mutator<String> mutator = HFactory.createMutator(workingKeyspace, StringSerializer.get()); mutator.insert("mykey", "TruncateableCf", HFactory.createStringColumn("mycolname", "myval")); ColumnQuery<String,String,String> q = HFactory.createColumnQuery(workingKeyspace, StringSerializer.get(), StringSerializer.get(), StringSerializer.get()); q.setKey("mykey").setName("mycolname").setColumnFamily("TruncateableCf"); assertEquals("myval",q.execute().get().getValue()); cassandraCluster.truncate("Keyspace1", "TruncateableCf"); assertNull(q.execute().get()); } @Test public void testAddDropKeyspace() throws Exception { ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition("DynKeyspace", "DynCf"); cassandraCluster.addKeyspace( new ThriftKsDef("DynKeyspace", "org.apache.cassandra.locator.SimpleStrategy", 1, Arrays.asList(cfDef))); String ksid2 = cassandraCluster.dropKeyspace("DynKeyspace"); assertNotNull(ksid2); // Now let's wait for schema agreement. cassandraCluster.addKeyspace(new ThriftKsDef("DynKeyspace", "org.apache.cassandra.locator.SimpleStrategy", 1, Arrays.asList(cfDef)), true); ksid2 = cassandraCluster.dropKeyspace("DynKeyspace", true); assertNotNull(ksid2); } @Test public void testAddKeyspaceNTS() throws Exception { ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition("DynKeyspaceNTS", "DynCf"); cassandraCluster.addKeyspace( new ThriftKsDef("DynKeyspaceNTS", "org.apache.cassandra.locator.NetworkTopologyStrategy", 1, Arrays.asList(cfDef))); } @Test public void testEditKeyspace() throws Exception { BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(); columnFamilyDefinition.setKeyspaceName("DynKeyspace2"); columnFamilyDefinition.setName("DynamicCF"); ColumnFamilyDefinition cfDef = new ThriftCfDef(columnFamilyDefinition); KeyspaceDefinition keyspaceDefinition = HFactory.createKeyspaceDefinition("DynKeyspace2", "org.apache.cassandra.locator.SimpleStrategy", 1, Arrays.asList(cfDef)); cassandraCluster.addKeyspace(keyspaceDefinition); keyspaceDefinition = HFactory.createKeyspaceDefinition("DynKeyspace2", "org.apache.cassandra.locator.SimpleStrategy", 2, null); cassandraCluster.updateKeyspace(keyspaceDefinition); KeyspaceDefinition fromCluster = cassandraCluster.describeKeyspace("DynKeyspace2"); assertEquals(2,fromCluster.getReplicationFactor()); cassandraCluster.dropKeyspace("DynKeyspace2"); } @Test public void testEditColumnFamily() throws Exception { BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(); columnFamilyDefinition.setKeyspaceName("DynKeyspace3"); columnFamilyDefinition.setName("DynamicCF"); ColumnFamilyDefinition cfDef = new ThriftCfDef(columnFamilyDefinition); KeyspaceDefinition keyspaceDefinition = HFactory.createKeyspaceDefinition("DynKeyspace3", "org.apache.cassandra.locator.SimpleStrategy", 1, Arrays.asList(cfDef)); cassandraCluster.addKeyspace(keyspaceDefinition); KeyspaceDefinition fromCluster = cassandraCluster.describeKeyspace("DynKeyspace3"); cfDef = fromCluster.getCfDefs().get(0); columnFamilyDefinition = new BasicColumnFamilyDefinition(cfDef); BasicColumnDefinition columnDefinition = new BasicColumnDefinition(); columnDefinition.setName(StringSerializer.get().toByteBuffer("birthdate")); + columnDefinition.setIndexName("birthdate_idx"); columnDefinition.setIndexType(ColumnIndexType.KEYS); columnDefinition.setValidationClass(ComparatorType.LONGTYPE.getClassName()); columnFamilyDefinition.addColumnDefinition(columnDefinition); columnDefinition = new BasicColumnDefinition(); columnDefinition.setName(StringSerializer.get().toByteBuffer("nonindexed_field")); columnDefinition.setValidationClass(ComparatorType.LONGTYPE.getClassName()); columnFamilyDefinition.addColumnDefinition(columnDefinition); cassandraCluster.updateColumnFamily(new ThriftCfDef(columnFamilyDefinition)); fromCluster = cassandraCluster.describeKeyspace("DynKeyspace3"); assertEquals("birthdate",StringSerializer.get().fromByteBuffer(fromCluster.getCfDefs().get(0).getColumnMetadata().get(0).getName())); + assertEquals("birthdate_idx",fromCluster.getCfDefs().get(0).getColumnMetadata().get(0).getIndexName()); assertEquals("nonindexed_field",StringSerializer.get().fromByteBuffer(fromCluster.getCfDefs().get(0).getColumnMetadata().get(1).getName())); } @Test public void testAddEmptyKeyspace() throws Exception { cassandraCluster.addKeyspace(new ThriftKsDef("DynKeyspaceEmpty")); assertNotNull(cassandraCluster.describeKeyspace("DynKeyspaceEmpty")); String ksid2 = cassandraCluster.dropKeyspace("DynKeyspaceEmpty"); assertNotNull(ksid2); } @Test public void testAddEmptyBasicKeyspaceDefinition() throws Exception { BasicKeyspaceDefinition ksDef = new BasicKeyspaceDefinition(); ksDef.setName("DynKeyspaceEmpty"); ksDef.setReplicationFactor(1); ksDef.setStrategyClass("SimpleStrategy"); cassandraCluster.addKeyspace(ksDef); assertNotNull(cassandraCluster.describeKeyspace("DynKeyspaceEmpty")); String ksid2 = cassandraCluster.dropKeyspace("DynKeyspaceEmpty"); assertNotNull(ksid2); } @Test public void testEditBasicKeyspaceDefinition() throws Exception { BasicKeyspaceDefinition ksDef = new BasicKeyspaceDefinition(); ksDef.setName("DynKeyspace4"); ksDef.setReplicationFactor(1); ksDef.setStrategyClass("SimpleStrategy"); cassandraCluster.addKeyspace(ksDef); assertNotNull(cassandraCluster.describeKeyspace("DynKeyspace4")); ksDef.setReplicationFactor(2); cassandraCluster.updateKeyspace(ksDef); KeyspaceDefinition fromCluster = cassandraCluster.describeKeyspace("DynKeyspace4"); assertEquals(2, fromCluster.getReplicationFactor()); cassandraCluster.dropKeyspace("DynKeyspace4"); } @Test public void testAddDropBasicColumnFamilyDefinition() throws Exception { BasicColumnFamilyDefinition cfDef = new BasicColumnFamilyDefinition(); cfDef.setName("DynCf"); cfDef.setKeyspaceName("Keyspace1"); cassandraCluster.addColumnFamily(cfDef); String cfid2 = cassandraCluster.dropColumnFamily("Keyspace1", "DynCf"); assertNotNull(cfid2); } @Test public void testEditBasicColumnFamilyDefinition() throws Exception { BasicKeyspaceDefinition ksDef = new BasicKeyspaceDefinition(); ksDef.setName("Keyspace2"); ksDef.setReplicationFactor(1); ksDef.setStrategyClass("SimpleStrategy"); cassandraCluster.addKeyspace(ksDef); BasicColumnFamilyDefinition cfDef = new BasicColumnFamilyDefinition(); cfDef.setName("DynCf2"); cfDef.setKeyspaceName("Keyspace2"); cassandraCluster.addColumnFamily(cfDef); KeyspaceDefinition fromCluster = cassandraCluster.describeKeyspace("Keyspace2"); cfDef = new BasicColumnFamilyDefinition(fromCluster.getCfDefs().get(0)); cfDef.setDefaultValidationClass(ComparatorType.LONGTYPE.getClassName()); cassandraCluster.updateColumnFamily(cfDef); String cfid2 = cassandraCluster.dropColumnFamily("Keyspace2", "DynCf2"); assertNotNull(cfid2); } }
false
true
public void testEditColumnFamily() throws Exception { BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(); columnFamilyDefinition.setKeyspaceName("DynKeyspace3"); columnFamilyDefinition.setName("DynamicCF"); ColumnFamilyDefinition cfDef = new ThriftCfDef(columnFamilyDefinition); KeyspaceDefinition keyspaceDefinition = HFactory.createKeyspaceDefinition("DynKeyspace3", "org.apache.cassandra.locator.SimpleStrategy", 1, Arrays.asList(cfDef)); cassandraCluster.addKeyspace(keyspaceDefinition); KeyspaceDefinition fromCluster = cassandraCluster.describeKeyspace("DynKeyspace3"); cfDef = fromCluster.getCfDefs().get(0); columnFamilyDefinition = new BasicColumnFamilyDefinition(cfDef); BasicColumnDefinition columnDefinition = new BasicColumnDefinition(); columnDefinition.setName(StringSerializer.get().toByteBuffer("birthdate")); columnDefinition.setIndexType(ColumnIndexType.KEYS); columnDefinition.setValidationClass(ComparatorType.LONGTYPE.getClassName()); columnFamilyDefinition.addColumnDefinition(columnDefinition); columnDefinition = new BasicColumnDefinition(); columnDefinition.setName(StringSerializer.get().toByteBuffer("nonindexed_field")); columnDefinition.setValidationClass(ComparatorType.LONGTYPE.getClassName()); columnFamilyDefinition.addColumnDefinition(columnDefinition); cassandraCluster.updateColumnFamily(new ThriftCfDef(columnFamilyDefinition)); fromCluster = cassandraCluster.describeKeyspace("DynKeyspace3"); assertEquals("birthdate",StringSerializer.get().fromByteBuffer(fromCluster.getCfDefs().get(0).getColumnMetadata().get(0).getName())); assertEquals("nonindexed_field",StringSerializer.get().fromByteBuffer(fromCluster.getCfDefs().get(0).getColumnMetadata().get(1).getName())); }
public void testEditColumnFamily() throws Exception { BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(); columnFamilyDefinition.setKeyspaceName("DynKeyspace3"); columnFamilyDefinition.setName("DynamicCF"); ColumnFamilyDefinition cfDef = new ThriftCfDef(columnFamilyDefinition); KeyspaceDefinition keyspaceDefinition = HFactory.createKeyspaceDefinition("DynKeyspace3", "org.apache.cassandra.locator.SimpleStrategy", 1, Arrays.asList(cfDef)); cassandraCluster.addKeyspace(keyspaceDefinition); KeyspaceDefinition fromCluster = cassandraCluster.describeKeyspace("DynKeyspace3"); cfDef = fromCluster.getCfDefs().get(0); columnFamilyDefinition = new BasicColumnFamilyDefinition(cfDef); BasicColumnDefinition columnDefinition = new BasicColumnDefinition(); columnDefinition.setName(StringSerializer.get().toByteBuffer("birthdate")); columnDefinition.setIndexName("birthdate_idx"); columnDefinition.setIndexType(ColumnIndexType.KEYS); columnDefinition.setValidationClass(ComparatorType.LONGTYPE.getClassName()); columnFamilyDefinition.addColumnDefinition(columnDefinition); columnDefinition = new BasicColumnDefinition(); columnDefinition.setName(StringSerializer.get().toByteBuffer("nonindexed_field")); columnDefinition.setValidationClass(ComparatorType.LONGTYPE.getClassName()); columnFamilyDefinition.addColumnDefinition(columnDefinition); cassandraCluster.updateColumnFamily(new ThriftCfDef(columnFamilyDefinition)); fromCluster = cassandraCluster.describeKeyspace("DynKeyspace3"); assertEquals("birthdate",StringSerializer.get().fromByteBuffer(fromCluster.getCfDefs().get(0).getColumnMetadata().get(0).getName())); assertEquals("birthdate_idx",fromCluster.getCfDefs().get(0).getColumnMetadata().get(0).getIndexName()); assertEquals("nonindexed_field",StringSerializer.get().fromByteBuffer(fromCluster.getCfDefs().get(0).getColumnMetadata().get(1).getName())); }
diff --git a/xfire-core/src/main/org/codehaus/xfire/service/invoker/AbstractInvoker.java b/xfire-core/src/main/org/codehaus/xfire/service/invoker/AbstractInvoker.java index d421c223..eebc280b 100755 --- a/xfire-core/src/main/org/codehaus/xfire/service/invoker/AbstractInvoker.java +++ b/xfire-core/src/main/org/codehaus/xfire/service/invoker/AbstractInvoker.java @@ -1,157 +1,157 @@ package org.codehaus.xfire.service.invoker; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.XFireRuntimeException; import org.codehaus.xfire.fault.XFireFault; import org.codehaus.xfire.util.ServiceUtils; /** * Abstract implementation of Invoker. * <p> * @author Ben Yu * Feb 10, 2006 10:57:23 PM */ public abstract class AbstractInvoker implements Invoker { public Object invoke(final Method method, final Object[] params, final MessageContext context) throws XFireFault { Method m = null; try { final Object serviceObject = getServiceObject(context); Object[] newParams = params; for (int i = 0; i < method.getParameterTypes().length; i++) { if (method.getParameterTypes()[i].equals(MessageContext.class)) { newParams = new Object[params.length+1]; for (int j = 0; j < newParams.length; j++) { if (j == i) { newParams[j] = context; } else if (j > i) { newParams[j] = params[j-1]; } else { newParams[j] = params[j]; } } } } m = matchMethod(method, serviceObject); return m.invoke(serviceObject, newParams); } catch (IllegalArgumentException e) { throw new XFireFault("Illegal argument invoking '" + ServiceUtils.getMethodName(method) + "': " + e.getMessage(), e, XFireFault.SENDER); } catch (InvocationTargetException e) { final Throwable t = e.getTargetException(); if (t instanceof XFireFault) { throw (XFireFault) t; } else if (t instanceof Exception) { Class[] exceptions = m.getExceptionTypes(); for( int i=0;i<exceptions.length;i++){ - if( exceptions[i].equals(t.getClass())){ + if( exceptions[i].isAssignableFrom(t.getClass())){ throw new XFireFault(t, XFireFault.RECEIVER); } } throw new XFireFault(t, XFireFault.SENDER); } else { throw new XFireRuntimeException("Error invoking '" + ServiceUtils.getMethodName(method) + '\'', e); } } catch (IllegalAccessException e) { throw new XFireFault("Couldn't access service object to invoke '" + ServiceUtils.getMethodName(method) + "': " + e.getMessage(), e, XFireFault.RECEIVER); } } /** * Creates and returns a service object depending on the scope. */ public abstract Object getServiceObject(final MessageContext context) throws XFireFault; /** * Returns a Method that has the same declaring class as the * class of targetObject to avoid the IllegalArgumentException * when invoking the method on the target object. The methodToMatch * will be returned if the targetObject doesn't have a similar method. * * @param methodToMatch The method to be used when finding a matching * method in targetObject * @param targetObject The object to search in for the method. * @return The methodToMatch if no such method exist in the class of * targetObject; otherwise, a method from the class of * targetObject matching the matchToMethod method. */ private static Method matchMethod(Method methodToMatch, Object targetObject) { if (isJdkDynamicProxy(targetObject)) { Class[] interfaces = targetObject.getClass().getInterfaces(); for (int i = 0; i < interfaces.length; i++) { Method m = getMostSpecificMethod(methodToMatch, interfaces[i]); if (!methodToMatch.equals(m)) { return m; } } } return methodToMatch; } /** * Return whether the given object is a J2SE dynamic proxy. * * @param object the object to check * @see java.lang.reflect.Proxy#isProxyClass */ public static boolean isJdkDynamicProxy(Object object) { return (object != null && Proxy.isProxyClass(object.getClass())); } /** * Given a method, which may come from an interface, and a targetClass * used in the current AOP invocation, find the most specific method * if there is one. E.g. the method may be IFoo.bar() and the target * class may be DefaultFoo. In this case, the method may be * DefaultFoo.bar(). This enables attributes on that method to be found. * * @param method method to be invoked, which may come from an interface * @param targetClass target class for the curren invocation. May * be <code>null</code> or may not even implement the method. * @return the more specific method, or the original method if the * targetClass doesn't specialize it or implement it or is null */ public static Method getMostSpecificMethod(Method method, Class targetClass) { if (method != null && targetClass != null) { try { method = targetClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ex) { // Perhaps the target class doesn't implement this method: // that's fine, just use the original method } } return method; } }
true
true
public Object invoke(final Method method, final Object[] params, final MessageContext context) throws XFireFault { Method m = null; try { final Object serviceObject = getServiceObject(context); Object[] newParams = params; for (int i = 0; i < method.getParameterTypes().length; i++) { if (method.getParameterTypes()[i].equals(MessageContext.class)) { newParams = new Object[params.length+1]; for (int j = 0; j < newParams.length; j++) { if (j == i) { newParams[j] = context; } else if (j > i) { newParams[j] = params[j-1]; } else { newParams[j] = params[j]; } } } } m = matchMethod(method, serviceObject); return m.invoke(serviceObject, newParams); } catch (IllegalArgumentException e) { throw new XFireFault("Illegal argument invoking '" + ServiceUtils.getMethodName(method) + "': " + e.getMessage(), e, XFireFault.SENDER); } catch (InvocationTargetException e) { final Throwable t = e.getTargetException(); if (t instanceof XFireFault) { throw (XFireFault) t; } else if (t instanceof Exception) { Class[] exceptions = m.getExceptionTypes(); for( int i=0;i<exceptions.length;i++){ if( exceptions[i].equals(t.getClass())){ throw new XFireFault(t, XFireFault.RECEIVER); } } throw new XFireFault(t, XFireFault.SENDER); } else { throw new XFireRuntimeException("Error invoking '" + ServiceUtils.getMethodName(method) + '\'', e); } } catch (IllegalAccessException e) { throw new XFireFault("Couldn't access service object to invoke '" + ServiceUtils.getMethodName(method) + "': " + e.getMessage(), e, XFireFault.RECEIVER); } }
public Object invoke(final Method method, final Object[] params, final MessageContext context) throws XFireFault { Method m = null; try { final Object serviceObject = getServiceObject(context); Object[] newParams = params; for (int i = 0; i < method.getParameterTypes().length; i++) { if (method.getParameterTypes()[i].equals(MessageContext.class)) { newParams = new Object[params.length+1]; for (int j = 0; j < newParams.length; j++) { if (j == i) { newParams[j] = context; } else if (j > i) { newParams[j] = params[j-1]; } else { newParams[j] = params[j]; } } } } m = matchMethod(method, serviceObject); return m.invoke(serviceObject, newParams); } catch (IllegalArgumentException e) { throw new XFireFault("Illegal argument invoking '" + ServiceUtils.getMethodName(method) + "': " + e.getMessage(), e, XFireFault.SENDER); } catch (InvocationTargetException e) { final Throwable t = e.getTargetException(); if (t instanceof XFireFault) { throw (XFireFault) t; } else if (t instanceof Exception) { Class[] exceptions = m.getExceptionTypes(); for( int i=0;i<exceptions.length;i++){ if( exceptions[i].isAssignableFrom(t.getClass())){ throw new XFireFault(t, XFireFault.RECEIVER); } } throw new XFireFault(t, XFireFault.SENDER); } else { throw new XFireRuntimeException("Error invoking '" + ServiceUtils.getMethodName(method) + '\'', e); } } catch (IllegalAccessException e) { throw new XFireFault("Couldn't access service object to invoke '" + ServiceUtils.getMethodName(method) + "': " + e.getMessage(), e, XFireFault.RECEIVER); } }
diff --git a/ccalc/rpc/src/test/java/org/gwtapp/ccalc/rpc/proc/calculator/CalculationTest.java b/ccalc/rpc/src/test/java/org/gwtapp/ccalc/rpc/proc/calculator/CalculationTest.java index d5d9f7d2..8043be4d 100644 --- a/ccalc/rpc/src/test/java/org/gwtapp/ccalc/rpc/proc/calculator/CalculationTest.java +++ b/ccalc/rpc/src/test/java/org/gwtapp/ccalc/rpc/proc/calculator/CalculationTest.java @@ -1,41 +1,67 @@ package org.gwtapp.ccalc.rpc.proc.calculator; import java.util.ArrayList; import java.util.List; import org.gwtapp.ccalc.rpc.data.book.Calculation; import org.gwtapp.ccalc.rpc.data.book.Currency; import org.gwtapp.ccalc.rpc.data.book.Operation; import org.gwtapp.ccalc.rpc.data.book.OperationImpl; import org.junit.Assert; import org.junit.Test; public class CalculationTest { @Test public void testInitState() { List<Operation> operations = new ArrayList<Operation>(); Calculator calculator = new Calculator(Currency.PLN, operations); List<Calculation> calculations = calculator.getCalculations(); Assert.assertNotNull(calculations); Assert.assertTrue(calculations.isEmpty()); } @Test public void testPositiveFifo() { List<Operation> operations = new ArrayList<Operation>(); operations.add(getOperation(100.0, 1.0, Currency.USD)); operations.add(getOperation(100.0, 2.0, Currency.USD)); - operations.add(getOperation(-50.0, null, Currency.USD)); - operations.add(getOperation(-125.0, null, Currency.USD)); + operations.add(getOperation(-50.0, 1.0, Currency.USD)); + operations.add(getOperation(-125.0, 1.0, Currency.USD)); Calculator calculator = new Calculator(Currency.PLN, operations); List<Calculation> calculations = calculator.getCalculations(); Assert.assertNotNull(calculations); Assert.assertEquals(4, calculations.size()); { + Calculation c = calculations.get(0); + Assert.assertEquals(new Double(100.0), c.getIncome()); + Assert.assertEquals(null, c.getCost()); + Assert.assertEquals(new Double(0.0), c.getFifo(Currency.USD)); + Assert.assertEquals(new Double(100.0), c.getFifoBase()); + } + { + Calculation c = calculations.get(1); + Assert.assertEquals(new Double(200.0), c.getIncome()); + Assert.assertEquals(null, c.getCost()); + Assert.assertEquals(new Double(25.0), c.getFifo(Currency.USD)); + Assert.assertEquals(new Double(200.0), c.getFifoBase()); + } + { + Calculation c = calculations.get(2); + Assert.assertEquals(null, c.getIncome()); + Assert.assertEquals(new Double(50.0), c.getCost()); + Assert.assertEquals(new Double(-1.0), c.getFifo(Currency.USD)); + Assert.assertEquals(new Double(-50), c.getFifoBase()); + } + { + Calculation c = calculations.get(3); + Assert.assertEquals(null, c.getIncome()); + Assert.assertEquals(new Double(125.0), c.getCost()); + Assert.assertEquals(new Double(-1.6), c.getFifo(Currency.USD)); + Assert.assertEquals(new Double(-200), c.getFifoBase()); } } private Operation getOperation(Double value, Double ratio, Currency currency) { return new OperationImpl(null, null, value, ratio, currency); } }
false
true
public void testPositiveFifo() { List<Operation> operations = new ArrayList<Operation>(); operations.add(getOperation(100.0, 1.0, Currency.USD)); operations.add(getOperation(100.0, 2.0, Currency.USD)); operations.add(getOperation(-50.0, null, Currency.USD)); operations.add(getOperation(-125.0, null, Currency.USD)); Calculator calculator = new Calculator(Currency.PLN, operations); List<Calculation> calculations = calculator.getCalculations(); Assert.assertNotNull(calculations); Assert.assertEquals(4, calculations.size()); { } }
public void testPositiveFifo() { List<Operation> operations = new ArrayList<Operation>(); operations.add(getOperation(100.0, 1.0, Currency.USD)); operations.add(getOperation(100.0, 2.0, Currency.USD)); operations.add(getOperation(-50.0, 1.0, Currency.USD)); operations.add(getOperation(-125.0, 1.0, Currency.USD)); Calculator calculator = new Calculator(Currency.PLN, operations); List<Calculation> calculations = calculator.getCalculations(); Assert.assertNotNull(calculations); Assert.assertEquals(4, calculations.size()); { Calculation c = calculations.get(0); Assert.assertEquals(new Double(100.0), c.getIncome()); Assert.assertEquals(null, c.getCost()); Assert.assertEquals(new Double(0.0), c.getFifo(Currency.USD)); Assert.assertEquals(new Double(100.0), c.getFifoBase()); } { Calculation c = calculations.get(1); Assert.assertEquals(new Double(200.0), c.getIncome()); Assert.assertEquals(null, c.getCost()); Assert.assertEquals(new Double(25.0), c.getFifo(Currency.USD)); Assert.assertEquals(new Double(200.0), c.getFifoBase()); } { Calculation c = calculations.get(2); Assert.assertEquals(null, c.getIncome()); Assert.assertEquals(new Double(50.0), c.getCost()); Assert.assertEquals(new Double(-1.0), c.getFifo(Currency.USD)); Assert.assertEquals(new Double(-50), c.getFifoBase()); } { Calculation c = calculations.get(3); Assert.assertEquals(null, c.getIncome()); Assert.assertEquals(new Double(125.0), c.getCost()); Assert.assertEquals(new Double(-1.6), c.getFifo(Currency.USD)); Assert.assertEquals(new Double(-200), c.getFifoBase()); } }
diff --git a/util/src/main/java/com/ning/arecibo/util/timeline/TimelineDAO.java b/util/src/main/java/com/ning/arecibo/util/timeline/TimelineDAO.java index 7f88e7f..02a3034 100644 --- a/util/src/main/java/com/ning/arecibo/util/timeline/TimelineDAO.java +++ b/util/src/main/java/com/ning/arecibo/util/timeline/TimelineDAO.java @@ -1,212 +1,213 @@ package com.ning.arecibo.util.timeline; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.inject.Inject; import com.google.inject.name.Named; import org.joda.time.DateTime; import org.skife.jdbi.v2.Folder2; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.util.IntegerMapper; import java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class TimelineDAO { private final IDBI dbi; @Inject public TimelineDAO(@Named("collector_db") IDBI dbi) { this.dbi = dbi; } /** * Get the full collection of hosts, as a BiMap that lets us look up * by host id */ public BiMap<Integer, String> getHosts() { return dbi.withHandle(new HandleCallback<BiMap<Integer, String>>() { @Override public BiMap<Integer, String> withHandle(Handle handle) throws Exception { return handle .createQuery("select host_id, host_name from hosts") .fold(makeBiMap(), new Folder2<BiMap<Integer, String>>() { @Override public BiMap<Integer, String> fold(BiMap<Integer, String> accumulator, ResultSet rs, StatementContext ctx) throws SQLException { final int hostId = rs.getInt(1); final String host = rs.getString(2); accumulator.put(hostId, host); return accumulator; } }); } }); } public int addHost(final String host) { return dbi.withHandle(new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { handle .createStatement("insert into hosts (host_name, created_dt) values (:host_name, unix_timestamp())") .bind("host_name", host) .execute(); return handle.createQuery("select last_insert_id()") .map(IntegerMapper.FIRST) .first(); } }); } public int addSampleKind(final String sampleKind) { return dbi.withHandle(new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { handle .createStatement("insert into sample_kinds (sample_kind) values (:sample_kind)") .bind("sample_kind", sampleKind) .execute(); return handle .createQuery("select last_insert_id()") .map(IntegerMapper.FIRST) .first(); } }); } private BiMap<Integer, String> makeBiMap() { return HashBiMap.create(); } public BiMap<Integer, String> getSampleKinds() { return dbi.withHandle(new HandleCallback<BiMap<Integer, String>>() { @Override public BiMap<Integer, String> withHandle(Handle handle) throws Exception { return handle .createQuery("select sample_kind_id, sample_kind from sample_kinds") .fold(makeBiMap(), new Folder2<BiMap<Integer, String>>() { @Override public BiMap<Integer, String> fold(BiMap<Integer, String> accumulator, ResultSet rs, StatementContext ctx) throws SQLException { final int sampleKindId = rs.getInt(1); final String sampleKind = rs.getString(2); accumulator.put(sampleKindId, sampleKind); return accumulator; } }); } }); } public int insertTimelineTimes(final TimelineTimes timelineTimes) { return dbi.inTransaction(new TransactionCallback<Integer>() { @Override public Integer inTransaction(Handle handle, TransactionStatus status) throws Exception { handle .createStatement("insert into timeline_times (host_id, start_time, end_time, count, times)" + " values (:host_id, :start_time, :end_time, :count, :times)") .bind("host_id", timelineTimes.getHostId()) .bind("start_time", TimelineTimes.unixSeconds(timelineTimes.getStartTime())) .bind("end_time", TimelineTimes.unixSeconds(timelineTimes.getEndTime())) .bind("count", timelineTimes.getSampleCount()) .bind("times", timelineTimes.getIntTimeArray()) .execute(); return handle .createQuery("select last_insert_id()") .map(IntegerMapper.FIRST) .first(); } }); } public int insertTimelineChunk(final TimelineChunk timelineChunk) { return dbi.inTransaction(new TransactionCallback<Integer>() { @Override public Integer inTransaction(Handle handle, TransactionStatus status) throws Exception { handle .createStatement("insert into timeline_chunks (host_id, sample_kind_id, sample_count, timeline_times_id, sample_bytes)" + "values (:host_id, :sample_kind_id, :sample_count, :timeline_times_id, :sample_bytes)") .bind("host_id", timelineChunk.getHostId()) .bind("sample_kind_id", timelineChunk.getSampleKindId()) .bind("sample_count", timelineChunk.getSampleCount()) .bind("timeline_times_id", timelineChunk.getTimelineTimesId()) .bind("sample_bytes", timelineChunk.getSamples()) .execute(); return handle .createQuery("select last_insert_id()") .map(IntegerMapper.FIRST) .first(); } }); } public List<TimelineChunkAndTimes> getSamplesByHostName(final String hostName, final DateTime startTime, final DateTime endTime) { return dbi.withHandle(new HandleCallback<List<TimelineChunkAndTimes>>() { @Override public List<TimelineChunkAndTimes> withHandle(final Handle handle) throws Exception { return handle .createQuery( "select\n" + " h.host_id\n" + ", h.host_name\n" + ", k.sample_kind_id\n" + ", k.sample_kind\n" + + ", c.sample_timeline_id\n" + ", c.timeline_times_id\n" + ", c.sample_count\n" + ", c.sample_bytes\n" + ", t.start_time\n" + ", t.end_time\n" + ", t.count\n" + ", t.times\n" + "from timeline_chunks c\n" + "join hosts h using (host_id)\n" + "join sample_kinds k using (sample_kind_id)\n" + "join timeline_times t using (timeline_times_id)\n" + "where t.start_time >= :start_time\n" + "and t.end_time <= :end_time\n" + "and h.host_name = :host_name\n" + ";") .bind("host_name", hostName) .bind("start_time", TimelineTimes.unixSeconds(startTime)) .bind("end_time", TimelineTimes.unixSeconds(endTime)) .fold(new ArrayList<TimelineChunkAndTimes>(), TimelineChunkAndTimes.folder); } }); } }
true
true
public List<TimelineChunkAndTimes> getSamplesByHostName(final String hostName, final DateTime startTime, final DateTime endTime) { return dbi.withHandle(new HandleCallback<List<TimelineChunkAndTimes>>() { @Override public List<TimelineChunkAndTimes> withHandle(final Handle handle) throws Exception { return handle .createQuery( "select\n" + " h.host_id\n" + ", h.host_name\n" + ", k.sample_kind_id\n" + ", k.sample_kind\n" + ", c.timeline_times_id\n" + ", c.sample_count\n" + ", c.sample_bytes\n" + ", t.start_time\n" + ", t.end_time\n" + ", t.count\n" + ", t.times\n" + "from timeline_chunks c\n" + "join hosts h using (host_id)\n" + "join sample_kinds k using (sample_kind_id)\n" + "join timeline_times t using (timeline_times_id)\n" + "where t.start_time >= :start_time\n" + "and t.end_time <= :end_time\n" + "and h.host_name = :host_name\n" + ";") .bind("host_name", hostName) .bind("start_time", TimelineTimes.unixSeconds(startTime)) .bind("end_time", TimelineTimes.unixSeconds(endTime)) .fold(new ArrayList<TimelineChunkAndTimes>(), TimelineChunkAndTimes.folder); } }); }
public List<TimelineChunkAndTimes> getSamplesByHostName(final String hostName, final DateTime startTime, final DateTime endTime) { return dbi.withHandle(new HandleCallback<List<TimelineChunkAndTimes>>() { @Override public List<TimelineChunkAndTimes> withHandle(final Handle handle) throws Exception { return handle .createQuery( "select\n" + " h.host_id\n" + ", h.host_name\n" + ", k.sample_kind_id\n" + ", k.sample_kind\n" + ", c.sample_timeline_id\n" + ", c.timeline_times_id\n" + ", c.sample_count\n" + ", c.sample_bytes\n" + ", t.start_time\n" + ", t.end_time\n" + ", t.count\n" + ", t.times\n" + "from timeline_chunks c\n" + "join hosts h using (host_id)\n" + "join sample_kinds k using (sample_kind_id)\n" + "join timeline_times t using (timeline_times_id)\n" + "where t.start_time >= :start_time\n" + "and t.end_time <= :end_time\n" + "and h.host_name = :host_name\n" + ";") .bind("host_name", hostName) .bind("start_time", TimelineTimes.unixSeconds(startTime)) .bind("end_time", TimelineTimes.unixSeconds(endTime)) .fold(new ArrayList<TimelineChunkAndTimes>(), TimelineChunkAndTimes.folder); } }); }
diff --git a/orbisgis-sif/src/main/java/org/orbisgis/sif/icons/BaseIcon.java b/orbisgis-sif/src/main/java/org/orbisgis/sif/icons/BaseIcon.java index c2350b199..7abd96e99 100644 --- a/orbisgis-sif/src/main/java/org/orbisgis/sif/icons/BaseIcon.java +++ b/orbisgis-sif/src/main/java/org/orbisgis/sif/icons/BaseIcon.java @@ -1,96 +1,97 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. OrbisGIS is * distributed under GPL 3 license. It is produced by the "Atelier SIG" team of * the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488. * * * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * * or contact directly: * info _at_ orbisgis.org */ package org.orbisgis.sif.icons; import java.awt.Image; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.swing.ImageIcon; import org.apache.log4j.Logger; import org.orbisgis.utils.I18N; /** * @package org.orbisgis.sif.icons * @brief Manage Icons loading */ /** * @class BaseIcon * @brief Use this class to retrieve the data of an icon * This final class load icons only on request. This feature help to reduce * the loading time of OrbisGis. Moreover this class does not have to be updated * when new icons are added. * Icon files are placed in the resource package org.orbisgis.sif.icons */ public class BaseIcon { private Map<String,ImageIcon> loadedIcons=new HashMap<String,ImageIcon>();/*!< This map contain all loaded icons */ private final ImageIcon ORBISGIS_MISSING_ICON = new ImageIcon(BaseIcon.class.getResource("remove.png")); /*!< Icon displayed when the requested icon is not found */ private final Logger LOG = Logger.getLogger(BaseIcon.class); /*!< Logger of SifIcon */ /** * Retrieve icon awt Image by its name * @param iconName The icon name, without extension. All icons are stored in the png format. * @return The Image content requested, or an Image corresponding to a Missing Resource */ public Image getIconImage(Class<?> loader,String iconName) { return getIcon(loader,iconName).getImage(); } /** * Retrieve icon by its name * @param iconName The icon name, without extension. All icons are stored in the png format. * @return The ImageIcon requested, or an ImageIcon corresponding to a Missing Resource */ public ImageIcon getIcon(Class<?> loader,String iconName) { if(!loadedIcons.containsKey(iconName)) { //This is the first request for this icon - URL url = loader.getResource(iconName+".png"); + String resourceName = iconName+".png"; + URL url = loader.getResource(resourceName); if(url!=null) { ImageIcon newIcon = new ImageIcon(url); loadedIcons.put(iconName, newIcon); return newIcon; } else { - LOG.warn(I18N.getString("sif.icons.OrbisGISIcon.icon_not_found")+" : "+iconName); + LOG.warn(I18N.getString("sif.icons.OrbisGISIcon.icon_not_found")+" : "+resourceName); //The next time, return directly the missing icon loadedIcons.put(iconName, ORBISGIS_MISSING_ICON); return ORBISGIS_MISSING_ICON; } } else { //Icon was already loaded, return its content return loadedIcons.get(iconName); } } }
false
true
public ImageIcon getIcon(Class<?> loader,String iconName) { if(!loadedIcons.containsKey(iconName)) { //This is the first request for this icon URL url = loader.getResource(iconName+".png"); if(url!=null) { ImageIcon newIcon = new ImageIcon(url); loadedIcons.put(iconName, newIcon); return newIcon; } else { LOG.warn(I18N.getString("sif.icons.OrbisGISIcon.icon_not_found")+" : "+iconName); //The next time, return directly the missing icon loadedIcons.put(iconName, ORBISGIS_MISSING_ICON); return ORBISGIS_MISSING_ICON; } } else { //Icon was already loaded, return its content return loadedIcons.get(iconName); } }
public ImageIcon getIcon(Class<?> loader,String iconName) { if(!loadedIcons.containsKey(iconName)) { //This is the first request for this icon String resourceName = iconName+".png"; URL url = loader.getResource(resourceName); if(url!=null) { ImageIcon newIcon = new ImageIcon(url); loadedIcons.put(iconName, newIcon); return newIcon; } else { LOG.warn(I18N.getString("sif.icons.OrbisGISIcon.icon_not_found")+" : "+resourceName); //The next time, return directly the missing icon loadedIcons.put(iconName, ORBISGIS_MISSING_ICON); return ORBISGIS_MISSING_ICON; } } else { //Icon was already loaded, return its content return loadedIcons.get(iconName); } }
diff --git a/src/org/opensolaris/opengrok/index/Indexer.java b/src/org/opensolaris/opengrok/index/Indexer.java index b0519877..3a05e1c7 100644 --- a/src/org/opensolaris/opengrok/index/Indexer.java +++ b/src/org/opensolaris/opengrok/index/Indexer.java @@ -1,468 +1,468 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ package org.opensolaris.opengrok.index; import java.awt.GraphicsEnvironment; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.InetAddress; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.opensolaris.opengrok.analysis.AnalyzerGuru; import org.opensolaris.opengrok.analysis.FileAnalyzerFactory; import org.opensolaris.opengrok.configuration.Project; import org.opensolaris.opengrok.history.HistoryGuru; import org.opensolaris.opengrok.configuration.RuntimeEnvironment; import org.opensolaris.opengrok.history.ExternalRepository; import org.opensolaris.opengrok.search.scope.MainFrame; import org.opensolaris.opengrok.util.Getopt; /** * Creates and updates an inverted source index * as well as generates Xref, file stats etc., if specified * in the options */ public class Indexer { private static String usage = "Usage: " + "opengrok.jar [-qe] [-c ctagsToUse] [-H] [-R filename] [-W filename] [-U hostname:port] [-P] [-p project-path] [-w webapproot] [-i ignore_name [ -i ..]] [-n] [-s SRC_ROOT] [-d DATA_ROOT] [subtree .. ]\n" + " opengrok.jar [-l | -t] [-d DATA_ROOT]\n" + "\t-q run quietly\n" + "\t-v Print progress information\n" + "\t-e economical - consumes less disk space\n" + "\t-c path to ctags\n" + "\t-R Read configuration from file\n" + "\t-W Write the current running configuration\n" + "\t-U Send configuration to hostname:port\n" + "\t-P Generate a project for each toplevel directory\n" + "\t-p Use the project specified by the project path as the default project\n" + "\t-Q on/off Turn on / off quick context scan. By default only the first 32k\n" + "\t of a file is scanned and a '[..all..]' link is inserted if the\n" + "\t is bigger. Activating this option may slow down the server.\n" + "\t-n Do not generate indexes\n" + "\t-H Generate history cache for all external repositories\n" + "\t-h /path/to/repos Generate history cache for the specified repos (absolute path from source root)\n" + "\t-r on/off Turn on / off support for remote SCM systems\n" + "\t-L laf Use \"laf\" as the look'n'feel for the webapp\n" + "\t-w root URL of the webapp, default is /source\n" + "\t-i ignore named files or directories\n" + "\t-A ext:analyzer Files with extension ext should be analyzed with the named class\n" + "\t-m Maximum words in a file to index\n" + "\t-O on/off Turn on / off database optimization\n" + "\t-a on/off Allow or disallow leading wildcards in a search\n" + "\t-S Search and add \"External\" repositories (Mercurial etc)\n" + "\t-s SRC_ROOT is root directory of source tree\n" + "\t default: last used SRC_ROOT\n" + "\t-d DATA_ROOT - is where output of indexer is stored\n" + "\tsubtree - only specified files or directories under SRC_ROOT are processed\n" + "\t if not specified all files under SRC_ROOT are processed\n" + "\n" + "\t-l list all files in the index\n" + "\t-t lists tokens occuring more than 5 times. Useful for building a unix dictionary\n" + "\n Eg. java -jar opengrok.jar -s /usr/include /var/tmp/opengrok_data rpc"; private static String options = "d:r:a:qec:Q:R:W:U:Pp:nHh:w:i:Ss:ltvm:O:A:L:"; /** * Program entry point * @param argv argument vector */ public static void main(String argv[]) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); boolean runIndex = true; if(argv.length == 0) { if (GraphicsEnvironment.isHeadless()) { System.err.println("No display available for the Graphical User Interface"); System.err.println(usage); System.exit(1); } else { MainFrame.main(argv); } //Run Scope GUI here I am running Indexing GUI for testing //new IndexerWizard(null).setVisible(true); } else { boolean searchRepositories = false; ArrayList<String> subFiles = new ArrayList<String>(); ArrayList<String> repositories = new ArrayList<String>(); String configFilename = null; String configHost = null; boolean addProjects = false; boolean refreshHistory = false; String defaultProject = null; boolean listFiles = false; boolean createDict = false; // Parse command line options: Getopt getopt = new Getopt(argv, options); try { getopt.parse(); } catch (ParseException ex) { System.err.println("OpenGrok: " + ex.getMessage()); System.err.println(usage); System.exit(1); } try{ int cmd; // We need to read the configuration file first, since we // will try to overwrite options.. while ((cmd = getopt.getOpt()) != -1) { if (cmd == 'R') { env.readConfiguration(new File(getopt.getOptarg())); break; } } // Now we can handle all the other options.. getopt.reset(); while ((cmd = getopt.getOpt()) != -1) { switch (cmd) { case 'l': listFiles = true; runIndex = false; break; case 't': createDict = true; runIndex = false; break; case 'q': env.setVerbose(false); break; case 'e': env.setGenerateHtml(false); break; case 'P': addProjects = true; break; case 'p': defaultProject = getopt.getOptarg(); break; case 'c': env.setCtags(getopt.getOptarg()); break; case 'w': { String webapp = getopt.getOptarg(); if (webapp.startsWith("/") || webapp.startsWith("http")) { ; } else { webapp = "/" + webapp; } if (webapp.endsWith("/")) { env.setUrlPrefix(webapp + "s?"); } else { env.setUrlPrefix(webapp + "/s?"); } } break; case 'W': configFilename = getopt.getOptarg(); break; case 'U': configHost = getopt.getOptarg(); break; case 'R': // already handled break; case 'n': runIndex = false; break; case 'H': refreshHistory = true; break; case 'h' : repositories.add(getopt.getOptarg()); break; case 'r': { if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setRemoteScmSupported(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { - env.setRemoteScmSupported(true); + env.setRemoteScmSupported(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r"); System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems"); - System.err.println(" \"-Q off\" will ignore SCM for remote systems"); + System.err.println(" \"-r off\" will ignore SCM for remote systems"); } } break; case 'O': { if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setOptimizeDatabase(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setOptimizeDatabase(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O"); System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation"); System.err.println(" \"-O off\" disable optimization of the index database"); } } break; case 'v': env.setVerbose(true); break; case 's': { File file = new File(getopt.getOptarg()); if (!file.isDirectory()) { System.err.println("ERROR: No such directory: " + file.toString()); System.exit(1); } env.setSourceRootFile(file); break; } case 'd': env.setDataRoot(getopt.getOptarg()); break; case 'i': env.getIgnoredNames().add(getopt.getOptarg()); break; case 'S' : searchRepositories = true; break; case 'Q' : if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setQuickContextScan(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setQuickContextScan(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q"); System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\""); System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file."); } break; case 'm' : { try { env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg())); } catch (NumberFormatException exp) { System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage()); System.exit(1); } break; } case 'a' : if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setAllowLeadingWildcard(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setAllowLeadingWildcard(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a"); System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard"); System.err.println(" \"-a off\" will disallow a search to start with a wildcard"); System.exit(1); } break; case 'A': { String[] arg = getopt.getOptarg().split(":"); if (arg.length != 2) { System.err.println("ERROR: You must specify: -A extension:class"); System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer"); System.err.println(" will use the C analyzer for all files ending with .foo"); System.err.println(" Ex: -A c:-"); System.err.println(" will disable the c-analyzer for for all files ending with .c"); System.exit(1); } arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase(); if (arg[1].equals("-")) { AnalyzerGuru.addExtension(arg[0], null); break; } try { AnalyzerGuru.addExtension( arg[0], AnalyzerGuru.findFactory(arg[1])); } catch (Exception e) { System.err.println("Unable to use " + arg[1] + " as a FileAnalyzerFactory"); e.printStackTrace(); System.exit(1); } } break; case 'L' : env.setWebappLAF(getopt.getOptarg()); break; default: System.err.println("Unknown option: " + (char)cmd); System.exit(1); } } int optind = getopt.getOptind(); if (optind != -1) { while (optind < argv.length) { subFiles.add(argv[optind]); ++optind; } } if (env.getDataRootPath() == null) { System.err.println("ERROR: Please specify a DATA ROOT path"); System.err.println(usage); System.exit(1); } if (env.getSourceRootFile() == null) { File srcConfig = new File(env.getDataRootPath(), "SRC_ROOT"); String line = null; if(srcConfig.exists()) { try { BufferedReader sr = new BufferedReader(new FileReader(srcConfig)); line = sr.readLine(); sr.close(); } catch (IOException e) { } } if(line == null) { System.err.println("ERROR: please specify a SRC_ROOT with option -s !"); System.err.println(usage); System.exit(1); } env.setSourceRoot(line); if (!env.getSourceRootFile().isDirectory()) { System.err.println("ERROR: No such directory:" + line); System.err.println(usage); System.exit(1); } } if (!env.validateExuberantCtags()) { System.exit(1); } if (searchRepositories) { if (env.isVerbose()) { System.out.println("Scanning for repositories..."); } env.getRepositories().clear(); long start = System.currentTimeMillis(); HistoryGuru.getInstance().addExternalRepositories(env.getSourceRootPath()); long time = (System.currentTimeMillis() - start) / 1000; if (env.isVerbose()) { System.out.println("Done searching for repositories (" + time + "s)"); } } if (addProjects) { File files[] = env.getSourceRootFile().listFiles(); List<Project> projects = env.getProjects(); projects.clear(); for (File file : files) { if (!file.getName().startsWith(".") && file.isDirectory()) { projects.add(new Project(file.getName(), "/" + file.getName())); } } // The projects should be sorted... Collections.sort(projects, new Comparator<Project>() { public int compare(Project p1, Project p2){ String s1 = p1.getDescription(); String s2 = p2.getDescription(); int ret; if (s1 == null) { ret = (s2 == null) ? 0 : 1; } else { ret = s1.compareTo(s2); } return ret; } }); } if (defaultProject != null) { for (Project p : env.getProjects()) { if (p.getPath().equals(defaultProject)) { env.setDefaultProject(p); break; } } } if (configFilename != null) { if (env.isVerbose()) { System.out.println("Writing configuration to " + configFilename); System.out.flush(); } env.writeConfiguration(new File(configFilename)); if (env.isVerbose()) { System.out.println("Done..."); System.out.flush(); } } if (refreshHistory) { HistoryGuru.getInstance().createCache(); } else if (repositories.size() > 0) { HistoryGuru.getInstance().createCache(repositories); } if (listFiles) { IndexDatabase.listAllFiles(subFiles); } if (createDict) { IndexDatabase.listFrequentTokens(subFiles); } if (runIndex) { IndexChangedListener progress = new DefaultIndexChangedListener(); if (subFiles.isEmpty() || !env.hasProjects()) { IndexDatabase.updateAll(progress); } else { for (String path : subFiles) { Project project = Project.getProject(path); if (project == null) { System.err.println("Warning: Could not find a project for \"" + path + "\""); } else { IndexDatabase db = new IndexDatabase(project); db.addIndexChangedListener(progress); db.update(); } } } } if (configHost != null) { String[] cfg = configHost.split(":"); if (env.isVerbose()) { System.out.println("Send configuration to: " + configHost); } if (cfg.length == 2) { try { InetAddress host = InetAddress.getByName(cfg[0]); RuntimeEnvironment.getInstance().writeConfiguration(host, Integer.parseInt(cfg[1])); } catch (Exception ex) { System.err.println("Failed to send configuration to " + configHost); ex.printStackTrace(); } } else { System.err.println("Syntax error: "); for (String s : cfg) { System.err.print("[" + s + "]"); } System.err.println(); } if (env.isVerbose()) { System.out.println("Configuration successfully updated"); } } } catch (Exception e) { System.err.println("Error: [ main ] " + e); if (env.isVerbose()) e.printStackTrace(); System.exit(1); } } } }
false
true
public static void main(String argv[]) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); boolean runIndex = true; if(argv.length == 0) { if (GraphicsEnvironment.isHeadless()) { System.err.println("No display available for the Graphical User Interface"); System.err.println(usage); System.exit(1); } else { MainFrame.main(argv); } //Run Scope GUI here I am running Indexing GUI for testing //new IndexerWizard(null).setVisible(true); } else { boolean searchRepositories = false; ArrayList<String> subFiles = new ArrayList<String>(); ArrayList<String> repositories = new ArrayList<String>(); String configFilename = null; String configHost = null; boolean addProjects = false; boolean refreshHistory = false; String defaultProject = null; boolean listFiles = false; boolean createDict = false; // Parse command line options: Getopt getopt = new Getopt(argv, options); try { getopt.parse(); } catch (ParseException ex) { System.err.println("OpenGrok: " + ex.getMessage()); System.err.println(usage); System.exit(1); } try{ int cmd; // We need to read the configuration file first, since we // will try to overwrite options.. while ((cmd = getopt.getOpt()) != -1) { if (cmd == 'R') { env.readConfiguration(new File(getopt.getOptarg())); break; } } // Now we can handle all the other options.. getopt.reset(); while ((cmd = getopt.getOpt()) != -1) { switch (cmd) { case 'l': listFiles = true; runIndex = false; break; case 't': createDict = true; runIndex = false; break; case 'q': env.setVerbose(false); break; case 'e': env.setGenerateHtml(false); break; case 'P': addProjects = true; break; case 'p': defaultProject = getopt.getOptarg(); break; case 'c': env.setCtags(getopt.getOptarg()); break; case 'w': { String webapp = getopt.getOptarg(); if (webapp.startsWith("/") || webapp.startsWith("http")) { ; } else { webapp = "/" + webapp; } if (webapp.endsWith("/")) { env.setUrlPrefix(webapp + "s?"); } else { env.setUrlPrefix(webapp + "/s?"); } } break; case 'W': configFilename = getopt.getOptarg(); break; case 'U': configHost = getopt.getOptarg(); break; case 'R': // already handled break; case 'n': runIndex = false; break; case 'H': refreshHistory = true; break; case 'h' : repositories.add(getopt.getOptarg()); break; case 'r': { if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setRemoteScmSupported(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setRemoteScmSupported(true); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r"); System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems"); System.err.println(" \"-Q off\" will ignore SCM for remote systems"); } } break; case 'O': { if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setOptimizeDatabase(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setOptimizeDatabase(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O"); System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation"); System.err.println(" \"-O off\" disable optimization of the index database"); } } break; case 'v': env.setVerbose(true); break; case 's': { File file = new File(getopt.getOptarg()); if (!file.isDirectory()) { System.err.println("ERROR: No such directory: " + file.toString()); System.exit(1); } env.setSourceRootFile(file); break; } case 'd': env.setDataRoot(getopt.getOptarg()); break; case 'i': env.getIgnoredNames().add(getopt.getOptarg()); break; case 'S' : searchRepositories = true; break; case 'Q' : if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setQuickContextScan(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setQuickContextScan(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q"); System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\""); System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file."); } break; case 'm' : { try { env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg())); } catch (NumberFormatException exp) { System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage()); System.exit(1); } break; } case 'a' : if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setAllowLeadingWildcard(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setAllowLeadingWildcard(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a"); System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard"); System.err.println(" \"-a off\" will disallow a search to start with a wildcard"); System.exit(1); } break; case 'A': { String[] arg = getopt.getOptarg().split(":"); if (arg.length != 2) { System.err.println("ERROR: You must specify: -A extension:class"); System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer"); System.err.println(" will use the C analyzer for all files ending with .foo"); System.err.println(" Ex: -A c:-"); System.err.println(" will disable the c-analyzer for for all files ending with .c"); System.exit(1); } arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase(); if (arg[1].equals("-")) { AnalyzerGuru.addExtension(arg[0], null); break; } try { AnalyzerGuru.addExtension( arg[0], AnalyzerGuru.findFactory(arg[1])); } catch (Exception e) { System.err.println("Unable to use " + arg[1] + " as a FileAnalyzerFactory"); e.printStackTrace(); System.exit(1); } } break; case 'L' : env.setWebappLAF(getopt.getOptarg()); break; default: System.err.println("Unknown option: " + (char)cmd); System.exit(1); } } int optind = getopt.getOptind(); if (optind != -1) { while (optind < argv.length) { subFiles.add(argv[optind]); ++optind; } } if (env.getDataRootPath() == null) { System.err.println("ERROR: Please specify a DATA ROOT path"); System.err.println(usage); System.exit(1); } if (env.getSourceRootFile() == null) { File srcConfig = new File(env.getDataRootPath(), "SRC_ROOT"); String line = null; if(srcConfig.exists()) { try { BufferedReader sr = new BufferedReader(new FileReader(srcConfig)); line = sr.readLine(); sr.close(); } catch (IOException e) { } } if(line == null) { System.err.println("ERROR: please specify a SRC_ROOT with option -s !"); System.err.println(usage); System.exit(1); } env.setSourceRoot(line); if (!env.getSourceRootFile().isDirectory()) { System.err.println("ERROR: No such directory:" + line); System.err.println(usage); System.exit(1); } } if (!env.validateExuberantCtags()) { System.exit(1); } if (searchRepositories) { if (env.isVerbose()) { System.out.println("Scanning for repositories..."); } env.getRepositories().clear(); long start = System.currentTimeMillis(); HistoryGuru.getInstance().addExternalRepositories(env.getSourceRootPath()); long time = (System.currentTimeMillis() - start) / 1000; if (env.isVerbose()) { System.out.println("Done searching for repositories (" + time + "s)"); } } if (addProjects) { File files[] = env.getSourceRootFile().listFiles(); List<Project> projects = env.getProjects(); projects.clear(); for (File file : files) { if (!file.getName().startsWith(".") && file.isDirectory()) { projects.add(new Project(file.getName(), "/" + file.getName())); } } // The projects should be sorted... Collections.sort(projects, new Comparator<Project>() { public int compare(Project p1, Project p2){ String s1 = p1.getDescription(); String s2 = p2.getDescription(); int ret; if (s1 == null) { ret = (s2 == null) ? 0 : 1; } else { ret = s1.compareTo(s2); } return ret; } }); } if (defaultProject != null) { for (Project p : env.getProjects()) { if (p.getPath().equals(defaultProject)) { env.setDefaultProject(p); break; } } } if (configFilename != null) { if (env.isVerbose()) { System.out.println("Writing configuration to " + configFilename); System.out.flush(); } env.writeConfiguration(new File(configFilename)); if (env.isVerbose()) { System.out.println("Done..."); System.out.flush(); } } if (refreshHistory) { HistoryGuru.getInstance().createCache(); } else if (repositories.size() > 0) { HistoryGuru.getInstance().createCache(repositories); } if (listFiles) { IndexDatabase.listAllFiles(subFiles); } if (createDict) { IndexDatabase.listFrequentTokens(subFiles); } if (runIndex) { IndexChangedListener progress = new DefaultIndexChangedListener(); if (subFiles.isEmpty() || !env.hasProjects()) { IndexDatabase.updateAll(progress); } else { for (String path : subFiles) { Project project = Project.getProject(path); if (project == null) { System.err.println("Warning: Could not find a project for \"" + path + "\""); } else { IndexDatabase db = new IndexDatabase(project); db.addIndexChangedListener(progress); db.update(); } } } } if (configHost != null) { String[] cfg = configHost.split(":"); if (env.isVerbose()) { System.out.println("Send configuration to: " + configHost); } if (cfg.length == 2) { try { InetAddress host = InetAddress.getByName(cfg[0]); RuntimeEnvironment.getInstance().writeConfiguration(host, Integer.parseInt(cfg[1])); } catch (Exception ex) { System.err.println("Failed to send configuration to " + configHost); ex.printStackTrace(); } } else { System.err.println("Syntax error: "); for (String s : cfg) { System.err.print("[" + s + "]"); } System.err.println(); } if (env.isVerbose()) { System.out.println("Configuration successfully updated"); } } } catch (Exception e) { System.err.println("Error: [ main ] " + e); if (env.isVerbose()) e.printStackTrace(); System.exit(1); } } }
public static void main(String argv[]) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); boolean runIndex = true; if(argv.length == 0) { if (GraphicsEnvironment.isHeadless()) { System.err.println("No display available for the Graphical User Interface"); System.err.println(usage); System.exit(1); } else { MainFrame.main(argv); } //Run Scope GUI here I am running Indexing GUI for testing //new IndexerWizard(null).setVisible(true); } else { boolean searchRepositories = false; ArrayList<String> subFiles = new ArrayList<String>(); ArrayList<String> repositories = new ArrayList<String>(); String configFilename = null; String configHost = null; boolean addProjects = false; boolean refreshHistory = false; String defaultProject = null; boolean listFiles = false; boolean createDict = false; // Parse command line options: Getopt getopt = new Getopt(argv, options); try { getopt.parse(); } catch (ParseException ex) { System.err.println("OpenGrok: " + ex.getMessage()); System.err.println(usage); System.exit(1); } try{ int cmd; // We need to read the configuration file first, since we // will try to overwrite options.. while ((cmd = getopt.getOpt()) != -1) { if (cmd == 'R') { env.readConfiguration(new File(getopt.getOptarg())); break; } } // Now we can handle all the other options.. getopt.reset(); while ((cmd = getopt.getOpt()) != -1) { switch (cmd) { case 'l': listFiles = true; runIndex = false; break; case 't': createDict = true; runIndex = false; break; case 'q': env.setVerbose(false); break; case 'e': env.setGenerateHtml(false); break; case 'P': addProjects = true; break; case 'p': defaultProject = getopt.getOptarg(); break; case 'c': env.setCtags(getopt.getOptarg()); break; case 'w': { String webapp = getopt.getOptarg(); if (webapp.startsWith("/") || webapp.startsWith("http")) { ; } else { webapp = "/" + webapp; } if (webapp.endsWith("/")) { env.setUrlPrefix(webapp + "s?"); } else { env.setUrlPrefix(webapp + "/s?"); } } break; case 'W': configFilename = getopt.getOptarg(); break; case 'U': configHost = getopt.getOptarg(); break; case 'R': // already handled break; case 'n': runIndex = false; break; case 'H': refreshHistory = true; break; case 'h' : repositories.add(getopt.getOptarg()); break; case 'r': { if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setRemoteScmSupported(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setRemoteScmSupported(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r"); System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems"); System.err.println(" \"-r off\" will ignore SCM for remote systems"); } } break; case 'O': { if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setOptimizeDatabase(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setOptimizeDatabase(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O"); System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation"); System.err.println(" \"-O off\" disable optimization of the index database"); } } break; case 'v': env.setVerbose(true); break; case 's': { File file = new File(getopt.getOptarg()); if (!file.isDirectory()) { System.err.println("ERROR: No such directory: " + file.toString()); System.exit(1); } env.setSourceRootFile(file); break; } case 'd': env.setDataRoot(getopt.getOptarg()); break; case 'i': env.getIgnoredNames().add(getopt.getOptarg()); break; case 'S' : searchRepositories = true; break; case 'Q' : if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setQuickContextScan(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setQuickContextScan(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q"); System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\""); System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file."); } break; case 'm' : { try { env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg())); } catch (NumberFormatException exp) { System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage()); System.exit(1); } break; } case 'a' : if (getopt.getOptarg().equalsIgnoreCase("on")) { env.setAllowLeadingWildcard(true); } else if (getopt.getOptarg().equalsIgnoreCase("off")) { env.setAllowLeadingWildcard(false); } else { System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a"); System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard"); System.err.println(" \"-a off\" will disallow a search to start with a wildcard"); System.exit(1); } break; case 'A': { String[] arg = getopt.getOptarg().split(":"); if (arg.length != 2) { System.err.println("ERROR: You must specify: -A extension:class"); System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer"); System.err.println(" will use the C analyzer for all files ending with .foo"); System.err.println(" Ex: -A c:-"); System.err.println(" will disable the c-analyzer for for all files ending with .c"); System.exit(1); } arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase(); if (arg[1].equals("-")) { AnalyzerGuru.addExtension(arg[0], null); break; } try { AnalyzerGuru.addExtension( arg[0], AnalyzerGuru.findFactory(arg[1])); } catch (Exception e) { System.err.println("Unable to use " + arg[1] + " as a FileAnalyzerFactory"); e.printStackTrace(); System.exit(1); } } break; case 'L' : env.setWebappLAF(getopt.getOptarg()); break; default: System.err.println("Unknown option: " + (char)cmd); System.exit(1); } } int optind = getopt.getOptind(); if (optind != -1) { while (optind < argv.length) { subFiles.add(argv[optind]); ++optind; } } if (env.getDataRootPath() == null) { System.err.println("ERROR: Please specify a DATA ROOT path"); System.err.println(usage); System.exit(1); } if (env.getSourceRootFile() == null) { File srcConfig = new File(env.getDataRootPath(), "SRC_ROOT"); String line = null; if(srcConfig.exists()) { try { BufferedReader sr = new BufferedReader(new FileReader(srcConfig)); line = sr.readLine(); sr.close(); } catch (IOException e) { } } if(line == null) { System.err.println("ERROR: please specify a SRC_ROOT with option -s !"); System.err.println(usage); System.exit(1); } env.setSourceRoot(line); if (!env.getSourceRootFile().isDirectory()) { System.err.println("ERROR: No such directory:" + line); System.err.println(usage); System.exit(1); } } if (!env.validateExuberantCtags()) { System.exit(1); } if (searchRepositories) { if (env.isVerbose()) { System.out.println("Scanning for repositories..."); } env.getRepositories().clear(); long start = System.currentTimeMillis(); HistoryGuru.getInstance().addExternalRepositories(env.getSourceRootPath()); long time = (System.currentTimeMillis() - start) / 1000; if (env.isVerbose()) { System.out.println("Done searching for repositories (" + time + "s)"); } } if (addProjects) { File files[] = env.getSourceRootFile().listFiles(); List<Project> projects = env.getProjects(); projects.clear(); for (File file : files) { if (!file.getName().startsWith(".") && file.isDirectory()) { projects.add(new Project(file.getName(), "/" + file.getName())); } } // The projects should be sorted... Collections.sort(projects, new Comparator<Project>() { public int compare(Project p1, Project p2){ String s1 = p1.getDescription(); String s2 = p2.getDescription(); int ret; if (s1 == null) { ret = (s2 == null) ? 0 : 1; } else { ret = s1.compareTo(s2); } return ret; } }); } if (defaultProject != null) { for (Project p : env.getProjects()) { if (p.getPath().equals(defaultProject)) { env.setDefaultProject(p); break; } } } if (configFilename != null) { if (env.isVerbose()) { System.out.println("Writing configuration to " + configFilename); System.out.flush(); } env.writeConfiguration(new File(configFilename)); if (env.isVerbose()) { System.out.println("Done..."); System.out.flush(); } } if (refreshHistory) { HistoryGuru.getInstance().createCache(); } else if (repositories.size() > 0) { HistoryGuru.getInstance().createCache(repositories); } if (listFiles) { IndexDatabase.listAllFiles(subFiles); } if (createDict) { IndexDatabase.listFrequentTokens(subFiles); } if (runIndex) { IndexChangedListener progress = new DefaultIndexChangedListener(); if (subFiles.isEmpty() || !env.hasProjects()) { IndexDatabase.updateAll(progress); } else { for (String path : subFiles) { Project project = Project.getProject(path); if (project == null) { System.err.println("Warning: Could not find a project for \"" + path + "\""); } else { IndexDatabase db = new IndexDatabase(project); db.addIndexChangedListener(progress); db.update(); } } } } if (configHost != null) { String[] cfg = configHost.split(":"); if (env.isVerbose()) { System.out.println("Send configuration to: " + configHost); } if (cfg.length == 2) { try { InetAddress host = InetAddress.getByName(cfg[0]); RuntimeEnvironment.getInstance().writeConfiguration(host, Integer.parseInt(cfg[1])); } catch (Exception ex) { System.err.println("Failed to send configuration to " + configHost); ex.printStackTrace(); } } else { System.err.println("Syntax error: "); for (String s : cfg) { System.err.print("[" + s + "]"); } System.err.println(); } if (env.isVerbose()) { System.out.println("Configuration successfully updated"); } } } catch (Exception e) { System.err.println("Error: [ main ] " + e); if (env.isVerbose()) e.printStackTrace(); System.exit(1); } } }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/display/DisplayView.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/display/DisplayView.java index ca40cdef5..4c23a724b 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/display/DisplayView.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/display/DisplayView.java @@ -1,488 +1,488 @@ /******************************************************************************* * Copyright (c) 2000, 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.jdt.internal.debug.ui.display; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jdt.debug.ui.IJavaDebugUIConstants; import org.eclipse.jdt.internal.debug.ui.EvaluationContextManager; import org.eclipse.jdt.internal.debug.ui.IJavaDebugHelpContextIds; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.internal.debug.ui.JDISourceViewer; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IFindReplaceTarget; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveListener2; import org.eclipse.ui.IViewReference; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.XMLMemento; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.commands.AbstractHandler; import org.eclipse.ui.commands.ExecutionException; import org.eclipse.ui.commands.HandlerSubmission; import org.eclipse.ui.commands.IHandler; import org.eclipse.ui.commands.IWorkbenchCommandSupport; import org.eclipse.ui.commands.Priority; import org.eclipse.ui.console.actions.ClearOutputAction; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.texteditor.FindReplaceAction; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds; public class DisplayView extends ViewPart implements ITextInputListener, IPerspectiveListener2 { class DataDisplay implements IDataDisplay { /** * @see IDataDisplay#clear() */ public void clear() { IDocument document= fSourceViewer.getDocument(); if (document != null) { document.set(""); //$NON-NLS-1$ } } /** * @see IDataDisplay#displayExpression(String) */ public void displayExpression(String expression) { IDocument document= fSourceViewer.getDocument(); int offset= document.getLength(); try { // add a cariage return if needed. if (offset != document.getLineInformationOfOffset(offset).getOffset()) { expression= System.getProperty("line.separator") + expression.trim(); //$NON-NLS-1$ } fSourceViewer.getDocument().replace(offset, 0, expression); fSourceViewer.setSelectedRange(offset + expression.length(), 0); fSourceViewer.revealRange(offset, expression.length()); } catch (BadLocationException ble) { JDIDebugUIPlugin.log(ble); } } /** * @see IDataDisplay#displayExpressionValue(String) */ public void displayExpressionValue(String value) { value= System.getProperty("line.separator") + '\t' + value; //$NON-NLS-1$ ITextSelection selection= (ITextSelection)fSourceViewer.getSelection(); int offset= selection.getOffset() + selection.getLength(); int length= value.length(); try { fSourceViewer.getDocument().replace(offset, 0, value); } catch (BadLocationException ble) { JDIDebugUIPlugin.log(ble); } fSourceViewer.setSelectedRange(offset + length, 0); fSourceViewer.revealRange(offset, length); } } protected IDataDisplay fDataDisplay= new DataDisplay(); protected IDocumentListener fDocumentListener= null; protected JDISourceViewer fSourceViewer; protected IAction fClearDisplayAction; protected DisplayViewAction fContentAssistAction; protected Map fGlobalActions= new HashMap(4); protected List fSelectionActions= new ArrayList(3); protected String fRestoredContents= null; /** * This memento allows the Display view to save and restore state * when it is closed and opened within a session. A different * memento is supplied by the platform for persistance at * workbench shutdown. */ private static IMemento fgMemento; private HandlerSubmission fSubmission; /** * @see ViewPart#createChild(IWorkbenchPartContainer) */ public void createPartControl(Composite parent) { int styles= SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION; fSourceViewer= new JDISourceViewer(parent, null, styles); fSourceViewer.configure(new DisplayViewerConfiguration()); fSourceViewer.getSelectionProvider().addSelectionChangedListener(getSelectionChangedListener()); IDocument doc= getRestoredDocument(); fSourceViewer.setDocument(doc); fSourceViewer.addTextInputListener(this); fRestoredContents= null; createActions(); initializeToolBar(); // create context menu MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { fillContextMenu(mgr); } }); Menu menu = menuMgr.createContextMenu(fSourceViewer.getTextWidget()); fSourceViewer.getTextWidget().setMenu(menu); getSite().registerContextMenu(menuMgr, fSourceViewer.getSelectionProvider()); getSite().setSelectionProvider(fSourceViewer.getSelectionProvider()); PlatformUI.getWorkbench().getHelpSystem().setHelp(fSourceViewer.getTextWidget(), IJavaDebugHelpContextIds.DISPLAY_VIEW); getSite().getWorkbenchWindow().addPerspectiveListener(this); } protected IDocument getRestoredDocument() { IDocument doc= null; if (fRestoredContents != null) { doc= new Document(fRestoredContents); } else { doc= new Document(); } JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); IDocumentPartitioner partitioner= tools.createDocumentPartitioner(); partitioner.connect(doc); doc.setDocumentPartitioner(partitioner); fDocumentListener= new IDocumentListener() { /** * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { } /** * @see IDocumentListener#documentChanged(DocumentEvent) */ public void documentChanged(DocumentEvent event) { updateAction(ActionFactory.FIND.getId()); } }; doc.addDocumentListener(fDocumentListener); return doc; } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#setFocus() */ public void setFocus() { if (fSourceViewer != null) { fSourceViewer.getControl().setFocus(); } } /** * Initialize the actions of this view */ protected void createActions() { fClearDisplayAction= new ClearOutputAction(fSourceViewer); IActionBars actionBars = getViewSite().getActionBars(); IAction action= new DisplayViewAction(this, ITextOperationTarget.CUT); action.setText(DisplayMessages.DisplayView_Cut_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Cut_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Cut_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.CUT.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.COPY); action.setText(DisplayMessages.DisplayView_Copy_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Copy_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Copy_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.COPY.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.PASTE); action.setText(DisplayMessages.DisplayView_Paste_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Paste_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Paste_Description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.PASTE.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.SELECT_ALL); action.setText(DisplayMessages.DisplayView_SelectAll_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_SelectAll_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_SelectAll_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.SELECT_ALL.getId(), action); //XXX Still using "old" resource access ResourceBundle bundle= ResourceBundle.getBundle("org.eclipse.jdt.internal.debug.ui.display.DisplayMessages"); //$NON-NLS-1$ - FindReplaceAction findReplaceAction = new FindReplaceAction(bundle, "find_replace_action.", this); //$NON-NLS-1$ + FindReplaceAction findReplaceAction = new FindReplaceAction(bundle, "find_replace_action_", this); //$NON-NLS-1$ findReplaceAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_REPLACE); setGlobalAction(actionBars, ActionFactory.FIND.getId(), findReplaceAction); fSelectionActions.add(ActionFactory.CUT.getId()); fSelectionActions.add(ActionFactory.COPY.getId()); fSelectionActions.add(ActionFactory.PASTE.getId()); fContentAssistAction= new DisplayViewAction(this, ISourceViewer.CONTENTASSIST_PROPOSALS); fContentAssistAction.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); fContentAssistAction.setText(DisplayMessages.DisplayView_Co_ntent_Assist_Ctrl_Space_1); //$NON-NLS-1$ fContentAssistAction.setDescription(DisplayMessages.DisplayView_Content_Assist_2); //$NON-NLS-1$ fContentAssistAction.setToolTipText(DisplayMessages.DisplayView_Content_Assist_2); //$NON-NLS-1$ fContentAssistAction.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_ELCL_CONTENT_ASSIST)); fContentAssistAction.setHoverImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_LCL_CONTENT_ASSIST)); fContentAssistAction.setDisabledImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_DLCL_CONTENT_ASSIST)); actionBars.updateActionBars(); IHandler handler = new AbstractHandler() { public Object execute(Map parameterValuesByName) throws ExecutionException { fContentAssistAction.run(); return null; } }; IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); fSubmission = new HandlerSubmission(null, null, getSite(), ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, handler, Priority.MEDIUM); //$NON-NLS-1$ commandSupport.addHandlerSubmission(fSubmission); } protected void setGlobalAction(IActionBars actionBars, String actionID, IAction action) { fGlobalActions.put(actionID, action); actionBars.setGlobalActionHandler(actionID, action); } /** * Configures the toolBar. */ private void initializeToolBar() { IToolBarManager tbm = getViewSite().getActionBars().getToolBarManager(); tbm.add(new Separator(IJavaDebugUIConstants.EVALUATION_GROUP)); tbm.add(fClearDisplayAction); getViewSite().getActionBars().updateActionBars(); } /** * Adds the context menu actions for the display view. */ protected void fillContextMenu(IMenuManager menu) { if (fSourceViewer.getDocument() == null) { return; } menu.add(new Separator(IJavaDebugUIConstants.EVALUATION_GROUP)); if (EvaluationContextManager.getEvaluationContext(this) != null) { menu.add(fContentAssistAction); } menu.add(new Separator()); menu.add((IAction) fGlobalActions.get(ActionFactory.CUT.getId())); menu.add((IAction) fGlobalActions.get(ActionFactory.COPY.getId())); menu.add((IAction) fGlobalActions.get(ActionFactory.PASTE.getId())); menu.add((IAction) fGlobalActions.get(ActionFactory.SELECT_ALL.getId())); menu.add(new Separator()); menu.add((IAction) fGlobalActions.get(ActionFactory.FIND.getId())); menu.add(fClearDisplayAction); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(Class) */ public Object getAdapter(Class required) { if (ITextOperationTarget.class.equals(required)) { return fSourceViewer.getTextOperationTarget(); } if (IFindReplaceTarget.class.equals(required)) { return fSourceViewer.getFindReplaceTarget(); } if (IDataDisplay.class.equals(required)) { return fDataDisplay; } if (ITextViewer.class.equals(required)) { return fSourceViewer; } return super.getAdapter(required); } protected void updateActions() { Iterator iterator = fSelectionActions.iterator(); while (iterator.hasNext()) { IAction action = (IAction) fGlobalActions.get(iterator.next()); if (action instanceof IUpdate) { ((IUpdate) action).update(); } } } /** * Saves the contents of the display view and the formatting. * * @see org.eclipse.ui.IViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fSourceViewer != null) { String contents= getContents(); if (contents != null) { memento.putTextData(contents); } } else if (fRestoredContents != null) { memento.putTextData(fRestoredContents); } } /** * Restores the contents of the display view and the formatting. * * @see org.eclipse.ui.IViewPart#init(IViewSite, IMemento) */ public void init(IViewSite site, IMemento memento) throws PartInitException { init(site); if (fgMemento != null) { memento= fgMemento; } if (memento != null) { fRestoredContents= memento.getTextData(); } } /** * Returns the entire trimmed contents of the current document. * If the contents are "empty" <code>null</code> is returned. */ private String getContents() { if (fSourceViewer != null) { IDocument doc= fSourceViewer.getDocument(); if (doc != null) { String contents= doc.get().trim(); if (contents.length() > 0) { return contents; } } } return null; } protected final ISelectionChangedListener getSelectionChangedListener() { return new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateSelectionDependentActions(); } }; } protected void updateSelectionDependentActions() { Iterator iterator= fSelectionActions.iterator(); while (iterator.hasNext()) updateAction((String)iterator.next()); } protected void updateAction(String actionId) { IAction action= (IAction)fGlobalActions.get(actionId); if (action instanceof IUpdate) { ((IUpdate) action).update(); } } /** * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { } /** * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { oldInput.removeDocumentListener(fDocumentListener); } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ public void dispose() { getSite().getWorkbenchWindow().removePerspectiveListener(this); if (fSourceViewer != null) { fSourceViewer.dispose(); } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); commandSupport.removeHandlerSubmission(fSubmission); super.dispose(); } /* (non-Javadoc) * @see org.eclipse.ui.IPerspectiveListener2#perspectiveChanged(org.eclipse.ui.IWorkbenchPage, org.eclipse.ui.IPerspectiveDescriptor, org.eclipse.ui.IWorkbenchPartReference, java.lang.String) */ public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective, IWorkbenchPartReference partRef, String changeId) { if (partRef instanceof IViewReference && changeId.equals(IWorkbenchPage.CHANGE_VIEW_HIDE)) { String id = ((IViewReference) partRef).getId(); if (id.equals(getViewSite().getId())) { // Display view closed. Persist contents. String contents= getContents(); if (contents != null) { fgMemento= XMLMemento.createWriteRoot("DisplayViewMemento"); //$NON-NLS-1$ fgMemento.putTextData(contents); } } } } /* (non-Javadoc) * @see org.eclipse.ui.IPerspectiveListener#perspectiveActivated(org.eclipse.ui.IWorkbenchPage, org.eclipse.ui.IPerspectiveDescriptor) */ public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) { } /* (non-Javadoc) * @see org.eclipse.ui.IPerspectiveListener#perspectiveChanged(org.eclipse.ui.IWorkbenchPage, org.eclipse.ui.IPerspectiveDescriptor, java.lang.String) */ public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective, String changeId) { } }
true
true
protected void createActions() { fClearDisplayAction= new ClearOutputAction(fSourceViewer); IActionBars actionBars = getViewSite().getActionBars(); IAction action= new DisplayViewAction(this, ITextOperationTarget.CUT); action.setText(DisplayMessages.DisplayView_Cut_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Cut_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Cut_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.CUT.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.COPY); action.setText(DisplayMessages.DisplayView_Copy_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Copy_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Copy_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.COPY.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.PASTE); action.setText(DisplayMessages.DisplayView_Paste_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Paste_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Paste_Description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.PASTE.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.SELECT_ALL); action.setText(DisplayMessages.DisplayView_SelectAll_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_SelectAll_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_SelectAll_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.SELECT_ALL.getId(), action); //XXX Still using "old" resource access ResourceBundle bundle= ResourceBundle.getBundle("org.eclipse.jdt.internal.debug.ui.display.DisplayMessages"); //$NON-NLS-1$ FindReplaceAction findReplaceAction = new FindReplaceAction(bundle, "find_replace_action.", this); //$NON-NLS-1$ findReplaceAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_REPLACE); setGlobalAction(actionBars, ActionFactory.FIND.getId(), findReplaceAction); fSelectionActions.add(ActionFactory.CUT.getId()); fSelectionActions.add(ActionFactory.COPY.getId()); fSelectionActions.add(ActionFactory.PASTE.getId()); fContentAssistAction= new DisplayViewAction(this, ISourceViewer.CONTENTASSIST_PROPOSALS); fContentAssistAction.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); fContentAssistAction.setText(DisplayMessages.DisplayView_Co_ntent_Assist_Ctrl_Space_1); //$NON-NLS-1$ fContentAssistAction.setDescription(DisplayMessages.DisplayView_Content_Assist_2); //$NON-NLS-1$ fContentAssistAction.setToolTipText(DisplayMessages.DisplayView_Content_Assist_2); //$NON-NLS-1$ fContentAssistAction.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_ELCL_CONTENT_ASSIST)); fContentAssistAction.setHoverImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_LCL_CONTENT_ASSIST)); fContentAssistAction.setDisabledImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_DLCL_CONTENT_ASSIST)); actionBars.updateActionBars(); IHandler handler = new AbstractHandler() { public Object execute(Map parameterValuesByName) throws ExecutionException { fContentAssistAction.run(); return null; } }; IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); fSubmission = new HandlerSubmission(null, null, getSite(), ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, handler, Priority.MEDIUM); //$NON-NLS-1$ commandSupport.addHandlerSubmission(fSubmission); }
protected void createActions() { fClearDisplayAction= new ClearOutputAction(fSourceViewer); IActionBars actionBars = getViewSite().getActionBars(); IAction action= new DisplayViewAction(this, ITextOperationTarget.CUT); action.setText(DisplayMessages.DisplayView_Cut_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Cut_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Cut_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.CUT.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.COPY); action.setText(DisplayMessages.DisplayView_Copy_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Copy_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Copy_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.COPY.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.PASTE); action.setText(DisplayMessages.DisplayView_Paste_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_Paste_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_Paste_Description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.PASTE.getId(), action); action= new DisplayViewAction(this, ITextOperationTarget.SELECT_ALL); action.setText(DisplayMessages.DisplayView_SelectAll_label); //$NON-NLS-1$ action.setToolTipText(DisplayMessages.DisplayView_SelectAll_tooltip); //$NON-NLS-1$ action.setDescription(DisplayMessages.DisplayView_SelectAll_description); //$NON-NLS-1$ setGlobalAction(actionBars, ActionFactory.SELECT_ALL.getId(), action); //XXX Still using "old" resource access ResourceBundle bundle= ResourceBundle.getBundle("org.eclipse.jdt.internal.debug.ui.display.DisplayMessages"); //$NON-NLS-1$ FindReplaceAction findReplaceAction = new FindReplaceAction(bundle, "find_replace_action_", this); //$NON-NLS-1$ findReplaceAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_REPLACE); setGlobalAction(actionBars, ActionFactory.FIND.getId(), findReplaceAction); fSelectionActions.add(ActionFactory.CUT.getId()); fSelectionActions.add(ActionFactory.COPY.getId()); fSelectionActions.add(ActionFactory.PASTE.getId()); fContentAssistAction= new DisplayViewAction(this, ISourceViewer.CONTENTASSIST_PROPOSALS); fContentAssistAction.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); fContentAssistAction.setText(DisplayMessages.DisplayView_Co_ntent_Assist_Ctrl_Space_1); //$NON-NLS-1$ fContentAssistAction.setDescription(DisplayMessages.DisplayView_Content_Assist_2); //$NON-NLS-1$ fContentAssistAction.setToolTipText(DisplayMessages.DisplayView_Content_Assist_2); //$NON-NLS-1$ fContentAssistAction.setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_ELCL_CONTENT_ASSIST)); fContentAssistAction.setHoverImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_LCL_CONTENT_ASSIST)); fContentAssistAction.setDisabledImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_DLCL_CONTENT_ASSIST)); actionBars.updateActionBars(); IHandler handler = new AbstractHandler() { public Object execute(Map parameterValuesByName) throws ExecutionException { fContentAssistAction.run(); return null; } }; IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); fSubmission = new HandlerSubmission(null, null, getSite(), ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, handler, Priority.MEDIUM); //$NON-NLS-1$ commandSupport.addHandlerSubmission(fSubmission); }
diff --git a/src/main/java/com/succinctllc/hazelcast/util/MultiMapProxy.java b/src/main/java/com/succinctllc/hazelcast/util/MultiMapProxy.java index 6ba762d..9bb61ef 100644 --- a/src/main/java/com/succinctllc/hazelcast/util/MultiMapProxy.java +++ b/src/main/java/com/succinctllc/hazelcast/util/MultiMapProxy.java @@ -1,163 +1,163 @@ package com.succinctllc.hazelcast.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import com.hazelcast.core.MultiMap; /** * This MultiMap implementation presents a consistent interface for using a MultiMap backed by * Guava or Hazelcast just to make some code a little cleaner. It might be nice to make this better * and use ReentrantReadWriteLocks to sychnonize the guava collections. Then we can implement * things nicer. * * @author Jason Clawson * */ public class MultiMapProxy<K, V> /*implements MultiMap<K, V>*/ { private final MultiMap<K, V> hcMultiMap; private final SetMultimap<K, V> guavaMultiMap; private MultiMapProxy(MultiMap<K, V> hcMultiMap) { this.hcMultiMap = hcMultiMap; this.guavaMultiMap = null; } private MultiMapProxy(SetMultimap<K, V> guavaMultiMap) { this.guavaMultiMap = guavaMultiMap; this.hcMultiMap = null; } public static <K,V> MultiMapProxy<K,V> localMultiMap(SetMultimap<K, V> guavaMultiMap) { return new MultiMapProxy<K,V>(Multimaps.<K,V>synchronizedSetMultimap(guavaMultiMap)); } public static <K,V> MultiMapProxy<K,V> clusteredMultiMap(MultiMap<K, V> hcMultiMap) { return new MultiMapProxy<K,V>(hcMultiMap); } public boolean put(K key, V value) { if(guavaMultiMap != null) return guavaMultiMap.put(key, value); return hcMultiMap.put(key, value); } public Collection<V> get(K key) { if(guavaMultiMap != null) { synchronized (guavaMultiMap) { Set<V> c = guavaMultiMap.get(key); if(c != null) return new HashSet<V>(c); else return null; } } return hcMultiMap.get(key); } public List<V> getAsList(K key) { if(guavaMultiMap != null) { synchronized (guavaMultiMap) { Collection<V> c = guavaMultiMap.get(key); if(c != null) - return new ArrayList<V>(); + return new ArrayList<V>(c); else return null; } } else { Collection<V> c = hcMultiMap.get(key); if(c != null) - return new ArrayList<V>(); + return new ArrayList<V>(c); else return null; } } public boolean remove(Object key, Object value) { if(guavaMultiMap != null) return guavaMultiMap.remove(key, value); return hcMultiMap.remove(key, value); } public Collection<V> remove(Object key) { return hcMultiMap.remove(key); } public Set<K> localKeySet() { if(guavaMultiMap != null) return keySet(); return hcMultiMap.localKeySet(); } public Set<K> keySet() { if(guavaMultiMap != null) { synchronized (guavaMultiMap) { Set<K> c = guavaMultiMap.keySet(); if(c != null) return new HashSet<K>(c); else return null; } } return hcMultiMap.keySet(); } public Collection<V> values() { if(guavaMultiMap != null) { synchronized (guavaMultiMap) { Collection<V> c = guavaMultiMap.values(); if(c != null) return new ArrayList<V>(c); else return null; } } return hcMultiMap.values(); } //don't feel like figuring out what to do with guava synchronization right now plus don't need it // public Set<Entry<K, V>> entrySet() { // if(guavaMultiMap != null) // return guavaMultiMap.entries(); // return hcMultiMap.entrySet(); // } public boolean containsKey(K key) { if(guavaMultiMap != null) return guavaMultiMap.containsKey(key); return hcMultiMap.containsKey(key); } public boolean containsValue(Object value) { if(guavaMultiMap != null) return guavaMultiMap.containsValue(value); return hcMultiMap.containsValue(value); } public boolean containsEntry(K key, V value) { if(guavaMultiMap != null) return guavaMultiMap.containsEntry(key, value); return hcMultiMap.containsEntry(key, value); } public int size() { if(guavaMultiMap != null) return guavaMultiMap.size(); return hcMultiMap.size(); } public void clear() { if(guavaMultiMap != null) guavaMultiMap.clear(); else hcMultiMap.clear(); } }
false
true
public List<V> getAsList(K key) { if(guavaMultiMap != null) { synchronized (guavaMultiMap) { Collection<V> c = guavaMultiMap.get(key); if(c != null) return new ArrayList<V>(); else return null; } } else { Collection<V> c = hcMultiMap.get(key); if(c != null) return new ArrayList<V>(); else return null; } }
public List<V> getAsList(K key) { if(guavaMultiMap != null) { synchronized (guavaMultiMap) { Collection<V> c = guavaMultiMap.get(key); if(c != null) return new ArrayList<V>(c); else return null; } } else { Collection<V> c = hcMultiMap.get(key); if(c != null) return new ArrayList<V>(c); else return null; } }
diff --git a/src/com/jidesoft/swing/JideBoxLayout.java b/src/com/jidesoft/swing/JideBoxLayout.java index 3b445020..20c2f574 100644 --- a/src/com/jidesoft/swing/JideBoxLayout.java +++ b/src/com/jidesoft/swing/JideBoxLayout.java @@ -1,901 +1,901 @@ /* * @(#)JideBoxLayout.java * * Copyright 2002 JIDE Software Inc. All rights reserved. */ package com.jidesoft.swing; import com.jidesoft.utils.SecurityUtils; import com.jidesoft.utils.SystemInfo; import com.jidesoft.dialog.JideOptionPane; import java.awt.*; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * JideBoxLayout is very similar to BoxLayout in the way that all components are arranged either from left to right or * from top to bottom. Different \ from BoxLayout, there are three possible constraints when adding component to this * layout - FIX, FLEXIBLE and VARY. <ul> <li>FIX: use the preferred size of the component and size is fixed * <li>FLEXIBLE: respect the preferred size of the component but size can be changed. <li>VARY: ignore preferred size. * Its size is calculated based how much area left. </ul> This is the default layout manager for {@link * com.jidesoft.swing.JideSplitPane}. */ public class JideBoxLayout implements LayoutManager2, Serializable { private static final Logger LOGGER = Logger.getLogger(JideBoxLayout.class.getName()); /** * True if resetToPreferredSizes has been invoked. */ private boolean doReset = true; /** * Axis, 0 for horizontal, or 1 for vertical. */ protected int _axis; protected Container _target; private int _gap = 0; protected int[] _componentSizes; /** * For FIX component, the width (or height if vertical) is and will always be the preferred width. */ public static final String FIX = "fix"; /** * FLEXIBLE components try to keep the preferred width. If there isn't enough space, all FLEXIBLE components will * shrink proportionally. */ public static final String FLEXIBLE = "flexible"; /** * For VARY component, the width will always be whatever width left. You can allow add multiple FIX or FLEXIBLE * components but only one VARY component is allowed. */ public static final String VARY = "vary"; private final HashMap<Component, Object> _constraintMap = new HashMap<Component, Object>(); /** * Specifies that components should be laid out left to right. */ public static final int X_AXIS = 0; /** * Specifies that components should be laid out top to bottom. */ public static final int Y_AXIS = 1; /** * Specifies that components should be laid out in the direction of a line of text as determined by the target * container's <code>ComponentOrientation</code> property. */ public static final int LINE_AXIS = 2; /** * Specifies that components should be laid out in the direction that lines flow across a page as determined by the * target container's <code>ComponentOrientation</code> property. */ public static final int PAGE_AXIS = 3; private boolean _resetWhenInvalidate = true; private boolean _alwaysLayout = true; private static final long serialVersionUID = -183922972679053590L; /** * Creates a layout manager that will lay out components along the given axis. * * @param target the container that needs to be laid out * @throws AWTError if the value of <code>axis</code> is invalid */ public JideBoxLayout(Container target) { this(target, X_AXIS); } /** * @param target the container that needs to be laid out * @param axis the axis to lay out components along. Can be one of: <code>JideBoxLayout.X_AXIS</code>, * <code>JideBoxLayout.Y_AXIS</code>, <code>JideBoxLayout.LINE_AXIS</code> or * <code>JideBoxLayout.PAGE_AXIS</code> */ public JideBoxLayout(Container target, int axis) { this(target, axis, 0); } /** * @param target the container that needs to be laid out * @param axis the axis to lay out components along. Can be one of: <code>JideBoxLayout.X_AXIS</code>, * <code>JideBoxLayout.Y_AXIS</code>, <code>JideBoxLayout.LINE_AXIS</code> or * <code>JideBoxLayout.PAGE_AXIS</code> * @param gap the gap */ public JideBoxLayout(Container target, int axis, int gap) { if (axis != X_AXIS && axis != Y_AXIS && axis != LINE_AXIS && axis != PAGE_AXIS) { throw new AWTError("Invalid axis"); } _axis = axis; _target = target; _gap = gap; } /** * Lays out the specified container. * * @param container the container to be laid out */ public void layoutContainer(Container container) { synchronized (container.getTreeLock()) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(this + " layoutContainer started"); } Dimension containerSize = container.getSize(); if (containerSize.height <= 0 || containerSize.width <= 0) { return; } Insets insets = _target.getInsets(); if (doReset) { _componentSizes = new int[_target.getComponentCount()]; int availableSize = getAvailableSize(containerSize, insets); availableSize -= getGapSize(); if (availableSize <= 0) { return; } boolean success = calculateComponentSizes(availableSize, 0, _target.getComponentCount()); if (!success) { if (!isAlwaysLayout() && "false".equals(SecurityUtils.getProperty("JideBoxLayout.alwaysLayout", "false"))) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); setComponentToSize(comp, 0, 0, insets, containerSize); // set size to zero to clear the layout } redoLayout(container); } return; } doReset = false; if (_componentSizes.length == 0) { container.repaint(); // repaint when the last component is removed. } } else { int totalSize = 0; for (int componentSize : _componentSizes) { totalSize += componentSize; } boolean containerResized = totalSize + getGapSize() != getSizeForPrimaryAxis(containerSize); if (containerResized) { int availableSize = getAvailableSize(containerSize, insets); availableSize -= getGapSize(); if (availableSize <= 0) { return; } boolean success = calculateComponentSizes(availableSize, 0, _target.getComponentCount()); if (!success) { if (!isAlwaysLayout() && "false".equals(SecurityUtils.getProperty("JideBoxLayout.alwaysLayout", "false"))) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); setComponentToSize(comp, 0, 0, insets, containerSize); // set size to zero to clear the layout } redoLayout(container); } return; } } } ComponentOrientation o = _target.getComponentOrientation(); boolean ltr = o.isLeftToRight(); int location = getSizeForPrimaryAxis(insets, true); boolean needRedoLayout = false; if (!ltr && resolveAxis(_axis, o) == X_AXIS) { location = containerSize.width - location; } for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); int oldSize = getPreferredSizeOfComponent(comp); if (!ltr && resolveAxis(_axis, o) == X_AXIS) { location -= _componentSizes[i]; setComponentToSize(comp, _componentSizes[i], location, insets, containerSize); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("layoutContainer index: " + i + " size: " + _componentSizes[i]); } if (_componentSizes[i] != 0) location -= _gap; } else { setComponentToSize(comp, _componentSizes[i], location, insets, containerSize); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("layoutContainer index: " + i + " size: " + _componentSizes[i]); } location += _componentSizes[i]; if (_componentSizes[i] != 0) location += _gap; } int newSize = getPreferredSizeOfComponent(comp); if (newSize != oldSize) { needRedoLayout = true; } } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("layoutContainer ended"); } if (_target instanceof JideOptionPane) { for (int i = 0; i < container.getComponentCount(); i++) { container.getComponent(i).invalidate(); } if (needRedoLayout) { redoLayout(container); } } } } private void redoLayout(Container container) { Component parent = container.getParent(); while (parent != null) { if (parent instanceof Dialog) { break; } parent = parent.getParent(); } if (parent != null) { ((Dialog) parent).pack(); } } protected boolean calculateComponentSizes(int availableSize, int startIndex, int endIndex) { int availableSizeExcludeFixed = availableSize; int varMinSize = 0; int flexMinSize = 0; int varIndex = -1; int totalFlexSize = 0; int totalFlexSizeMinusMin = 0; int lastFlexIndex = -1; int lastNoneZeroFlexIndex = -1; for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { availableSizeExcludeFixed -= Math.max(preferredSize, minimumSize); } else if (VARY.equals(constraint)) { varIndex = i; getPreferredSizeOf(comp, i); // there is a bug in jdk1.5 which minimum size returns a large number if preferred size is not call. varMinSize = minimumSize; } else /* if (FLEXIBLE.equals(constraint)) */ { if (preferredSize > minimumSize) { totalFlexSizeMinusMin += preferredSize - minimumSize; } totalFlexSize += preferredSize; flexMinSize += minimumSize; lastFlexIndex = i; // prevent the zero width column has a column width like 1 or 2 eventually if (preferredSize != 0) { lastNoneZeroFlexIndex = i; } } } if (!isAlwaysLayout() && "false".equals(SecurityUtils.getProperty("JideBoxLayout.alwaysLayout", "false")) && availableSizeExcludeFixed - varMinSize < 0) { return false; } boolean hasVary = varIndex != -1; boolean expand = availableSizeExcludeFixed - varMinSize >= totalFlexSize; if (!hasVary || (hasVary && !expand)) { double resizeRatio; if (expand) { resizeRatio = totalFlexSize == 0 ? 0 : (double) (availableSizeExcludeFixed - varMinSize) / (double) totalFlexSize; } else { resizeRatio = totalFlexSizeMinusMin == 0 ? 0 : (double) (availableSizeExcludeFixed - varMinSize - flexMinSize) / (double) totalFlexSizeMinusMin; } for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { setComponentSize(i, 0); } else { Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { setComponentSize(i, Math.max(preferredSize, minimumSize)); } else if (VARY.equals(constraint)) { setComponentSize(i, varMinSize); } else /* if (FLEXIBLE.equals(constraint)) */ { if (expand) { setComponentSize(i, (int) (preferredSize * resizeRatio)); } else { setComponentSize(i, minimumSize + (int) ((preferredSize - minimumSize) * resizeRatio)); } } } } } else { // if (expand && hasVary) { // VARY component get all extra spaces. for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { setComponentSize(i, 0); } else { Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { setComponentSize(i, Math.max(preferredSize, minimumSize)); } else if (VARY.equals(constraint)) { setComponentSize(i, availableSizeExcludeFixed - totalFlexSize); } else /* if (FLEXIBLE.equals(constraint)) */ { setComponentSize(i, Math.max(preferredSize, minimumSize)); } } } } int totalActualSize = 0; for (int i = startIndex; i < endIndex; i++) { totalActualSize += _componentSizes[i]; } if (totalActualSize != availableSize) { if (varIndex != -1) { setComponentSizeByGap(varIndex, availableSize - totalActualSize); } else if (lastNoneZeroFlexIndex != -1) { setComponentSizeByGap(lastNoneZeroFlexIndex, availableSize - totalActualSize); } else if (lastFlexIndex != -1) { setComponentSizeByGap(lastFlexIndex, availableSize - totalActualSize); } } return true; } private void setComponentSizeByGap(int index, int gap) { if (SystemInfo.isJdk15Above() && _target.getComponent(index).isMinimumSizeSet()) { setComponentSize(index, Math.max(_componentSizes[index] + gap, getSizeForPrimaryAxis(_target.getComponent(index).getMinimumSize()))); } else { setComponentSize(index, _componentSizes[index] + gap); } } private void setComponentSize(int index, int size) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setComponentSize index: " + index + " size: " + size); } _componentSizes[index] = size; } /** * If the layout manager uses a per-component string, adds the component <code>comp</code> to the layout, * associating it with the string specified by <code>name</code>. * * @param name the string to be associated with the component * @param component the component to be added */ public void addLayoutComponent(String name, Component component) { layoutReset(); } /** * Returns the minimum size needed to contain the children. The width is the sum of all the children min widths and * the height is the largest of the children minimum heights. */ public Dimension minimumLayoutSize(Container container) { int minPrimary = 0; int minSecondary = 0; Insets insets = _target.getInsets(); synchronized (container.getTreeLock()) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Object constraint = _constraintMap.get(comp); Dimension minimumSize = comp.getMinimumSize(); if (FIX.equals(constraint)) { minPrimary += getPreferredSizeOfComponent(comp); } else { minPrimary += getSizeForPrimaryAxis(minimumSize); } int secSize = getSizeForSecondaryAxis(minimumSize); if (secSize > minSecondary) minSecondary = secSize; } if (insets != null) { minPrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); minSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } } ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return new Dimension(minPrimary + getGapSize(), minSecondary); } else { return new Dimension(minSecondary, minPrimary + getGapSize()); } } /** * Returns the preferred size needed to contain the children. The width is the sum of all the children preferred * widths and the height is the largest of the children preferred heights. */ public Dimension preferredLayoutSize(Container container) { int prePrimary = 0; int preSecondary = 0; Insets insets = _target.getInsets(); synchronized (container.getTreeLock()) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Dimension preferredSize = getPreferredSizeOf(comp, i); prePrimary += getSizeForPrimaryAxis(preferredSize); int secSize = getSizeForSecondaryAxis(preferredSize); if (secSize > preSecondary) preSecondary = secSize; } if (insets != null) { prePrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); preSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } } if (_axis == 0) { return new Dimension(prePrimary + getGapSize(), preSecondary); } else { return new Dimension(preSecondary, prePrimary + getGapSize()); } } private int getGapSize() { if (_gap == 0) { return 0; } else { int count = 0; for (int i = 0; i < _target.getComponentCount(); i++) { if (_target.getComponent(i).isVisible()) { count++; } } return Math.max(0, (count - 1)) * _gap; } } /** * Removes the specified component from the layout. * * @param comp the component to be removed */ public void removeLayoutComponent(Component comp) { _constraintMap.remove(comp); if (comp instanceof JideSplitPaneDivider) layoutReset(); } // // LayoutManager2 // /** * Adds the specified component to the layout, using the specified constraint object. * * @param comp the component to be added * @param constraints where/how the component is added to the layout. */ public void addLayoutComponent(Component comp, Object constraints) { if (constraints == null) _constraintMap.put(comp, FLEXIBLE); else _constraintMap.put(comp, constraints); layoutReset(); } private void layoutReset() { doReset = true; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(this + " layoutReset"); } } /** * Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to * other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 * is aligned the furthest away from the origin, 0.5 is centered, etc. */ public synchronized float getLayoutAlignmentX(Container target) { return 0.0f; } /** * Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to * other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 * is aligned the furthest away from the origin, 0.5 is centered, etc. */ public synchronized float getLayoutAlignmentY(Container target) { return 0.0f; } /** * Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. */ public synchronized void invalidateLayout(Container c) { if (isResetWhenInvalidate() || componentCountChanged(c)) { layoutReset(); } } protected boolean componentCountChanged(Container c) { if (_componentSizes == null) { return true; } int oldLength = 0; for (int _componentSize : _componentSizes) { if (_componentSize > 0) { oldLength++; } } int newLength = 0; for (int i = 0; i < c.getComponentCount(); i++) { if (c.getComponent(i).isVisible()) { newLength++; } } return newLength != oldLength; } /** * Returns the maximum layout size, which is Integer.MAX_VALUE in both directions. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Returns the width of the passed in Components preferred size. * @param c the component * @return the preferred size of the component. */ protected int getPreferredSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getPreferredSize()); } /** * Returns the width of the passed in Components minimum size. * @param c the component * @return the minimum size of the component. */ int getMinimumSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getMinimumSize()); } /** * Returns the width of the passed in component. * @param c the component * @return the size of the component. */ protected int getSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getSize()); } /** * Returns the available width based on the container size and Insets. * @param containerSize the size of the container * @param insets the insets * @return the available size. */ protected int getAvailableSize(Dimension containerSize, Insets insets) { if (insets == null) return getSizeForPrimaryAxis(containerSize); return (getSizeForPrimaryAxis(containerSize) - (getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false))); } /** * Returns the left inset, unless the Insets are null in which case 0 is returned. * * @param insets the insets * @return the initial location. */ protected int getInitialLocation(Insets insets) { if (insets != null) return getSizeForPrimaryAxis(insets, true); return 0; } /** * Sets the width of the component c to be size, placing its x location at location, y to the insets.top and height * to the containersize.height less the top and bottom insets. * * @param c the component * @param size the size of the component * @param location the location of the component * @param insets the insets of the component * @param containerSize the size of the container */ protected void setComponentToSize(Component c, int size, int location, Insets insets, Dimension containerSize) { if (insets != null) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { c.setBounds(Math.max(location, 0), Math.max(insets.top, 0), Math.max(size, 0), Math.max(containerSize.height - (insets.top + insets.bottom), 0)); } else { c.setBounds(Math.max(insets.left, 0), Math.max(location, 0), Math.max(containerSize.width - (insets.left + insets.right), 0), Math.max(size, 0)); } } else { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { c.setBounds(Math.max(location, 0), 0, Math.max(size, 0), Math.max(containerSize.height, 0)); } else { c.setBounds(0, Math.max(location, 0), Math.max(containerSize.width, 0), Math.max(size, 0)); } } } /* * If the axis == 0, the width is returned, otherwise the height. */ int getSizeForPrimaryAxis(Dimension size) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return size.width; } else { return size.height; } } /* * If the axis == X_AXIS, the width is returned, otherwise the height. */ int getSizeForSecondaryAxis(Dimension size) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return size.height; } else { return size.width; } } /* * Returns a particular value of the inset identified by the axis and <code>isTop</code><p>. axis isTop 0 true - * left 0 false - right 1 true - top 1 false - bottom */ int getSizeForPrimaryAxis(Insets insets, boolean isTop) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { if (isTop) { return insets.left; } else { return insets.right; } } else { if (isTop) { return insets.top; } else { return insets.bottom; } } } /* * Returns a particular value of the inset identified by the axis and <code>isTop</code><p>. axis isTop 0 true - * left 0 false - right 1 true - top 1 false - bottom */ int getSizeForSecondaryAxis(Insets insets, boolean isTop) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { if (isTop) { return insets.top; } else { return insets.bottom; } } else { if (isTop) { return insets.left; } else { return insets.right; } } } /** * Gets the map of constraints. * * @return the map of constraints */ public Map<Component, Object> getConstraintMap() { return _constraintMap; } /** * Given one of the 4 axis values, resolve it to an absolute axis. The relative axis values, PAGE_AXIS and LINE_AXIS * are converted to their absolute counterpart given the target's ComponentOrientation value. The absolute axes, * X_AXIS and Y_AXIS are returned unmodified. * * @param axis the axis to resolve * @param o the ComponentOrientation to resolve against * @return the resolved axis */ protected static int resolveAxis(int axis, ComponentOrientation o) { int absoluteAxis; if (axis == LINE_AXIS) { absoluteAxis = o.isHorizontal() ? X_AXIS : Y_AXIS; } else if (axis == PAGE_AXIS) { absoluteAxis = o.isHorizontal() ? Y_AXIS : X_AXIS; } else { absoluteAxis = axis; } return absoluteAxis; } /** * Gets the gap between each component. * * @return the gap between each component. */ public int getGap() { return _gap; } /** * Sets the gap between each component. Make sure you cal doLayout() after you change the gap. * * @param gap the gap */ public void setGap(int gap) { _gap = gap; } protected Dimension getPreferredSizeOf(Component comp, int atIndex) { Dimension preferredSize = comp.getPreferredSize(); Dimension minimumSize = comp.getMinimumSize(); if (preferredSize.height < minimumSize.height) { preferredSize.height = minimumSize.height; } if (preferredSize.width < minimumSize.width) { preferredSize.width = minimumSize.width; } Dimension maximumSize = comp.getMaximumSize(); - if (preferredSize.height > maximumSize.height) { + if (preferredSize.height > maximumSize.height && maximumSize.height != 32767) { // 32767 is hard-coded inside Swing. If you set maximum size to null, the maximum size is 32767. preferredSize.height = maximumSize.height; } - if (preferredSize.width > maximumSize.width) { + if (preferredSize.width > maximumSize.width && maximumSize.height != 32767) { preferredSize.width = maximumSize.width; } return preferredSize; } /** * Checks of the layout should be reset when {@link #invalidateLayout(java.awt.Container)} is called. * * @return true or false. */ public boolean isResetWhenInvalidate() { return _resetWhenInvalidate; } /** * Sets the flag if the layout should be reset when {@link #invalidateLayout(java.awt.Container)} is called. * * @param resetWhenInvalidate the flag */ public void setResetWhenInvalidate(boolean resetWhenInvalidate) { _resetWhenInvalidate = resetWhenInvalidate; } /** * Gets the axis. * * @return the axis. */ public int getAxis() { return _axis; } /** * Sets the axis. After changing the axis, you need to call doLayout method on the container which has this layout. * * @param axis the new axis. */ public void setAxis(int axis) { _axis = axis; } /** * Checks if the alwaysLayout flag is true. If true, the layout manager will layout the components even there is no * way to satisfy the minimum size requirements from all FIXED components. By default, it is true. * * @return true or false. */ public boolean isAlwaysLayout() { return _alwaysLayout; } /** * Sets the alwaysLayout flag. * * @param alwaysLayout true to always layout components even there is no way to satisfy the minimum size * requirements from all FIXED components. */ public void setAlwaysLayout(boolean alwaysLayout) { _alwaysLayout = alwaysLayout; } }
false
true
protected boolean calculateComponentSizes(int availableSize, int startIndex, int endIndex) { int availableSizeExcludeFixed = availableSize; int varMinSize = 0; int flexMinSize = 0; int varIndex = -1; int totalFlexSize = 0; int totalFlexSizeMinusMin = 0; int lastFlexIndex = -1; int lastNoneZeroFlexIndex = -1; for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { availableSizeExcludeFixed -= Math.max(preferredSize, minimumSize); } else if (VARY.equals(constraint)) { varIndex = i; getPreferredSizeOf(comp, i); // there is a bug in jdk1.5 which minimum size returns a large number if preferred size is not call. varMinSize = minimumSize; } else /* if (FLEXIBLE.equals(constraint)) */ { if (preferredSize > minimumSize) { totalFlexSizeMinusMin += preferredSize - minimumSize; } totalFlexSize += preferredSize; flexMinSize += minimumSize; lastFlexIndex = i; // prevent the zero width column has a column width like 1 or 2 eventually if (preferredSize != 0) { lastNoneZeroFlexIndex = i; } } } if (!isAlwaysLayout() && "false".equals(SecurityUtils.getProperty("JideBoxLayout.alwaysLayout", "false")) && availableSizeExcludeFixed - varMinSize < 0) { return false; } boolean hasVary = varIndex != -1; boolean expand = availableSizeExcludeFixed - varMinSize >= totalFlexSize; if (!hasVary || (hasVary && !expand)) { double resizeRatio; if (expand) { resizeRatio = totalFlexSize == 0 ? 0 : (double) (availableSizeExcludeFixed - varMinSize) / (double) totalFlexSize; } else { resizeRatio = totalFlexSizeMinusMin == 0 ? 0 : (double) (availableSizeExcludeFixed - varMinSize - flexMinSize) / (double) totalFlexSizeMinusMin; } for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { setComponentSize(i, 0); } else { Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { setComponentSize(i, Math.max(preferredSize, minimumSize)); } else if (VARY.equals(constraint)) { setComponentSize(i, varMinSize); } else /* if (FLEXIBLE.equals(constraint)) */ { if (expand) { setComponentSize(i, (int) (preferredSize * resizeRatio)); } else { setComponentSize(i, minimumSize + (int) ((preferredSize - minimumSize) * resizeRatio)); } } } } } else { // if (expand && hasVary) { // VARY component get all extra spaces. for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { setComponentSize(i, 0); } else { Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { setComponentSize(i, Math.max(preferredSize, minimumSize)); } else if (VARY.equals(constraint)) { setComponentSize(i, availableSizeExcludeFixed - totalFlexSize); } else /* if (FLEXIBLE.equals(constraint)) */ { setComponentSize(i, Math.max(preferredSize, minimumSize)); } } } } int totalActualSize = 0; for (int i = startIndex; i < endIndex; i++) { totalActualSize += _componentSizes[i]; } if (totalActualSize != availableSize) { if (varIndex != -1) { setComponentSizeByGap(varIndex, availableSize - totalActualSize); } else if (lastNoneZeroFlexIndex != -1) { setComponentSizeByGap(lastNoneZeroFlexIndex, availableSize - totalActualSize); } else if (lastFlexIndex != -1) { setComponentSizeByGap(lastFlexIndex, availableSize - totalActualSize); } } return true; } private void setComponentSizeByGap(int index, int gap) { if (SystemInfo.isJdk15Above() && _target.getComponent(index).isMinimumSizeSet()) { setComponentSize(index, Math.max(_componentSizes[index] + gap, getSizeForPrimaryAxis(_target.getComponent(index).getMinimumSize()))); } else { setComponentSize(index, _componentSizes[index] + gap); } } private void setComponentSize(int index, int size) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setComponentSize index: " + index + " size: " + size); } _componentSizes[index] = size; } /** * If the layout manager uses a per-component string, adds the component <code>comp</code> to the layout, * associating it with the string specified by <code>name</code>. * * @param name the string to be associated with the component * @param component the component to be added */ public void addLayoutComponent(String name, Component component) { layoutReset(); } /** * Returns the minimum size needed to contain the children. The width is the sum of all the children min widths and * the height is the largest of the children minimum heights. */ public Dimension minimumLayoutSize(Container container) { int minPrimary = 0; int minSecondary = 0; Insets insets = _target.getInsets(); synchronized (container.getTreeLock()) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Object constraint = _constraintMap.get(comp); Dimension minimumSize = comp.getMinimumSize(); if (FIX.equals(constraint)) { minPrimary += getPreferredSizeOfComponent(comp); } else { minPrimary += getSizeForPrimaryAxis(minimumSize); } int secSize = getSizeForSecondaryAxis(minimumSize); if (secSize > minSecondary) minSecondary = secSize; } if (insets != null) { minPrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); minSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } } ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return new Dimension(minPrimary + getGapSize(), minSecondary); } else { return new Dimension(minSecondary, minPrimary + getGapSize()); } } /** * Returns the preferred size needed to contain the children. The width is the sum of all the children preferred * widths and the height is the largest of the children preferred heights. */ public Dimension preferredLayoutSize(Container container) { int prePrimary = 0; int preSecondary = 0; Insets insets = _target.getInsets(); synchronized (container.getTreeLock()) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Dimension preferredSize = getPreferredSizeOf(comp, i); prePrimary += getSizeForPrimaryAxis(preferredSize); int secSize = getSizeForSecondaryAxis(preferredSize); if (secSize > preSecondary) preSecondary = secSize; } if (insets != null) { prePrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); preSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } } if (_axis == 0) { return new Dimension(prePrimary + getGapSize(), preSecondary); } else { return new Dimension(preSecondary, prePrimary + getGapSize()); } } private int getGapSize() { if (_gap == 0) { return 0; } else { int count = 0; for (int i = 0; i < _target.getComponentCount(); i++) { if (_target.getComponent(i).isVisible()) { count++; } } return Math.max(0, (count - 1)) * _gap; } } /** * Removes the specified component from the layout. * * @param comp the component to be removed */ public void removeLayoutComponent(Component comp) { _constraintMap.remove(comp); if (comp instanceof JideSplitPaneDivider) layoutReset(); } // // LayoutManager2 // /** * Adds the specified component to the layout, using the specified constraint object. * * @param comp the component to be added * @param constraints where/how the component is added to the layout. */ public void addLayoutComponent(Component comp, Object constraints) { if (constraints == null) _constraintMap.put(comp, FLEXIBLE); else _constraintMap.put(comp, constraints); layoutReset(); } private void layoutReset() { doReset = true; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(this + " layoutReset"); } } /** * Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to * other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 * is aligned the furthest away from the origin, 0.5 is centered, etc. */ public synchronized float getLayoutAlignmentX(Container target) { return 0.0f; } /** * Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to * other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 * is aligned the furthest away from the origin, 0.5 is centered, etc. */ public synchronized float getLayoutAlignmentY(Container target) { return 0.0f; } /** * Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. */ public synchronized void invalidateLayout(Container c) { if (isResetWhenInvalidate() || componentCountChanged(c)) { layoutReset(); } } protected boolean componentCountChanged(Container c) { if (_componentSizes == null) { return true; } int oldLength = 0; for (int _componentSize : _componentSizes) { if (_componentSize > 0) { oldLength++; } } int newLength = 0; for (int i = 0; i < c.getComponentCount(); i++) { if (c.getComponent(i).isVisible()) { newLength++; } } return newLength != oldLength; } /** * Returns the maximum layout size, which is Integer.MAX_VALUE in both directions. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Returns the width of the passed in Components preferred size. * @param c the component * @return the preferred size of the component. */ protected int getPreferredSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getPreferredSize()); } /** * Returns the width of the passed in Components minimum size. * @param c the component * @return the minimum size of the component. */ int getMinimumSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getMinimumSize()); } /** * Returns the width of the passed in component. * @param c the component * @return the size of the component. */ protected int getSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getSize()); } /** * Returns the available width based on the container size and Insets. * @param containerSize the size of the container * @param insets the insets * @return the available size. */ protected int getAvailableSize(Dimension containerSize, Insets insets) { if (insets == null) return getSizeForPrimaryAxis(containerSize); return (getSizeForPrimaryAxis(containerSize) - (getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false))); } /** * Returns the left inset, unless the Insets are null in which case 0 is returned. * * @param insets the insets * @return the initial location. */ protected int getInitialLocation(Insets insets) { if (insets != null) return getSizeForPrimaryAxis(insets, true); return 0; } /** * Sets the width of the component c to be size, placing its x location at location, y to the insets.top and height * to the containersize.height less the top and bottom insets. * * @param c the component * @param size the size of the component * @param location the location of the component * @param insets the insets of the component * @param containerSize the size of the container */ protected void setComponentToSize(Component c, int size, int location, Insets insets, Dimension containerSize) { if (insets != null) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { c.setBounds(Math.max(location, 0), Math.max(insets.top, 0), Math.max(size, 0), Math.max(containerSize.height - (insets.top + insets.bottom), 0)); } else { c.setBounds(Math.max(insets.left, 0), Math.max(location, 0), Math.max(containerSize.width - (insets.left + insets.right), 0), Math.max(size, 0)); } } else { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { c.setBounds(Math.max(location, 0), 0, Math.max(size, 0), Math.max(containerSize.height, 0)); } else { c.setBounds(0, Math.max(location, 0), Math.max(containerSize.width, 0), Math.max(size, 0)); } } } /* * If the axis == 0, the width is returned, otherwise the height. */ int getSizeForPrimaryAxis(Dimension size) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return size.width; } else { return size.height; } } /* * If the axis == X_AXIS, the width is returned, otherwise the height. */ int getSizeForSecondaryAxis(Dimension size) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return size.height; } else { return size.width; } } /* * Returns a particular value of the inset identified by the axis and <code>isTop</code><p>. axis isTop 0 true - * left 0 false - right 1 true - top 1 false - bottom */ int getSizeForPrimaryAxis(Insets insets, boolean isTop) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { if (isTop) { return insets.left; } else { return insets.right; } } else { if (isTop) { return insets.top; } else { return insets.bottom; } } } /* * Returns a particular value of the inset identified by the axis and <code>isTop</code><p>. axis isTop 0 true - * left 0 false - right 1 true - top 1 false - bottom */ int getSizeForSecondaryAxis(Insets insets, boolean isTop) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { if (isTop) { return insets.top; } else { return insets.bottom; } } else { if (isTop) { return insets.left; } else { return insets.right; } } } /** * Gets the map of constraints. * * @return the map of constraints */ public Map<Component, Object> getConstraintMap() { return _constraintMap; } /** * Given one of the 4 axis values, resolve it to an absolute axis. The relative axis values, PAGE_AXIS and LINE_AXIS * are converted to their absolute counterpart given the target's ComponentOrientation value. The absolute axes, * X_AXIS and Y_AXIS are returned unmodified. * * @param axis the axis to resolve * @param o the ComponentOrientation to resolve against * @return the resolved axis */ protected static int resolveAxis(int axis, ComponentOrientation o) { int absoluteAxis; if (axis == LINE_AXIS) { absoluteAxis = o.isHorizontal() ? X_AXIS : Y_AXIS; } else if (axis == PAGE_AXIS) { absoluteAxis = o.isHorizontal() ? Y_AXIS : X_AXIS; } else { absoluteAxis = axis; } return absoluteAxis; } /** * Gets the gap between each component. * * @return the gap between each component. */ public int getGap() { return _gap; } /** * Sets the gap between each component. Make sure you cal doLayout() after you change the gap. * * @param gap the gap */ public void setGap(int gap) { _gap = gap; } protected Dimension getPreferredSizeOf(Component comp, int atIndex) { Dimension preferredSize = comp.getPreferredSize(); Dimension minimumSize = comp.getMinimumSize(); if (preferredSize.height < minimumSize.height) { preferredSize.height = minimumSize.height; } if (preferredSize.width < minimumSize.width) { preferredSize.width = minimumSize.width; } Dimension maximumSize = comp.getMaximumSize(); if (preferredSize.height > maximumSize.height) { preferredSize.height = maximumSize.height; } if (preferredSize.width > maximumSize.width) { preferredSize.width = maximumSize.width; } return preferredSize; } /** * Checks of the layout should be reset when {@link #invalidateLayout(java.awt.Container)} is called. * * @return true or false. */ public boolean isResetWhenInvalidate() { return _resetWhenInvalidate; } /** * Sets the flag if the layout should be reset when {@link #invalidateLayout(java.awt.Container)} is called. * * @param resetWhenInvalidate the flag */ public void setResetWhenInvalidate(boolean resetWhenInvalidate) { _resetWhenInvalidate = resetWhenInvalidate; } /** * Gets the axis. * * @return the axis. */ public int getAxis() { return _axis; } /** * Sets the axis. After changing the axis, you need to call doLayout method on the container which has this layout. * * @param axis the new axis. */ public void setAxis(int axis) { _axis = axis; } /** * Checks if the alwaysLayout flag is true. If true, the layout manager will layout the components even there is no * way to satisfy the minimum size requirements from all FIXED components. By default, it is true. * * @return true or false. */ public boolean isAlwaysLayout() { return _alwaysLayout; } /** * Sets the alwaysLayout flag. * * @param alwaysLayout true to always layout components even there is no way to satisfy the minimum size * requirements from all FIXED components. */ public void setAlwaysLayout(boolean alwaysLayout) { _alwaysLayout = alwaysLayout; } }
protected boolean calculateComponentSizes(int availableSize, int startIndex, int endIndex) { int availableSizeExcludeFixed = availableSize; int varMinSize = 0; int flexMinSize = 0; int varIndex = -1; int totalFlexSize = 0; int totalFlexSizeMinusMin = 0; int lastFlexIndex = -1; int lastNoneZeroFlexIndex = -1; for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { availableSizeExcludeFixed -= Math.max(preferredSize, minimumSize); } else if (VARY.equals(constraint)) { varIndex = i; getPreferredSizeOf(comp, i); // there is a bug in jdk1.5 which minimum size returns a large number if preferred size is not call. varMinSize = minimumSize; } else /* if (FLEXIBLE.equals(constraint)) */ { if (preferredSize > minimumSize) { totalFlexSizeMinusMin += preferredSize - minimumSize; } totalFlexSize += preferredSize; flexMinSize += minimumSize; lastFlexIndex = i; // prevent the zero width column has a column width like 1 or 2 eventually if (preferredSize != 0) { lastNoneZeroFlexIndex = i; } } } if (!isAlwaysLayout() && "false".equals(SecurityUtils.getProperty("JideBoxLayout.alwaysLayout", "false")) && availableSizeExcludeFixed - varMinSize < 0) { return false; } boolean hasVary = varIndex != -1; boolean expand = availableSizeExcludeFixed - varMinSize >= totalFlexSize; if (!hasVary || (hasVary && !expand)) { double resizeRatio; if (expand) { resizeRatio = totalFlexSize == 0 ? 0 : (double) (availableSizeExcludeFixed - varMinSize) / (double) totalFlexSize; } else { resizeRatio = totalFlexSizeMinusMin == 0 ? 0 : (double) (availableSizeExcludeFixed - varMinSize - flexMinSize) / (double) totalFlexSizeMinusMin; } for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { setComponentSize(i, 0); } else { Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { setComponentSize(i, Math.max(preferredSize, minimumSize)); } else if (VARY.equals(constraint)) { setComponentSize(i, varMinSize); } else /* if (FLEXIBLE.equals(constraint)) */ { if (expand) { setComponentSize(i, (int) (preferredSize * resizeRatio)); } else { setComponentSize(i, minimumSize + (int) ((preferredSize - minimumSize) * resizeRatio)); } } } } } else { // if (expand && hasVary) { // VARY component get all extra spaces. for (int i = startIndex; i < endIndex; i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { setComponentSize(i, 0); } else { Object constraint = _constraintMap.get(comp); int minimumSize = getSizeForPrimaryAxis(comp.getMinimumSize()); int preferredSize = getSizeForPrimaryAxis(getPreferredSizeOf(comp, i)); if (FIX.equals(constraint)) { setComponentSize(i, Math.max(preferredSize, minimumSize)); } else if (VARY.equals(constraint)) { setComponentSize(i, availableSizeExcludeFixed - totalFlexSize); } else /* if (FLEXIBLE.equals(constraint)) */ { setComponentSize(i, Math.max(preferredSize, minimumSize)); } } } } int totalActualSize = 0; for (int i = startIndex; i < endIndex; i++) { totalActualSize += _componentSizes[i]; } if (totalActualSize != availableSize) { if (varIndex != -1) { setComponentSizeByGap(varIndex, availableSize - totalActualSize); } else if (lastNoneZeroFlexIndex != -1) { setComponentSizeByGap(lastNoneZeroFlexIndex, availableSize - totalActualSize); } else if (lastFlexIndex != -1) { setComponentSizeByGap(lastFlexIndex, availableSize - totalActualSize); } } return true; } private void setComponentSizeByGap(int index, int gap) { if (SystemInfo.isJdk15Above() && _target.getComponent(index).isMinimumSizeSet()) { setComponentSize(index, Math.max(_componentSizes[index] + gap, getSizeForPrimaryAxis(_target.getComponent(index).getMinimumSize()))); } else { setComponentSize(index, _componentSizes[index] + gap); } } private void setComponentSize(int index, int size) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setComponentSize index: " + index + " size: " + size); } _componentSizes[index] = size; } /** * If the layout manager uses a per-component string, adds the component <code>comp</code> to the layout, * associating it with the string specified by <code>name</code>. * * @param name the string to be associated with the component * @param component the component to be added */ public void addLayoutComponent(String name, Component component) { layoutReset(); } /** * Returns the minimum size needed to contain the children. The width is the sum of all the children min widths and * the height is the largest of the children minimum heights. */ public Dimension minimumLayoutSize(Container container) { int minPrimary = 0; int minSecondary = 0; Insets insets = _target.getInsets(); synchronized (container.getTreeLock()) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Object constraint = _constraintMap.get(comp); Dimension minimumSize = comp.getMinimumSize(); if (FIX.equals(constraint)) { minPrimary += getPreferredSizeOfComponent(comp); } else { minPrimary += getSizeForPrimaryAxis(minimumSize); } int secSize = getSizeForSecondaryAxis(minimumSize); if (secSize > minSecondary) minSecondary = secSize; } if (insets != null) { minPrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); minSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } } ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return new Dimension(minPrimary + getGapSize(), minSecondary); } else { return new Dimension(minSecondary, minPrimary + getGapSize()); } } /** * Returns the preferred size needed to contain the children. The width is the sum of all the children preferred * widths and the height is the largest of the children preferred heights. */ public Dimension preferredLayoutSize(Container container) { int prePrimary = 0; int preSecondary = 0; Insets insets = _target.getInsets(); synchronized (container.getTreeLock()) { for (int i = 0; i < _target.getComponentCount(); i++) { Component comp = _target.getComponent(i); if (!comp.isVisible()) { continue; } Dimension preferredSize = getPreferredSizeOf(comp, i); prePrimary += getSizeForPrimaryAxis(preferredSize); int secSize = getSizeForSecondaryAxis(preferredSize); if (secSize > preSecondary) preSecondary = secSize; } if (insets != null) { prePrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); preSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } } if (_axis == 0) { return new Dimension(prePrimary + getGapSize(), preSecondary); } else { return new Dimension(preSecondary, prePrimary + getGapSize()); } } private int getGapSize() { if (_gap == 0) { return 0; } else { int count = 0; for (int i = 0; i < _target.getComponentCount(); i++) { if (_target.getComponent(i).isVisible()) { count++; } } return Math.max(0, (count - 1)) * _gap; } } /** * Removes the specified component from the layout. * * @param comp the component to be removed */ public void removeLayoutComponent(Component comp) { _constraintMap.remove(comp); if (comp instanceof JideSplitPaneDivider) layoutReset(); } // // LayoutManager2 // /** * Adds the specified component to the layout, using the specified constraint object. * * @param comp the component to be added * @param constraints where/how the component is added to the layout. */ public void addLayoutComponent(Component comp, Object constraints) { if (constraints == null) _constraintMap.put(comp, FLEXIBLE); else _constraintMap.put(comp, constraints); layoutReset(); } private void layoutReset() { doReset = true; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(this + " layoutReset"); } } /** * Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to * other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 * is aligned the furthest away from the origin, 0.5 is centered, etc. */ public synchronized float getLayoutAlignmentX(Container target) { return 0.0f; } /** * Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to * other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 * is aligned the furthest away from the origin, 0.5 is centered, etc. */ public synchronized float getLayoutAlignmentY(Container target) { return 0.0f; } /** * Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. */ public synchronized void invalidateLayout(Container c) { if (isResetWhenInvalidate() || componentCountChanged(c)) { layoutReset(); } } protected boolean componentCountChanged(Container c) { if (_componentSizes == null) { return true; } int oldLength = 0; for (int _componentSize : _componentSizes) { if (_componentSize > 0) { oldLength++; } } int newLength = 0; for (int i = 0; i < c.getComponentCount(); i++) { if (c.getComponent(i).isVisible()) { newLength++; } } return newLength != oldLength; } /** * Returns the maximum layout size, which is Integer.MAX_VALUE in both directions. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Returns the width of the passed in Components preferred size. * @param c the component * @return the preferred size of the component. */ protected int getPreferredSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getPreferredSize()); } /** * Returns the width of the passed in Components minimum size. * @param c the component * @return the minimum size of the component. */ int getMinimumSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getMinimumSize()); } /** * Returns the width of the passed in component. * @param c the component * @return the size of the component. */ protected int getSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getSize()); } /** * Returns the available width based on the container size and Insets. * @param containerSize the size of the container * @param insets the insets * @return the available size. */ protected int getAvailableSize(Dimension containerSize, Insets insets) { if (insets == null) return getSizeForPrimaryAxis(containerSize); return (getSizeForPrimaryAxis(containerSize) - (getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false))); } /** * Returns the left inset, unless the Insets are null in which case 0 is returned. * * @param insets the insets * @return the initial location. */ protected int getInitialLocation(Insets insets) { if (insets != null) return getSizeForPrimaryAxis(insets, true); return 0; } /** * Sets the width of the component c to be size, placing its x location at location, y to the insets.top and height * to the containersize.height less the top and bottom insets. * * @param c the component * @param size the size of the component * @param location the location of the component * @param insets the insets of the component * @param containerSize the size of the container */ protected void setComponentToSize(Component c, int size, int location, Insets insets, Dimension containerSize) { if (insets != null) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { c.setBounds(Math.max(location, 0), Math.max(insets.top, 0), Math.max(size, 0), Math.max(containerSize.height - (insets.top + insets.bottom), 0)); } else { c.setBounds(Math.max(insets.left, 0), Math.max(location, 0), Math.max(containerSize.width - (insets.left + insets.right), 0), Math.max(size, 0)); } } else { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { c.setBounds(Math.max(location, 0), 0, Math.max(size, 0), Math.max(containerSize.height, 0)); } else { c.setBounds(0, Math.max(location, 0), Math.max(containerSize.width, 0), Math.max(size, 0)); } } } /* * If the axis == 0, the width is returned, otherwise the height. */ int getSizeForPrimaryAxis(Dimension size) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return size.width; } else { return size.height; } } /* * If the axis == X_AXIS, the width is returned, otherwise the height. */ int getSizeForSecondaryAxis(Dimension size) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { return size.height; } else { return size.width; } } /* * Returns a particular value of the inset identified by the axis and <code>isTop</code><p>. axis isTop 0 true - * left 0 false - right 1 true - top 1 false - bottom */ int getSizeForPrimaryAxis(Insets insets, boolean isTop) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { if (isTop) { return insets.left; } else { return insets.right; } } else { if (isTop) { return insets.top; } else { return insets.bottom; } } } /* * Returns a particular value of the inset identified by the axis and <code>isTop</code><p>. axis isTop 0 true - * left 0 false - right 1 true - top 1 false - bottom */ int getSizeForSecondaryAxis(Insets insets, boolean isTop) { ComponentOrientation o = _target.getComponentOrientation(); if (resolveAxis(_axis, o) == X_AXIS) { if (isTop) { return insets.top; } else { return insets.bottom; } } else { if (isTop) { return insets.left; } else { return insets.right; } } } /** * Gets the map of constraints. * * @return the map of constraints */ public Map<Component, Object> getConstraintMap() { return _constraintMap; } /** * Given one of the 4 axis values, resolve it to an absolute axis. The relative axis values, PAGE_AXIS and LINE_AXIS * are converted to their absolute counterpart given the target's ComponentOrientation value. The absolute axes, * X_AXIS and Y_AXIS are returned unmodified. * * @param axis the axis to resolve * @param o the ComponentOrientation to resolve against * @return the resolved axis */ protected static int resolveAxis(int axis, ComponentOrientation o) { int absoluteAxis; if (axis == LINE_AXIS) { absoluteAxis = o.isHorizontal() ? X_AXIS : Y_AXIS; } else if (axis == PAGE_AXIS) { absoluteAxis = o.isHorizontal() ? Y_AXIS : X_AXIS; } else { absoluteAxis = axis; } return absoluteAxis; } /** * Gets the gap between each component. * * @return the gap between each component. */ public int getGap() { return _gap; } /** * Sets the gap between each component. Make sure you cal doLayout() after you change the gap. * * @param gap the gap */ public void setGap(int gap) { _gap = gap; } protected Dimension getPreferredSizeOf(Component comp, int atIndex) { Dimension preferredSize = comp.getPreferredSize(); Dimension minimumSize = comp.getMinimumSize(); if (preferredSize.height < minimumSize.height) { preferredSize.height = minimumSize.height; } if (preferredSize.width < minimumSize.width) { preferredSize.width = minimumSize.width; } Dimension maximumSize = comp.getMaximumSize(); if (preferredSize.height > maximumSize.height && maximumSize.height != 32767) { // 32767 is hard-coded inside Swing. If you set maximum size to null, the maximum size is 32767. preferredSize.height = maximumSize.height; } if (preferredSize.width > maximumSize.width && maximumSize.height != 32767) { preferredSize.width = maximumSize.width; } return preferredSize; } /** * Checks of the layout should be reset when {@link #invalidateLayout(java.awt.Container)} is called. * * @return true or false. */ public boolean isResetWhenInvalidate() { return _resetWhenInvalidate; } /** * Sets the flag if the layout should be reset when {@link #invalidateLayout(java.awt.Container)} is called. * * @param resetWhenInvalidate the flag */ public void setResetWhenInvalidate(boolean resetWhenInvalidate) { _resetWhenInvalidate = resetWhenInvalidate; } /** * Gets the axis. * * @return the axis. */ public int getAxis() { return _axis; } /** * Sets the axis. After changing the axis, you need to call doLayout method on the container which has this layout. * * @param axis the new axis. */ public void setAxis(int axis) { _axis = axis; } /** * Checks if the alwaysLayout flag is true. If true, the layout manager will layout the components even there is no * way to satisfy the minimum size requirements from all FIXED components. By default, it is true. * * @return true or false. */ public boolean isAlwaysLayout() { return _alwaysLayout; } /** * Sets the alwaysLayout flag. * * @param alwaysLayout true to always layout components even there is no way to satisfy the minimum size * requirements from all FIXED components. */ public void setAlwaysLayout(boolean alwaysLayout) { _alwaysLayout = alwaysLayout; } }
diff --git a/_Code/Warranty/src/ch/zhaw/warranty/CardListActivity.java b/_Code/Warranty/src/ch/zhaw/warranty/CardListActivity.java index dea09a5..823917e 100644 --- a/_Code/Warranty/src/ch/zhaw/warranty/CardListActivity.java +++ b/_Code/Warranty/src/ch/zhaw/warranty/CardListActivity.java @@ -1,88 +1,88 @@ package ch.zhaw.warranty; import java.util.ArrayList; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import ch.zhaw.warranty.card.WarrantyCard; public class CardListActivity extends ListActivity { private ArrayAdapter<WarrantyCard> arrayAdapter; private ListView list; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_card_list, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { boolean handled = false; switch (item.getItemId()){ case R.id.card_menu_sortByTitle: setOrder("title"); handled = true; break; case R.id.card_menu_sortByDate: setOrder("created_at"); handled = true; break; case R.id.card_menu_sortByDesc: setOrder("description"); handled = true; break; } return handled; } @Override public void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.activity_card_list); list = getListView(); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(CardListActivity.this, CardActivity.class); WarrantyCard card = (WarrantyCard) list.getItemAtPosition(position); intent.putExtra("id", card.get_id()); intent.putExtra("status", "edit"); startActivity(intent); } }); list.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { WarrantyCard card = (WarrantyCard) list.getItemAtPosition(position); - Toast.makeText(getApplicationContext(), card.getTitle() + "deleted",Toast.LENGTH_LONG).show(); + Toast.makeText(getApplicationContext(), card.getTitle() + " deleted",Toast.LENGTH_LONG).show(); MainActivity.tblwarranty.deleteCard(card.get_id()); finish(); startActivity(getIntent()); return true; } }); setOrder("title"); } private void setOrder(String order){ ArrayList<WarrantyCard> cards = MainActivity.tblwarranty.getAllCardsOrdered(order); arrayAdapter = new ArrayAdapter<WarrantyCard>(this, android.R.layout.simple_list_item_1,cards); setListAdapter(arrayAdapter); } }
true
true
public void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.activity_card_list); list = getListView(); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(CardListActivity.this, CardActivity.class); WarrantyCard card = (WarrantyCard) list.getItemAtPosition(position); intent.putExtra("id", card.get_id()); intent.putExtra("status", "edit"); startActivity(intent); } }); list.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { WarrantyCard card = (WarrantyCard) list.getItemAtPosition(position); Toast.makeText(getApplicationContext(), card.getTitle() + "deleted",Toast.LENGTH_LONG).show(); MainActivity.tblwarranty.deleteCard(card.get_id()); finish(); startActivity(getIntent()); return true; } }); setOrder("title"); }
public void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.activity_card_list); list = getListView(); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(CardListActivity.this, CardActivity.class); WarrantyCard card = (WarrantyCard) list.getItemAtPosition(position); intent.putExtra("id", card.get_id()); intent.putExtra("status", "edit"); startActivity(intent); } }); list.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { WarrantyCard card = (WarrantyCard) list.getItemAtPosition(position); Toast.makeText(getApplicationContext(), card.getTitle() + " deleted",Toast.LENGTH_LONG).show(); MainActivity.tblwarranty.deleteCard(card.get_id()); finish(); startActivity(getIntent()); return true; } }); setOrder("title"); }
diff --git a/src/lang/LuaTypedInsideBlockDelegate.java b/src/lang/LuaTypedInsideBlockDelegate.java index 65ae5e6e..e8148e70 100644 --- a/src/lang/LuaTypedInsideBlockDelegate.java +++ b/src/lang/LuaTypedInsideBlockDelegate.java @@ -1,57 +1,62 @@ /* * Copyright 2011 Jon S Akhtar (Sylvanaar) * * 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.sylvanaar.idea.Lua.lang; import com.intellij.codeInsight.editorActions.TypedHandlerDelegate; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.sylvanaar.idea.Lua.lang.psi.LuaFunctionDefinition; /** * Created by IntelliJ IDEA. * User: Jon S Akhtar * Date: 1/30/11 * Time: 6:45 AM */ public class LuaTypedInsideBlockDelegate extends TypedHandlerDelegate { @Override public Result charTyped(char c, final Project project, final Editor editor, final PsiFile file) { Document document = editor.getDocument(); int caretOffset = editor.getCaretModel().getOffset(); PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); PsiElement e = file.findElementAt(caretOffset-1); PsiElement e1 = file.findElementAt(caretOffset); + // This handles the case where we are already inside parens. + // for example a(b,c function(|) where | is the cursor + boolean preserveCloseParen = false; if (c == '(' && e1 !=null && e1.getText().equals(")")) { - e = e1; c = ')'; + e = e1; + c = ')'; + preserveCloseParen = true; } if (c==')' && e != null && e.getContext() instanceof LuaFunctionDefinition ) { - document.insertString(e.getTextOffset()+1, " end"); + document.insertString(e.getTextOffset()+1, preserveCloseParen ? " end)" :" end"); return Result.STOP; } return super.charTyped(c, project, editor, file); } }
false
true
public Result charTyped(char c, final Project project, final Editor editor, final PsiFile file) { Document document = editor.getDocument(); int caretOffset = editor.getCaretModel().getOffset(); PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); PsiElement e = file.findElementAt(caretOffset-1); PsiElement e1 = file.findElementAt(caretOffset); if (c == '(' && e1 !=null && e1.getText().equals(")")) { e = e1; c = ')'; } if (c==')' && e != null && e.getContext() instanceof LuaFunctionDefinition ) { document.insertString(e.getTextOffset()+1, " end"); return Result.STOP; } return super.charTyped(c, project, editor, file); }
public Result charTyped(char c, final Project project, final Editor editor, final PsiFile file) { Document document = editor.getDocument(); int caretOffset = editor.getCaretModel().getOffset(); PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); PsiElement e = file.findElementAt(caretOffset-1); PsiElement e1 = file.findElementAt(caretOffset); // This handles the case where we are already inside parens. // for example a(b,c function(|) where | is the cursor boolean preserveCloseParen = false; if (c == '(' && e1 !=null && e1.getText().equals(")")) { e = e1; c = ')'; preserveCloseParen = true; } if (c==')' && e != null && e.getContext() instanceof LuaFunctionDefinition ) { document.insertString(e.getTextOffset()+1, preserveCloseParen ? " end)" :" end"); return Result.STOP; } return super.charTyped(c, project, editor, file); }
diff --git a/code/src/main/java/se/altran/java/lambda/streamdemo/StreamDemo.java b/code/src/main/java/se/altran/java/lambda/streamdemo/StreamDemo.java index 1656f5c..31c1bda 100644 --- a/code/src/main/java/se/altran/java/lambda/streamdemo/StreamDemo.java +++ b/code/src/main/java/se/altran/java/lambda/streamdemo/StreamDemo.java @@ -1,34 +1,38 @@ package se.altran.java.lambda.streamdemo; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamDemo { public static void main (String[] args) { int max = 24; System.out.format("Checking numbers [1..%d]...%n", max); long start = System.nanoTime(); + System.out.println("Sequential"); + System.out.println("---------------"); System.out.format("Odd numbers: %s%n", naturalNumbersUpTo(max).stream().filter(StreamDemo::heavyIsOdd).collect(Collectors.<Integer>toList())); long end = System.nanoTime(); - System.out.format("Time taken: %f%n", (end - start) /1.0e9); + System.out.format("Time taken: %f%n%n%n", (end - start) /1.0e9); start = System.nanoTime(); + System.out.println("Parallel"); + System.out.println("---------------"); System.out.format("Odd numbers: %s%n", naturalNumbersUpTo(max).parallelStream().filter(StreamDemo::heavyIsOdd).collect(Collectors.<Integer>toList())); end = System.nanoTime(); System.out.format("Time taken: %f%n", (end - start) /1.0e9); } public static List<Integer> naturalNumbersUpTo(int max) { return Stream.iterate(1, num -> num + 1).limit(max).collect(Collectors.<Integer>toList()); } public static boolean heavyIsOdd(Integer number) { try { Thread.sleep(1000); } catch (InterruptedException e) { } return number % 2 == 1; } }
false
true
public static void main (String[] args) { int max = 24; System.out.format("Checking numbers [1..%d]...%n", max); long start = System.nanoTime(); System.out.format("Odd numbers: %s%n", naturalNumbersUpTo(max).stream().filter(StreamDemo::heavyIsOdd).collect(Collectors.<Integer>toList())); long end = System.nanoTime(); System.out.format("Time taken: %f%n", (end - start) /1.0e9); start = System.nanoTime(); System.out.format("Odd numbers: %s%n", naturalNumbersUpTo(max).parallelStream().filter(StreamDemo::heavyIsOdd).collect(Collectors.<Integer>toList())); end = System.nanoTime(); System.out.format("Time taken: %f%n", (end - start) /1.0e9); }
public static void main (String[] args) { int max = 24; System.out.format("Checking numbers [1..%d]...%n", max); long start = System.nanoTime(); System.out.println("Sequential"); System.out.println("---------------"); System.out.format("Odd numbers: %s%n", naturalNumbersUpTo(max).stream().filter(StreamDemo::heavyIsOdd).collect(Collectors.<Integer>toList())); long end = System.nanoTime(); System.out.format("Time taken: %f%n%n%n", (end - start) /1.0e9); start = System.nanoTime(); System.out.println("Parallel"); System.out.println("---------------"); System.out.format("Odd numbers: %s%n", naturalNumbersUpTo(max).parallelStream().filter(StreamDemo::heavyIsOdd).collect(Collectors.<Integer>toList())); end = System.nanoTime(); System.out.format("Time taken: %f%n", (end - start) /1.0e9); }
diff --git a/src/org/art_core/dev/cinder/input/XmlInputReader.java b/src/org/art_core/dev/cinder/input/XmlInputReader.java index 05ed7ab..125cfca 100644 --- a/src/org/art_core/dev/cinder/input/XmlInputReader.java +++ b/src/org/art_core/dev/cinder/input/XmlInputReader.java @@ -1,176 +1,176 @@ package org.art_core.dev.cinder.input; import java.io.File; import java.util.ArrayList; import java.util.Collection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.art_core.dev.cinder.CinderLog; import org.art_core.dev.cinder.model.IItem; import org.art_core.dev.cinder.model.PropertiesItem; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XmlInputReader implements IInputHandler { private String sFilename = null; private final Collection<IItem> items = new ArrayList<IItem>(); /** * Reads an XML file from an URI. * * @param String * the URI */ @Override public void readFromUri(final String sUri) { this.readFromFile(sUri, true); } /** * Reads an XML file from the local file system. * * @param String * the location of the file */ @Override public void readFromLocalFile(final String sFile) { this.readFromFile(sFile, false); } /** * Reads an XML file from the workspace. * * @param String * the file name */ @Override public void readFromWorkspaceFile(final String sWorkspaceFile) { final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); final String sPath = root.getLocation().toString(); String sFilename; sFilename = sPath + "/" + sWorkspaceFile; CinderLog.logDebug("XIR:RFW:" + sPath + "_" + sWorkspaceFile); this.readFromFile(sFilename, false); } /** * Reads an XML file. * * @param sFile * the filename * @param bRemote * Whether the file is given via URI */ protected void readFromFile(final String sFile, final boolean bRemote) { this.sFilename = sFile; File fXml = null; Document doc = null; final DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = fac.newDocumentBuilder(); if (bRemote) { doc = builder.parse(sFile); CinderLog.logDebug("XIR:RFF_R:" + sFile); } else { fXml = new File(sFile); doc = builder.parse(fXml); CinderLog.logDebug("XIR:RFF_L:" + sFile + "_" + fXml.length()); } } catch (Exception e) { CinderLog.logError(e); } this.parseDocument(doc); } /** * Parses a Document. * * @param doc */ protected void parseDocument(final Document doc) { try { PropertiesItem xItem; NodeList fileNodes, errorNodes; Integer eLine, eColumn; String eSeverity, eMessage, ePattern, sTargetFileName; Element fileElement, error; - fileNodes = doc.getChildNodes().item(0).getChildNodes(); + fileNodes = doc.getElementsByTagName("padawan").item(0).getChildNodes(); // handle all <file name=""> sections for (int fIndex = 0; fIndex < fileNodes.getLength(); fIndex++) { // ignore whitespace final int iNodeType = fileNodes.item(fIndex).getNodeType(); if (iNodeType == Node.ELEMENT_NODE) { fileElement = (Element) fileNodes.item(fIndex); sTargetFileName = fileElement.getAttribute("name"); CinderLog.logDebug("XIR::read:" + sTargetFileName); errorNodes = fileElement.getChildNodes(); // handle all <error line="" column="" severity="" // message="" pattern=""> sections for (int eIndex = 0; eIndex < errorNodes.getLength(); eIndex++) { // ignore whitespace if (errorNodes.item(eIndex).getNodeType() == Node.ELEMENT_NODE) { error = (Element) errorNodes.item(eIndex); eLine = Integer.valueOf(error.getAttribute("line")); eColumn = Integer.valueOf(error .getAttribute("column")); eSeverity = error.getAttribute("severity"); eMessage = error.getAttribute("message"); ePattern = error.getAttribute("pattern"); CinderLog.logDebug("XIR:" + eLine + ":" + eColumn + ":" + eSeverity); xItem = new PropertiesItem(ePattern, sTargetFileName, PropertiesItem.chooseType(eSeverity), eLine.intValue(), eColumn.intValue()); xItem.setMessage(eMessage); items.add(xItem); } } } } } catch (Exception e) { CinderLog.logError(e); } } @Override public boolean isReadable() { return false; } /** * Shows a list of the items read from XML. * * @return Collection<IItem> the list */ @Override public Collection<IItem> getItems() { return this.items; } /** * Shows the filename that was last accessed. * * @return String the file name or URI */ @Override public String getFilename() { return this.sFilename; } }
true
true
protected void parseDocument(final Document doc) { try { PropertiesItem xItem; NodeList fileNodes, errorNodes; Integer eLine, eColumn; String eSeverity, eMessage, ePattern, sTargetFileName; Element fileElement, error; fileNodes = doc.getChildNodes().item(0).getChildNodes(); // handle all <file name=""> sections for (int fIndex = 0; fIndex < fileNodes.getLength(); fIndex++) { // ignore whitespace final int iNodeType = fileNodes.item(fIndex).getNodeType(); if (iNodeType == Node.ELEMENT_NODE) { fileElement = (Element) fileNodes.item(fIndex); sTargetFileName = fileElement.getAttribute("name"); CinderLog.logDebug("XIR::read:" + sTargetFileName); errorNodes = fileElement.getChildNodes(); // handle all <error line="" column="" severity="" // message="" pattern=""> sections for (int eIndex = 0; eIndex < errorNodes.getLength(); eIndex++) { // ignore whitespace if (errorNodes.item(eIndex).getNodeType() == Node.ELEMENT_NODE) { error = (Element) errorNodes.item(eIndex); eLine = Integer.valueOf(error.getAttribute("line")); eColumn = Integer.valueOf(error .getAttribute("column")); eSeverity = error.getAttribute("severity"); eMessage = error.getAttribute("message"); ePattern = error.getAttribute("pattern"); CinderLog.logDebug("XIR:" + eLine + ":" + eColumn + ":" + eSeverity); xItem = new PropertiesItem(ePattern, sTargetFileName, PropertiesItem.chooseType(eSeverity), eLine.intValue(), eColumn.intValue()); xItem.setMessage(eMessage); items.add(xItem); } } } } } catch (Exception e) { CinderLog.logError(e); } }
protected void parseDocument(final Document doc) { try { PropertiesItem xItem; NodeList fileNodes, errorNodes; Integer eLine, eColumn; String eSeverity, eMessage, ePattern, sTargetFileName; Element fileElement, error; fileNodes = doc.getElementsByTagName("padawan").item(0).getChildNodes(); // handle all <file name=""> sections for (int fIndex = 0; fIndex < fileNodes.getLength(); fIndex++) { // ignore whitespace final int iNodeType = fileNodes.item(fIndex).getNodeType(); if (iNodeType == Node.ELEMENT_NODE) { fileElement = (Element) fileNodes.item(fIndex); sTargetFileName = fileElement.getAttribute("name"); CinderLog.logDebug("XIR::read:" + sTargetFileName); errorNodes = fileElement.getChildNodes(); // handle all <error line="" column="" severity="" // message="" pattern=""> sections for (int eIndex = 0; eIndex < errorNodes.getLength(); eIndex++) { // ignore whitespace if (errorNodes.item(eIndex).getNodeType() == Node.ELEMENT_NODE) { error = (Element) errorNodes.item(eIndex); eLine = Integer.valueOf(error.getAttribute("line")); eColumn = Integer.valueOf(error .getAttribute("column")); eSeverity = error.getAttribute("severity"); eMessage = error.getAttribute("message"); ePattern = error.getAttribute("pattern"); CinderLog.logDebug("XIR:" + eLine + ":" + eColumn + ":" + eSeverity); xItem = new PropertiesItem(ePattern, sTargetFileName, PropertiesItem.chooseType(eSeverity), eLine.intValue(), eColumn.intValue()); xItem.setMessage(eMessage); items.add(xItem); } } } } } catch (Exception e) { CinderLog.logError(e); } }
diff --git a/src/com/madgear/ninjatrials/ResultWinScene.java b/src/com/madgear/ninjatrials/ResultWinScene.java index 7e1765c..2747273 100644 --- a/src/com/madgear/ninjatrials/ResultWinScene.java +++ b/src/com/madgear/ninjatrials/ResultWinScene.java @@ -1,441 +1,441 @@ /* * Ninja Trials is an old school style Android Game developed for OUYA & using * AndEngine. It features several minigames with simple gameplay. * Copyright 2013 Mad Gear Games <[email protected]> * * 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.madgear.ninjatrials; import org.andengine.engine.handler.IUpdateHandler; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.entity.Entity; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.SpriteBackground; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.sprite.TiledSprite; import org.andengine.entity.text.Text; import org.andengine.entity.text.TextOptions; import org.andengine.util.adt.align.HorizontalAlign; import android.util.Log; import com.madgear.ninjatrials.managers.GameManager; import com.madgear.ninjatrials.managers.ResourceManager; import com.madgear.ninjatrials.managers.SceneManager; import com.madgear.ninjatrials.test.TestingScene; import com.madgear.ninjatrials.trials.TrialSceneCut; import com.madgear.ninjatrials.trials.TrialSceneJump; import com.madgear.ninjatrials.trials.TrialSceneRun; import com.madgear.ninjatrials.trials.TrialSceneShuriken; /** * This class shows the trial results, and adds the trial score to the total game score. * @author Madgear Games * */ public class ResultWinScene extends GameScene { public final static int STAMP_THUG = 0; public final static int STAMP_NINJA = 1; public final static int STAMP_NINJA_MASTER = 2; public final static int STAMP_GRAND_MASTER = 3; private final static float WIDTH = ResourceManager.getInstance().cameraWidth; private final static float HEIGHT = ResourceManager.getInstance().cameraHeight; private static final int MAX_SCORE_ITEMS = 5; private static final float POS_X_LEFT_SCORE = 600f; private static final float SCORE_ROW_HEIGHT = HEIGHT - 380; protected static final float SCORE_ROW_GAP = 80; private Text tittleText; private String tittle; private SpriteBackground bg; private Sprite characterSprite; private Sprite scroll; private TiledSprite drawings; private TiledSprite stamp; private boolean pressEnabled = true; private GrowingScore growingScore; private int scoreItemsNumber; private int scoreItemArrayIndex; private ScoreItem[] scoreItemArray; private TimerHandler timerHandler; private IUpdateHandler updateHandler; private int drawingIndex; public ResultWinScene() { super(0f); // 0 = no loading screen. } @Override public Scene onLoadingScreenLoadAndShown() { return null; } @Override public void onLoadingScreenUnloadAndHidden() {} @SuppressWarnings("static-access") @Override public void onLoadScene() { ResourceManager.getInstance().loadResultWinResources(); } @SuppressWarnings("static-access") @Override public void onShowScene() { if (GameManager.DEBUG_MODE == true) loadTestData(); // Background: bg = new SpriteBackground(new Sprite(WIDTH/2, HEIGHT/2, ResourceManager.getInstance().winBg, ResourceManager.getInstance().engine.getVertexBufferObjectManager())); setBackground(bg); // Scroll: scroll = new Sprite(WIDTH/2, HEIGHT/2, ResourceManager.getInstance().winScroll, ResourceManager.getInstance().engine.getVertexBufferObjectManager()); attachChild(scroll); // Drawings: drawings = new TiledSprite(WIDTH/2, HEIGHT/2, ResourceManager.getInstance().winDrawings, ResourceManager.getInstance().engine.getVertexBufferObjectManager()); drawings.setVisible(false); attachChild(drawings); // Stamp: stamp = new TiledSprite(750, HEIGHT - 850, ResourceManager.getInstance().winStampRanking, ResourceManager.getInstance().engine.getVertexBufferObjectManager()); stamp.setVisible(false); attachChild(stamp); // Trial Name: tittleText = new Text(WIDTH/2, HEIGHT - 200, ResourceManager.getInstance().fontBig, "TRIAL NAME PLACE HOLDER", new TextOptions(HorizontalAlign.CENTER), ResourceManager.getInstance().engine.getVertexBufferObjectManager()); tittleText.setVisible(false); attachChild(tittleText); // Character: if(GameManager.getSelectedCharacter() == GameManager.CHAR_SHO) { characterSprite = new Sprite(300, HEIGHT - 690, ResourceManager.getInstance().winCharSho, ResourceManager.getInstance().engine.getVertexBufferObjectManager()); } else { characterSprite = new Sprite(300, HEIGHT - 690, ResourceManager.getInstance().winCharRyoko, ResourceManager.getInstance().engine.getVertexBufferObjectManager()); } attachChild(characterSprite); // Total Score: growingScore = new GrowingScore(POS_X_LEFT_SCORE, HEIGHT - 670, 0); attachChild(growingScore); prepareResults(); } @Override public void onHideScene() {} @SuppressWarnings("static-access") @Override public void onUnloadScene() { ResourceManager.getInstance().unloadResultWinResources(); } // ------------------------------------------------------- /** * Loads the testing data in debug mode. */ private void loadTestData() { GameManager.setCurrentTrial(GameManager.TRIAL_CUT); GameManager.player1result.cutConcentration = 99; GameManager.player1result.cutRound = 3; } /** * Prepare the results data before showing them. * We must keep control for the drawing in the scroll, trial name, type of stamp and number * of rows for score items. */ private void prepareResults() { // Score Items: // We store a row for each score line in the results (for example time, concentration...). scoreItemArray = new ScoreItem[MAX_SCORE_ITEMS]; switch(GameManager.getCurrentTrial()) { case GameManager.TRIAL_RUN: tittleText.setText("Run Results"); drawings.setCurrentTileIndex(2); stamp.setCurrentTileIndex(TrialSceneRun.getStamp(TrialSceneRun.getScore())); scoreItemsNumber = 4; scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.runTime), TrialSceneRun.getTimeScore()); scoreItemArray[1] = new ScoreItem("Max Speed Combo", String.valueOf(GameManager.player1result.runMaxSpeedCombo), TrialSceneRun.getMaxSpeedComboScore()); scoreItemArray[2] = new ScoreItem("Max Speed Combo Total", String.valueOf(GameManager.player1result.runMaxSpeedComboTotal), TrialSceneRun.getMaxSpeedComboTotalScore()); scoreItemArray[3] = new ScoreItem("Max Speed", String.valueOf(GameManager.player1result.runMaxSpeed), TrialSceneRun.getMaxSpeedScore()); break; case GameManager.TRIAL_CUT: tittleText.setText("Cut Results"); drawings.setCurrentTileIndex(3); stamp.setCurrentTileIndex(TrialSceneCut.getStamp(TrialSceneCut.getScore())); scoreItemsNumber = 2; scoreItemArray[0] = new ScoreItem("Rounds", String.valueOf(GameManager.player1result.cutRound), TrialSceneCut.getRoundScore()); scoreItemArray[1] = new ScoreItem("Concentratation", String.valueOf(GameManager.player1result.cutConcentration), TrialSceneCut.getConcentrationScore()); break; case GameManager.TRIAL_JUMP: tittleText.setText("Jump Results"); drawings.setCurrentTileIndex(0); stamp.setCurrentTileIndex(TrialSceneJump.getStamp(TrialSceneJump.getScore())); scoreItemsNumber = 3; scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.jumpTime), TrialSceneJump.getTimeScore()); scoreItemArray[1] = new ScoreItem("Perfect Jump Combo", String.valueOf(GameManager.player1result.jumpPerfectJumpCombo), TrialSceneJump.getPerfectJumpScore()); scoreItemArray[2] = new ScoreItem("Max Perfect Jump Combo", String.valueOf(GameManager.player1result.jumpMaxPerfectJumpCombo), TrialSceneJump.getMaxPerfectJumpScore()); break; case GameManager.TRIAL_SHURIKEN: tittleText.setText("Shuriken Results"); drawings.setCurrentTileIndex(1); stamp.setCurrentTileIndex(TrialSceneShuriken.getStamp(TrialSceneShuriken.getScore())); scoreItemsNumber = 2; - scoreItemArray[0] = new ScoreItem("Rounds", + scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.shurikenTime), TrialSceneShuriken.getTimeScore()); - scoreItemArray[1] = new ScoreItem("Concentratation", + scoreItemArray[1] = new ScoreItem("Precission", String.valueOf(GameManager.player1result.shurikenPrecission), TrialSceneShuriken.getPrecissionScore()); break; } } /** * Show one score item each time, and the growing score. * Finally adds the score to the main game score. */ private void showResults() { drawings.setVisible(true); tittleText.setVisible(true); stamp.setVisible(true); scoreItemArrayIndex = 0; updateHandler = new IUpdateHandler() { @Override public void onUpdate(float pSecondsElapsed) { if(growingScore.isFinished()) if(scoreItemArrayIndex < scoreItemsNumber) { growingScore.addScore(scoreItemArray[scoreItemArrayIndex].addedPoints); addScoreLine(SCORE_ROW_HEIGHT - SCORE_ROW_GAP * scoreItemArrayIndex, scoreItemArray[scoreItemArrayIndex].description, scoreItemArray[scoreItemArrayIndex].value); scoreItemArrayIndex++; } else { // No more rows to show. ResultWinScene.this.unregisterUpdateHandler(updateHandler); } } @Override public void reset() {} }; registerUpdateHandler(updateHandler); // Add the trial score to the total score: GameManager.incrementScore(TrialSceneCut.getScore()); } /** * If it is the final trial then go to the ending scene. If there are more trials to complete * then go to the map scene (and set the current trial to the next one). */ private void endingSequence() { if(GameManager.getCurrentTrial() == GameManager.TRIAL_FINAL) // TODO: SceneManager.getInstance().showScene(new EndingScene()); SceneManager.getInstance().showScene(new TestingScene()); else // TODO: SceneManager.getInstance().showScene(new MapScene()); GameManager.setCurrentTrial(GameManager.nextTrial(GameManager.getCurrentTrial())); SceneManager.getInstance().showScene(new TestingScene()); } /** * Add a new score row to the scroll. * @param y The Y position of the score line. * @param description The score item description, like "Jump Time", "Shuriken Precission", etc. * @param value The item value like "34 sec", or "67%". */ private void addScoreLine(float y, String description, String value) { Text descriptionText = new Text(WIDTH/2, y, ResourceManager.getInstance().fontSmall, description, new TextOptions(HorizontalAlign.CENTER), ResourceManager.getInstance().engine.getVertexBufferObjectManager()); attachChild(descriptionText); Text valueText = new Text(POS_X_LEFT_SCORE, y, ResourceManager.getInstance().fontSmall, value, new TextOptions(HorizontalAlign.CENTER), ResourceManager.getInstance().engine.getVertexBufferObjectManager()); attachChild(valueText); } // INTERFACE -------------------------------------------------------- /** * If the score hasn't finished, then finalize it now, else go to the end sequence. */ @Override public void onPressButtonO() { if(pressEnabled) { if(growingScore.isFinished()) endingSequence(); else growingScore.finalize(); } } // AUXILIARY CLASSES ------------------------------------------------- /** * This class represents a score number that can grow along time and shows it in the screen. * @author Madgear Games */ private class GrowingScore extends Entity { private int startingScore; private int currentScore; private int finalScore; private Text scoreText; private final static int POINTS_PER_SECOND = 1000; private boolean sumFinished = true; /** * Create the text item and initializes the class fields. * @param x The x position in the screen. * @param y The y position in the screen. * @param s Starting score (normally 0). */ public GrowingScore(float x, float y, int s) { startingScore = s; currentScore = startingScore; scoreText = new Text(x, y, ResourceManager.getInstance().fontMedium, "GROWING SCORE PLACE HOLDER", new TextOptions(HorizontalAlign.CENTER), ResourceManager.getInstance().engine.getVertexBufferObjectManager()); scoreText.setText(Integer.toString(startingScore)); attachChild(scoreText); setIgnoreUpdate(true); } /** * Adds points to the score. Tells the class than can be updated. * @param points Number of points to add to the score. */ public void addScore(int points) { sumFinished = false; finalScore = (int)currentScore + points; setIgnoreUpdate(false); } /** * Tell the class to end the update and set the score to the final value. */ public void finalize() { currentScore = finalScore; scoreText.setText(Integer.toString(currentScore)); sumFinished = true; setIgnoreUpdate(true); } /** * Update the score and show it on the screen while it is growing. * If it reach the final value then stops. */ @Override protected void onManagedUpdate(final float pSecondsElapsed) { if(currentScore < finalScore) { scoreText.setText(Integer.toString(currentScore)); currentScore = Math.round(currentScore + pSecondsElapsed * POINTS_PER_SECOND); } else { finalize(); } super.onManagedUpdate(pSecondsElapsed); } /** * Tells us if all the points has been added. * @return False if the score is growing yet, else return true. */ public boolean isFinished() { return sumFinished; } } /** * Keeps data about a score row. The scene uses an array of them to store the information * about trial results. * Example: in the cut scene, the score item "concentraton" whould be: * descripton = "Concentration" * value = "89%" * addedPoints = 8455 * * @author Madgear Games */ private class ScoreItem { String description, value; int addedPoints; public ScoreItem(String d, String v, int p) { description = d; value = v; addedPoints = p; } } }
false
true
private void prepareResults() { // Score Items: // We store a row for each score line in the results (for example time, concentration...). scoreItemArray = new ScoreItem[MAX_SCORE_ITEMS]; switch(GameManager.getCurrentTrial()) { case GameManager.TRIAL_RUN: tittleText.setText("Run Results"); drawings.setCurrentTileIndex(2); stamp.setCurrentTileIndex(TrialSceneRun.getStamp(TrialSceneRun.getScore())); scoreItemsNumber = 4; scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.runTime), TrialSceneRun.getTimeScore()); scoreItemArray[1] = new ScoreItem("Max Speed Combo", String.valueOf(GameManager.player1result.runMaxSpeedCombo), TrialSceneRun.getMaxSpeedComboScore()); scoreItemArray[2] = new ScoreItem("Max Speed Combo Total", String.valueOf(GameManager.player1result.runMaxSpeedComboTotal), TrialSceneRun.getMaxSpeedComboTotalScore()); scoreItemArray[3] = new ScoreItem("Max Speed", String.valueOf(GameManager.player1result.runMaxSpeed), TrialSceneRun.getMaxSpeedScore()); break; case GameManager.TRIAL_CUT: tittleText.setText("Cut Results"); drawings.setCurrentTileIndex(3); stamp.setCurrentTileIndex(TrialSceneCut.getStamp(TrialSceneCut.getScore())); scoreItemsNumber = 2; scoreItemArray[0] = new ScoreItem("Rounds", String.valueOf(GameManager.player1result.cutRound), TrialSceneCut.getRoundScore()); scoreItemArray[1] = new ScoreItem("Concentratation", String.valueOf(GameManager.player1result.cutConcentration), TrialSceneCut.getConcentrationScore()); break; case GameManager.TRIAL_JUMP: tittleText.setText("Jump Results"); drawings.setCurrentTileIndex(0); stamp.setCurrentTileIndex(TrialSceneJump.getStamp(TrialSceneJump.getScore())); scoreItemsNumber = 3; scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.jumpTime), TrialSceneJump.getTimeScore()); scoreItemArray[1] = new ScoreItem("Perfect Jump Combo", String.valueOf(GameManager.player1result.jumpPerfectJumpCombo), TrialSceneJump.getPerfectJumpScore()); scoreItemArray[2] = new ScoreItem("Max Perfect Jump Combo", String.valueOf(GameManager.player1result.jumpMaxPerfectJumpCombo), TrialSceneJump.getMaxPerfectJumpScore()); break; case GameManager.TRIAL_SHURIKEN: tittleText.setText("Shuriken Results"); drawings.setCurrentTileIndex(1); stamp.setCurrentTileIndex(TrialSceneShuriken.getStamp(TrialSceneShuriken.getScore())); scoreItemsNumber = 2; scoreItemArray[0] = new ScoreItem("Rounds", String.valueOf(GameManager.player1result.shurikenTime), TrialSceneShuriken.getTimeScore()); scoreItemArray[1] = new ScoreItem("Concentratation", String.valueOf(GameManager.player1result.shurikenPrecission), TrialSceneShuriken.getPrecissionScore()); break; } }
private void prepareResults() { // Score Items: // We store a row for each score line in the results (for example time, concentration...). scoreItemArray = new ScoreItem[MAX_SCORE_ITEMS]; switch(GameManager.getCurrentTrial()) { case GameManager.TRIAL_RUN: tittleText.setText("Run Results"); drawings.setCurrentTileIndex(2); stamp.setCurrentTileIndex(TrialSceneRun.getStamp(TrialSceneRun.getScore())); scoreItemsNumber = 4; scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.runTime), TrialSceneRun.getTimeScore()); scoreItemArray[1] = new ScoreItem("Max Speed Combo", String.valueOf(GameManager.player1result.runMaxSpeedCombo), TrialSceneRun.getMaxSpeedComboScore()); scoreItemArray[2] = new ScoreItem("Max Speed Combo Total", String.valueOf(GameManager.player1result.runMaxSpeedComboTotal), TrialSceneRun.getMaxSpeedComboTotalScore()); scoreItemArray[3] = new ScoreItem("Max Speed", String.valueOf(GameManager.player1result.runMaxSpeed), TrialSceneRun.getMaxSpeedScore()); break; case GameManager.TRIAL_CUT: tittleText.setText("Cut Results"); drawings.setCurrentTileIndex(3); stamp.setCurrentTileIndex(TrialSceneCut.getStamp(TrialSceneCut.getScore())); scoreItemsNumber = 2; scoreItemArray[0] = new ScoreItem("Rounds", String.valueOf(GameManager.player1result.cutRound), TrialSceneCut.getRoundScore()); scoreItemArray[1] = new ScoreItem("Concentratation", String.valueOf(GameManager.player1result.cutConcentration), TrialSceneCut.getConcentrationScore()); break; case GameManager.TRIAL_JUMP: tittleText.setText("Jump Results"); drawings.setCurrentTileIndex(0); stamp.setCurrentTileIndex(TrialSceneJump.getStamp(TrialSceneJump.getScore())); scoreItemsNumber = 3; scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.jumpTime), TrialSceneJump.getTimeScore()); scoreItemArray[1] = new ScoreItem("Perfect Jump Combo", String.valueOf(GameManager.player1result.jumpPerfectJumpCombo), TrialSceneJump.getPerfectJumpScore()); scoreItemArray[2] = new ScoreItem("Max Perfect Jump Combo", String.valueOf(GameManager.player1result.jumpMaxPerfectJumpCombo), TrialSceneJump.getMaxPerfectJumpScore()); break; case GameManager.TRIAL_SHURIKEN: tittleText.setText("Shuriken Results"); drawings.setCurrentTileIndex(1); stamp.setCurrentTileIndex(TrialSceneShuriken.getStamp(TrialSceneShuriken.getScore())); scoreItemsNumber = 2; scoreItemArray[0] = new ScoreItem("Time", String.valueOf(GameManager.player1result.shurikenTime), TrialSceneShuriken.getTimeScore()); scoreItemArray[1] = new ScoreItem("Precission", String.valueOf(GameManager.player1result.shurikenPrecission), TrialSceneShuriken.getPrecissionScore()); break; } }
diff --git a/src/balle/bluetooth/messages/MessageDecoder.java b/src/balle/bluetooth/messages/MessageDecoder.java index 4abdaad..472b01d 100644 --- a/src/balle/bluetooth/messages/MessageDecoder.java +++ b/src/balle/bluetooth/messages/MessageDecoder.java @@ -1,38 +1,43 @@ package balle.bluetooth.messages; /** * Factory for Messages. Decodes the message from opcode. */ public class MessageDecoder { /** * Decode message. * * @param hashedMessage * the hashed message * @return An instance of particular message * @throws InvalidArgumentException * when something went horribly wrong */ - public AbstractMessage decodeMessage(int hashedMessage) throws InvalidArgumentException { + public AbstractMessage decodeMessage(int hashedMessage) + throws InvalidArgumentException { switch (AbstractMessage.extactOpcodeFromEncodedMessage(hashedMessage)) { case MessageKick.OPCODE: - int isPenalty = MessageKick.decodeArgumentsFromHash(hashedMessage); + int isPenalty = MessageKick + .decodeArgumentsFromHash(hashedMessage); return new MessageKick(isPenalty); case MessageMove.OPCODE: - int[] moveArguments = MessageMove.decodeArgumentsFromHash(hashedMessage); - return new MessageMove(moveArguments[0] - MessageMove.OFFSET, moveArguments[1] - - MessageMove.OFFSET); + int[] moveArguments = MessageMove + .decodeArgumentsFromHash(hashedMessage); + return new MessageMove(moveArguments[0] - MessageMove.OFFSET, + moveArguments[1] - MessageMove.OFFSET); case MessageRotate.OPCODE: - int[] rotateArguments = MessageRotate.decodeArgumentsFromHash(hashedMessage); - return new MessageRotate(rotateArguments[0] - MessageRotate.ANGLE_OFFSET, - rotateArguments[1] - MessageRotate.ANGLE_OFFSET); + int[] rotateArguments = MessageRotate + .decodeArgumentsFromHash(hashedMessage); + return new MessageRotate(rotateArguments[0] + - MessageRotate.ANGLE_OFFSET, rotateArguments[1]); case MessageStop.OPCODE: - int floatWheels = MessageStop.decodeArgumentsFromHash(hashedMessage); + int floatWheels = MessageStop + .decodeArgumentsFromHash(hashedMessage); return new MessageStop(floatWheels); default: // Unknown type return null; } } }
false
true
public AbstractMessage decodeMessage(int hashedMessage) throws InvalidArgumentException { switch (AbstractMessage.extactOpcodeFromEncodedMessage(hashedMessage)) { case MessageKick.OPCODE: int isPenalty = MessageKick.decodeArgumentsFromHash(hashedMessage); return new MessageKick(isPenalty); case MessageMove.OPCODE: int[] moveArguments = MessageMove.decodeArgumentsFromHash(hashedMessage); return new MessageMove(moveArguments[0] - MessageMove.OFFSET, moveArguments[1] - MessageMove.OFFSET); case MessageRotate.OPCODE: int[] rotateArguments = MessageRotate.decodeArgumentsFromHash(hashedMessage); return new MessageRotate(rotateArguments[0] - MessageRotate.ANGLE_OFFSET, rotateArguments[1] - MessageRotate.ANGLE_OFFSET); case MessageStop.OPCODE: int floatWheels = MessageStop.decodeArgumentsFromHash(hashedMessage); return new MessageStop(floatWheels); default: // Unknown type return null; } }
public AbstractMessage decodeMessage(int hashedMessage) throws InvalidArgumentException { switch (AbstractMessage.extactOpcodeFromEncodedMessage(hashedMessage)) { case MessageKick.OPCODE: int isPenalty = MessageKick .decodeArgumentsFromHash(hashedMessage); return new MessageKick(isPenalty); case MessageMove.OPCODE: int[] moveArguments = MessageMove .decodeArgumentsFromHash(hashedMessage); return new MessageMove(moveArguments[0] - MessageMove.OFFSET, moveArguments[1] - MessageMove.OFFSET); case MessageRotate.OPCODE: int[] rotateArguments = MessageRotate .decodeArgumentsFromHash(hashedMessage); return new MessageRotate(rotateArguments[0] - MessageRotate.ANGLE_OFFSET, rotateArguments[1]); case MessageStop.OPCODE: int floatWheels = MessageStop .decodeArgumentsFromHash(hashedMessage); return new MessageStop(floatWheels); default: // Unknown type return null; } }